KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sample > jms > queues > guitalk > 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.guitalk;
47
48 import java.awt.BorderLayout JavaDoc;
49 import java.awt.Color JavaDoc;
50 import java.awt.Dimension JavaDoc;
51 import java.awt.event.ActionEvent JavaDoc;
52 import java.awt.event.ActionListener JavaDoc;
53 import java.awt.event.WindowAdapter JavaDoc;
54 import java.awt.event.WindowEvent JavaDoc;
55 import java.io.IOException JavaDoc;
56
57 import javax.jms.QueueConnectionFactory JavaDoc;
58 import javax.jms.QueueSession JavaDoc;
59 import javax.jms.Session JavaDoc;
60 import javax.swing.BoxLayout JavaDoc;
61 import javax.swing.JFrame JavaDoc;
62 import javax.swing.JLabel JavaDoc;
63 import javax.swing.JPanel JavaDoc;
64 import javax.swing.JScrollPane JavaDoc;
65 import javax.swing.JTextField JavaDoc;
66 import javax.swing.JTextPane JavaDoc;
67 import javax.swing.SwingUtilities JavaDoc;
68 import javax.swing.text.BadLocationException JavaDoc;
69 import javax.swing.text.Style JavaDoc;
70 import javax.swing.text.StyleConstants JavaDoc;
71 import javax.swing.text.StyleContext JavaDoc;
72 import javax.swing.text.StyledDocument JavaDoc;
73
74 import org.mr.api.jms.MantaQueueConnectionFactory;
75
76
77 /*==================================================================================
78   For instructions on how to run this sample please refer to the file
79   sample\jms\queues\guitalk\Readme.txt under the MantaRay installation directory.
80 ====================================================================================*/

