View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  package org.apache.commons.net.examples.ftp;
19  
20  import java.io.Closeable;
21  import java.io.File;
22  import java.io.FileInputStream;
23  import java.io.FileOutputStream;
24  import java.io.IOException;
25  import java.net.SocketException;
26  import java.net.UnknownHostException;
27  
28  import org.apache.commons.net.tftp.TFTP;
29  import org.apache.commons.net.tftp.TFTPClient;
30  import org.apache.commons.net.tftp.TFTPPacket;
31  
32  /**
33   * This is an example of a simple Java tftp client.
34   * Notice how all of the code is really just argument processing and
35   * error handling.
36   * <p>
37   * Usage: tftp [options] hostname localfile remotefile
38   * hostname   - The name of the remote host, with optional :port
39   * localfile  - The name of the local file to send or the name to use for
40   *              the received file
41   * remotefile - The name of the remote file to receive or the name for
42   *              the remote server to use to name the local file being sent.
43   * options: (The default is to assume -r -b)
44   *        -s Send a local file
45   *        -r Receive a remote file
46   *        -a Use ASCII transfer mode
47   *        -b Use binary transfer mode
48   */
49  public final class TFTPExample
50  {
51      static final String USAGE =
52          "Usage: tftp [options] hostname localfile remotefile\n\n" +
53          "hostname   - The name of the remote host [:port]\n" +
54          "localfile  - The name of the local file to send or the name to use for\n" +
55          "\tthe received file\n" +
56          "remotefile - The name of the remote file to receive or the name for\n" +
57          "\tthe remote server to use to name the local file being sent.\n\n" +
58          "options: (The default is to assume -r -b)\n" +
59          "\t-t timeout in seconds (default 60s)\n" +
60          "\t-s Send a local file\n" +
61          "\t-r Receive a remote file\n" +
62          "\t-a Use ASCII transfer mode\n" +
63          "\t-b Use binary transfer mode\n" +
64          "\t-v Verbose (trace packets)\n"
65          ;
66  
67      public static void main(final String[] args)
68      {
69          boolean receiveFile = true, closed;
70          int transferMode = TFTP.BINARY_MODE, argc;
71          String arg;
72          final String hostname;
73          final String localFilename;
74          final String remoteFilename;
75          final TFTPClient tftp;
76          int timeout = 60000;
77          boolean verbose = false;
78  
79          // Parse options
80          for (argc = 0; argc < args.length; argc++)
81          {
82              arg = args[argc];
83              if (arg.startsWith("-"))
84              {
85                  if (arg.equals("-r")) {
86                      receiveFile = true;
87                  } else if (arg.equals("-s")) {
88                      receiveFile = false;
89                  } else if (arg.equals("-a")) {
90                      transferMode = TFTP.ASCII_MODE;
91                  } else if (arg.equals("-b")) {
92                      transferMode = TFTP.BINARY_MODE;
93                  } else if (arg.equals("-t")) {
94                      timeout = 1000*Integer.parseInt(args[++argc]);
95                  } else if (arg.equals("-v")) {
96                      verbose = true;
97                  } else {
98                      System.err.println("Error: unrecognized option.");
99                      System.err.print(USAGE);
100                     System.exit(1);
101                 }
102             } else {
103                 break;
104             }
105         }
106 
107         // Make sure there are enough arguments
108         if (args.length - argc != 3)
109         {
110             System.err.println("Error: invalid number of arguments.");
111             System.err.print(USAGE);
112             System.exit(1);
113         }
114 
115         // Get host and file arguments
116         hostname = args[argc];
117         localFilename = args[argc + 1];
118         remoteFilename = args[argc + 2];
119 
120         // Create our TFTP instance to handle the file transfer.
121         if (verbose) {
122             tftp = new TFTPClient() {
123                 @Override
124                 protected void trace(final String direction, final TFTPPacket packet) {
125                     System.out.println(direction + " " + packet);
126                 }
127             };
128         } else {
129             tftp = new TFTPClient();
130         }
131 
132         // We want to timeout if a response takes longer than 60 seconds
133         tftp.setDefaultTimeout(timeout);
134 
135         // We haven't closed the local file yet.
136         closed = false;
137 
138         // If we're receiving a file, receive, otherwise send.
139         if (receiveFile)
140         {
141             closed = receive(transferMode, hostname, localFilename, remoteFilename, tftp);
142         } else {
143             // We're sending a file
144             closed = send(transferMode, hostname, localFilename, remoteFilename, tftp);
145         }
146 
147         System.out.println("Recd: "+tftp.getTotalBytesReceived()+" Sent: "+tftp.getTotalBytesSent());
148 
149         if (!closed) {
150             System.out.println("Failed");
151             System.exit(1);
152         }
153 
154         System.out.println("OK");
155     }
156 
157     private static boolean send(final int transferMode, final String hostname, final String localFilename,
158             final String remoteFilename, final TFTPClient tftp) {
159         final boolean closed;
160         FileInputStream input = null;
161 
162         // Try to open local file for reading
163         try
164         {
165             input = new FileInputStream(localFilename);
166         }
167         catch (final IOException e)
168         {
169             tftp.close();
170             throw new RuntimeException("Error: could not open local file for reading.", e);
171         }
172 
173         open(tftp);
174 
175         // Try to send local file via TFTP
176         try
177         {
178             final String [] parts = hostname.split(":");
179             if (parts.length == 2) {
180                 tftp.sendFile(remoteFilename, transferMode, input, parts[0], Integer.parseInt(parts[1]));
181             } else {
182                 tftp.sendFile(remoteFilename, transferMode, input, hostname);
183             }
184         }
185         catch (final UnknownHostException e)
186         {
187             System.err.println("Error: could not resolve hostname.");
188             System.err.println(e.getMessage());
189             System.exit(1);
190         }
191         catch (final IOException e)
192         {
193             System.err.println("Error: I/O exception occurred while sending file.");
194             System.err.println(e.getMessage());
195             System.exit(1);
196         }
197         finally
198         {
199             // Close local socket and input file
200             closed = close(tftp, input);
201         }
202 
203         return closed;
204     }
205 
206     private static boolean receive(final int transferMode, final String hostname, final String localFilename,
207             final String remoteFilename, final TFTPClient tftp) {
208         final boolean closed;
209         FileOutputStream output = null;
210         final File file;
211 
212         file = new File(localFilename);
213 
214         // If file exists, don't overwrite it.
215         if (file.exists())
216         {
217             System.err.println("Error: " + localFilename + " already exists.");
218             return false;
219         }
220 
221         // Try to open local file for writing
222         try
223         {
224             output = new FileOutputStream(file);
225         }
226         catch (final IOException e)
227         {
228             tftp.close();
229             throw new RuntimeException("Error: could not open local file for writing.", e);
230         }
231 
232         open(tftp);
233 
234         // Try to receive remote file via TFTP
235         try
236         {
237             final String [] parts = hostname.split(":");
238             if (parts.length == 2) {
239                 tftp.receiveFile(remoteFilename, transferMode, output, parts[0], Integer.parseInt(parts[1]));
240             } else {
241                 tftp.receiveFile(remoteFilename, transferMode, output, hostname);
242             }
243         }
244         catch (final UnknownHostException e)
245         {
246             System.err.println("Error: could not resolve hostname.");
247             System.err.println(e.getMessage());
248             System.exit(1);
249         }
250         catch (final IOException e)
251         {
252             System.err.println(
253                 "Error: I/O exception occurred while receiving file.");
254             System.err.println(e.getMessage());
255             System.exit(1);
256         }
257         finally
258         {
259             // Close local socket and output file
260             closed = close(tftp, output);
261         }
262 
263         return closed;
264     }
265 
266     private static boolean close(final TFTPClient tftp, final Closeable output) {
267         boolean closed;
268         tftp.close();
269         try
270         {
271             if (output != null) {
272                 output.close();
273             }
274             closed = true;
275         }
276         catch (final IOException e)
277         {
278             closed = false;
279             System.err.println("Error: error closing file.");
280             System.err.println(e.getMessage());
281         }
282         return closed;
283     }
284 
285     private static void open(final TFTPClient tftp) {
286         try
287         {
288             tftp.open();
289         }
290         catch (final SocketException e)
291         {
292             throw new RuntimeException("Error: could not open local UDP socket.", e);
293         }
294     }
295 
296 }
297 
298