KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > sample > jms > files > FileTransfer


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

65
66
67 public class FileTransfer implements javax.jms.MessageListener JavaDoc{
68 private static final int MESSAGE_TTL = 6000000;
69
70 private javax.jms.QueueConnection JavaDoc con = null;
71 private javax.jms.QueueSession JavaDoc sendSession = null;
72 private javax.jms.QueueSession JavaDoc receiveSession = null;
73 private javax.jms.QueueSender JavaDoc sender = null;
74
75 private MantaFileMessage fileInPipe;
76
77 /** Create JMS client for sending and receiving messages. */
78 private void transfer(String JavaDoc userName, String JavaDoc rQueue, String JavaDoc sQueue)
79 {
80     // Create a connection and sessions.
81
try
82     {
83         QueueConnectionFactory JavaDoc conFactory = (QueueConnectionFactory JavaDoc) new MantaQueueConnectionFactory();
84
85         //Set up the JMS objects needed
86
con = conFactory.createQueueConnection();
87
88         //This session is not transacted.
89
sendSession =(QueueSession JavaDoc) con.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
90         receiveSession =(QueueSession JavaDoc) con.createQueueSession(false,Session.AUTO_ACKNOWLEDGE);
91
92     }
93     catch (javax.jms.JMSException JavaDoc jmse)
94     {
95         jmse.printStackTrace();
96         waitForAnyKey();
97
98         try {
99             System.in.read();
100         } catch (IOException JavaDoc e) {
101             e.printStackTrace();
102         }
103
104         System.exit(1);
105     }
106
107     // Create Receiver on 'rQueue' Queue
108
try
109     {
110         if (sQueue != null)
111         {
112             javax.jms.Queue JavaDoc sendQueue = sendSession.createQueue (sQueue);
113             sender = sendSession.createSender(sendQueue);
114         }
115         if (rQueue != null)
116         {
117             javax.jms.Queue JavaDoc receiveQueue = receiveSession.createQueue (rQueue);
118             javax.jms.QueueReceiver JavaDoc qReceiver = receiveSession.createReceiver(receiveQueue);
119             qReceiver.setMessageListener(this);
120             // Now that 'receive' setup is complete, start the Connection
121
//enable message transfer
122
System.out.println ("\nStart receiving messages on queue \"" + rQueue + "\".\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 the full path of the file to be transfered and commit the transfer.
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 the file to send to queue \"" + sQueue + "\".");
139             System.out.println("Press Enter to send the file.");
140
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.startsWith("upload")&& sQueue != null)
161             {
162                 s = s.substring(s.indexOf("upload")+6);
163                 s = s.trim();
164                 if(s.length() == 0)
165                     continue;
166                 MantaFileMessage msg = new MantaFileMessage();
167                 msg.load(s);
168                 // for non PERSISTENT see Talk (hint: use NON_PERSISTENT flag)
169
// Hold messages for MESSAGE_TTL millisecs.
170
sender.send( msg,
171                              javax.jms.DeliveryMode.NON_PERSISTENT,
172                              javax.jms.Message.DEFAULT_PRIORITY,
173                              MESSAGE_TTL);
174             }else if ( s.startsWith("save")&& sQueue != null)
175             {
176                 s = s.substring(s.indexOf("save")+4);
177                 s = s.trim();
178                 if(s.length() == 0)
179                     continue;
180                 if(fileInPipe == null){
181                     System.out.println( "No file is waiting to be saved" );
182                     continue;
183                 }
184                 fileInPipe.save(s);
185                 fileInPipe = null;
186             }else{
187                 System.out.println( "Valid commands are upload <path> and save <path>" );
188             }
189         }
190     }
191     catch ( java.io.IOException JavaDoc ioe )
192     {
193         ioe.printStackTrace();
194     }
195     catch ( javax.jms.JMSException JavaDoc jmse )
196     {
197         jmse.printStackTrace();
198     }
199     // Close the connection.
200
exit();
201 }
202
203 /**
204  * Handle the message
205  * (as specified in the javax.jms.MessageListener interface).
206  */

207 public void onMessage( javax.jms.Message JavaDoc aMessage)
208 {
209     try
210     {
211         // Cast the message as a text message.
212
fileInPipe = (MantaFileMessage) aMessage;
213
214         // This handler reads a single String from the
215
// message and prints it to the standard output.
216

217             String JavaDoc fileName = fileInPipe.getFileName();
218             if(fileName!=null){
219                 System.out.println( "File '"+fileName+"' waiting to be saved" );
220                 System.out.println( "Type save <path> to save file" );
221             }
222
223
224     }
225     catch (Throwable JavaDoc t)
226     {
227         t.printStackTrace();
228     }
229 }
230
231 /** Cleanup resources and then exit. */
232 private void exit()
233 {
234     try
235     {
236         con.close();
237     }
238     catch (javax.jms.JMSException JavaDoc jmse)
239     {
240         jmse.printStackTrace();
241     }
242
243     System.exit(0);
244 }
245
246 //
247
// NOTE: the remainder of this sample deals with reading arguments
248
// and does not utilize any JMS classes or code.
249
//
250

251 /** Main program entry point. */
252 public static void main(String JavaDoc argv[]) {
253
254     // Is there anything to do?
255
if (argv.length == 0) {
256         printHelp();
257         waitForAnyKey();
258         System.exit(1);
259     }
260
261     // Values to be read from parameters
262

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