81
82 public class Talk
83     implements javax.jms.MessageListener JavaDoc
84 {
85
86     private static final int MESSAGE_TTL = 6000000;
87
88     private javax.jms.QueueConnection JavaDoc con = null;
89     private javax.jms.QueueSession JavaDoc sendSession = null;
90     private javax.jms.QueueSession JavaDoc receiveSession = null;
91     private javax.jms.QueueSender JavaDoc sender = null;
92
93     private JFrame JavaDoc frame = null;
94     private JTextField JavaDoc textField = null;
95     private JTextPane JavaDoc textArea = null;
96     private StyledDocument JavaDoc doc = null;
97     private String JavaDoc username = null;
98     private String JavaDoc qSender = null;
99     private String JavaDoc qReceiver = null;
100
101     public Talk(String JavaDoc userName, String JavaDoc rQueue, String JavaDoc sQueue) {
102         this.username = userName;
103         qSender = rQueue;
104         qReceiver = sQueue;
105         createUI();
106     }
107
108     /** Create JMS client for sending and receiving messages. */
109     //private void talker(String userName, String rQueue, String sQueue)
110
private void talker()
111     {
112         // Create a connection and sessions.
113
try
114         {
115             QueueConnectionFactory JavaDoc conFactory = (QueueConnectionFactory JavaDoc) new MantaQueueConnectionFactory();
116
117             //Set up the JMS objects needed
118
con = conFactory.createQueueConnection();
119
120             //This session is not transacted.
121
sendSession =(QueueSession JavaDoc) con.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
122             receiveSession =(QueueSession JavaDoc) con.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
123
124         }
125         catch (javax.jms.JMSException JavaDoc jmse)
126         {
127             jmse.printStackTrace();
128             waitForAnyKey();
129
130             try {
131                 System.in.read();
132             } catch (IOException JavaDoc e) {
133                 e.printStackTrace();
134             }
135
136             System.exit(1);
137         }
138
139         // Create Receiver and Sender on 'Talk' queues
140
try
141         {
142             javax.jms.Queue JavaDoc sendQueue = sendSession.createQueue (qSender);
143             sender = sendSession.createSender(sendQueue);
144             javax.jms.Queue JavaDoc receiveQueue = receiveSession.createQueue (qReceiver);
145             javax.jms.QueueReceiver JavaDoc qReceiver = receiveSession.createReceiver(receiveQueue);
146             qReceiver.setMessageListener(this);
147             // Now that 'receive' setup is complete, start the Connection
148
//enable message transfer
149
System.out.println ("\nStart receiving messages on queue \"" + qReceiver + "\".\n");
150             con.start();
151         }
152         catch (javax.jms.JMSException JavaDoc jmse)
153         {
154             jmse.printStackTrace();
155             exit();
156         }
157     }
158
159     // creates the GUI of the program
160
private void createUI() {
161         frame = new JFrame JavaDoc("Talk Client");
162         JPanel JavaDoc panel = new JPanel JavaDoc();
163         frame.setContentPane(panel);
164         panel.setLayout(new BorderLayout JavaDoc(5, 5));
165
166         // create the text area
167
textArea = new JTextPane JavaDoc();
168         doc = textArea.getStyledDocument();
169         Style JavaDoc defaultStyle = StyleContext.getDefaultStyleContext().getStyle(StyleContext.DEFAULT_STYLE);
170         Style JavaDoc localStyle = doc.addStyle("local", defaultStyle);
171         StyleConstants.setBold(localStyle, true);
172         StyleConstants.setForeground(localStyle, Color.blue);
173         Style JavaDoc remoteStyle = doc.addStyle("remote", defaultStyle);
174         StyleConstants.setBold(remoteStyle, true);
175         StyleConstants.setForeground(remoteStyle, Color.green);
176         JScrollPane JavaDoc areaScroll = new JScrollPane JavaDoc(textArea, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
177         areaScroll.setPreferredSize(new Dimension JavaDoc(250, 145));
178         panel.add(areaScroll, BorderLayout.CENTER);
179
180         // create the text field
181
JPanel JavaDoc inputPanel = new JPanel JavaDoc();
182         inputPanel.setLayout(new BoxLayout JavaDoc(inputPanel, BoxLayout.X_AXIS));
183         inputPanel.add(new JLabel JavaDoc("Text: "));
184         textField = new JTextField JavaDoc();
185         textField.addActionListener(new ActionListener JavaDoc() {
186             public void actionPerformed(ActionEvent JavaDoc e) {
187                 String JavaDoc text = textField.getText();
188                 if (text == null) return;
189                 text = text.trim();
190                 if (text.length() == 0) return;
191                 String JavaDoc msgText = username + "> " + text;
192                 try {
193                     if (qSender != null) {
194                         javax.jms.TextMessage JavaDoc msg = sendSession.createTextMessage();
195                         msg.setText(msgText);
196                         // for PERSISTENT see ReliableTalk (hint: use PERSISTENT flag)
197
// Hold messages for MESSAGE_TTL millisecs.
198
sender.send( msg,
199                                      javax.jms.DeliveryMode.NON_PERSISTENT,
200                                      javax.jms.Message.DEFAULT_PRIORITY,
201                                      MESSAGE_TTL);
202                     }
203                 }
204                 catch ( javax.jms.JMSException JavaDoc jmse )
205                 {
206                     jmse.printStackTrace();
207                 }
208
209                 try {
210                     doc.insertString(doc.getLength(), msgText+"\n", doc.getStyle("local"));
211                 }
212                 catch (BadLocationException JavaDoc ble) {ble.printStackTrace();}
213                 textField.setText("");
214                 textArea.setCaretPosition(textArea.getDocument().getLength());
215             }
216         });
217         inputPanel.add(textField);
218         panel.add(inputPanel, BorderLayout.SOUTH);
219
220         // set window close operation
221
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
222         frame.addWindowListener(new WindowAdapter JavaDoc() {
223             public void windowClosing(WindowEvent JavaDoc e) {
224                 exit();
225             }
226         });
227
228         // show the GUI
229
frame.pack();
230         
231     }
232
233     private void showGUI() {
234         SwingUtilities.invokeLater(new Runnable JavaDoc() {
235             public void run() {
236                 frame.setVisible(true);
237                 textField.requestFocus();
238             }
239         });
240     }
241
242     /**
243      * Handle the message
244      * (as specified in the javax.jms.MessageListener interface).
245      */

246     public void onMessage( javax.jms.Message JavaDoc aMessage)
247     {
248
249         try
250         {
251             // Cast the message as a text message.
252
javax.jms.TextMessage JavaDoc textMessage = (javax.jms.TextMessage JavaDoc) aMessage;
253
254             // This handler reads a single String from the
255
// message and prints it to the chat area.
256
try
257             {
258                 String JavaDoc string = textMessage.getText();
259                 doc.insertString(doc.getLength(), string+"\n", doc.getStyle("remote"));
260                 textArea.setCaretPosition(doc.getLength());
261             }
262             catch (javax.jms.JMSException JavaDoc jmse)
263             {
264                 jmse.printStackTrace();
265             }
266         }
267         catch (Throwable JavaDoc t)
268         {
269             t.printStackTrace();
270         }
271     }
272
273     /** Cleanup resources and then exit. */
274     private void exit()
275     {
276         try
277         {
278             con.close();
279         }
280         catch (javax.jms.JMSException JavaDoc jmse)
281         {
282             jmse.printStackTrace();
283         }
284         frame.dispose();
285         System.exit(0);
286     }
287
288     //
289
// NOTE: the remainder of this sample deals with reading arguments
290
// and does not utilize any JMS classes or code.
291
//
292

293     /** Main program entry point. */
294     public static void main(String JavaDoc argv[]) {
295
296         // Is there anything to do?
297
if (argv.length == 0) {
298             printHelp();
299             waitForAnyKey();
300             System.exit(1);
301         }
302
303         // Values to be read from parameters
304

305         String JavaDoc user = null;
306         String JavaDoc qSend = null;
307         String JavaDoc qReceive = null;
308
309         // Check parameters
310
for (int i = 0; i < argv.length; i++) {
311             String JavaDoc arg = argv[i];
312
313             // Options
314
if (!arg.startsWith("-")) {
315                 System.err.println ("error: unexpected argument - "+arg);
316                 printHelp();
317
318                 waitForAnyKey();
319                 System.exit(1);
320             }
321             else {
322
323                 if (arg.equals("-u")) {
324                     if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
325                         System.err.println("error: missing user name");
326                         System.exit(1);
327                     }
328                     user = argv[++i];
329                     continue;
330                 }
331
332                 if (arg.equals("-qr")) {
333                     if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
334                         System.err.println("error: missing receive queue parameter");
335                         System.exit(1);
336                     }
337                     qReceive = argv[++i];
338                     continue;
339                 }
340
341                 if (arg.equals("-qs")) {
342                     if (i == argv.length - 1 || argv[i+1].startsWith("-")) {
343                         System.err.println("error: missing send queue parameter");
344                         System.exit(1);
345                     }
346                     qSend = argv[++i];
347                     continue;
348                 }
349
350
351                 if (arg.equals("-h")) {
352                     printHelp();
353                     System.exit(1);
354                 }
355             }
356         }
357
358         // Check values read in.
359
if (user == null) {
360             System.err.println ("error: user name must be supplied");
361             printHelp();
362             System.exit(1);
363         }
364
365         if (qReceive == null || qSend == null) {
366             System.err.println ("error: receive queue and send queue must be supplied");
367             printHelp();
368             System.exit(1);
369         }
370
371         // Start the JMS client for the "Talk".
372
Talk talk = new Talk(user, qReceive, qSend);
373         talk.talker();
374         talk.showGUI();
375     }
376
377     private static void waitForAnyKey(){
378         System.out.print("Press any key ...");
379         try {
380             System.in.read();
381         } catch (IOException JavaDoc e) {
382             e.printStackTrace();
383         }
384     }
385
386     /** Prints the usage. */
387     private static void printHelp() {
388
389         StringBuffer JavaDoc use = new StringBuffer JavaDoc();
390         use.append("help: java Talk (options) ...\n\n");
391         use.append("options:\n");
392         use.append(" -qr queue Specify queue for receiving messages.\n");
393         use.append(" -qs queue Specify queue for sending messages.\n");
394         use.append(" -u user Specify a user name.\n");
395         use.append(" -h This help screen.\n");
396         System.err.println (use);
397     }
398
399 }
Popular Tags