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 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  import org.apache.commons.net.tftp.TFTP;
28  import org.apache.commons.net.tftp.TFTPClient;
29  import org.apache.commons.net.tftp.TFTPPacket;
30  
31  /***
32   * This is an example of a simple Java tftp client.
33   * Notice how all of the code is really just argument processing and
34   * error handling.
35   * <p>
36   * Usage: tftp [options] hostname localfile remotefile
37   * hostname   - The name of the remote host, with optional :port
38   * localfile  - The name of the local file to send or the name to use for
39   *              the received file
40   * remotefile - The name of the remote file to receive or the name for
41   *              the remote server to use to name the local file being sent.
42   * options: (The default is to assume -r -b)
43   *        -s Send a local file
44   *        -r Receive a remote file
45   *        -a Use ASCII transfer mode
46   *        -b Use binary transfer mode
47   ***/
48  public final class TFTPExample
49  {
50      static final String USAGE =
51          "Usage: tftp [options] hostname localfile remotefile\n\n" +
52          "hostname   - The name of the remote host [:port]\n" +
53          "localfile  - The name of the local file to send or the name to use for\n" +
54          "\tthe received file\n" +
55          "remotefile - The name of the remote file to receive or the name for\n" +
56          "\tthe remote server to use to name the local file being sent.\n\n" +
57          "options: (The default is to assume -r -b)\n" +
58          "\t-t timeout in seconds (default 60s)\n" +
59          "\t-s Send a local file\n" +
60          "\t-r Receive a remote file\n" +
61          "\t-a Use ASCII transfer mode\n" +
62          "\t-b Use binary transfer mode\n" +
63          "\t-v Verbose (trace packets)\n"
64          ;
65  
66      public static void main(String[] args)
67      {
68          boolean receiveFile = true, closed;
69          int transferMode = TFTP.BINARY_MODE, argc;
70          String arg, hostname, localFilename, remoteFilename;
71          final TFTPClient tftp;
72          int timeout = 60000;
73          boolean verbose = false;
74  
75          // Parse options
76          for (argc = 0; argc < args.length; argc++)
77          {
78              arg = args[argc];
79              if (arg.startsWith("-"))
80              {
81                  if (arg.equals("-r")) {
82                      receiveFile = true;
83                  } else if (arg.equals("-s")) {
84                      receiveFile = false;
85                  } else if (arg.equals("-a")) {
86                      transferMode = TFTP.ASCII_MODE;
87                  } else if (arg.equals("-b")) {
88                      transferMode = TFTP.BINARY_MODE;
89                  } else if (arg.equals("-t")) {
90                      timeout = 1000*Integer.parseInt(args[++argc]);
91                  } else if (arg.equals("-v")) {
92                      verbose = true;
93                  } else {
94                      System.err.println("Error: unrecognized option.");
95                      System.err.print(USAGE);
96                      System.exit(1);
97                  }
98              } else {
99                  break;
100             }
101         }
102 
103         // Make sure there are enough arguments
104         if (args.length - argc != 3)
105         {
106             System.err.println("Error: invalid number of arguments.");
107             System.err.print(USAGE);
108             System.exit(1);
109         }
110 
111         // Get host and file arguments
112         hostname = args[argc];
113         localFilename = args[argc + 1];
114         remoteFilename = args[argc + 2];
115 
116         // Create our TFTP instance to handle the file transfer.
117         if (verbose) {
118             tftp = new TFTPClient() {
119                 @Override
120                 protected void trace(String direction, TFTPPacket packet) {
121                     System.out.println(direction + " " + packet);
122                 }
123             };
124         } else {
125             tftp = new TFTPClient();
126         }
127 
128         // We want to timeout if a response takes longer than 60 seconds
129         tftp.setDefaultTimeout(timeout);
130 
131         // We haven't closed the local file yet.
132         closed = false;
133 
134         // If we're receiving a file, receive, otherwise send.
135         if (receiveFile)
136         {
137             closed = receive(transferMode, hostname, localFilename, remoteFilename, tftp);
138         } else {
139             // We're sending a file
140             closed = send(transferMode, hostname, localFilename, remoteFilename, tftp);
141         }
142 
143         System.out.println("Recd: "+tftp.getTotalBytesReceived()+" Sent: "+tftp.getTotalBytesSent());
144 
145         if (!closed) {
146             System.out.println("Failed");
147             System.exit(1);
148         }
149 
150         System.out.println("OK");
151     }
152 
153     private static boolean send(int transferMode, String hostname, String localFilename, String remoteFilename,
154             TFTPClient tftp) {
155         boolean closed;
156         FileInputStream input = null;
157 
158         // Try to open local file for reading
159         try
160         {
161             input = new FileInputStream(localFilename);
162         }
163         catch (IOException e)
164         {
165             tftp.close();
166             System.err.println("Error: could not open local file for reading.");
167             System.err.println(e.getMessage());
168             System.exit(1);
169         }
170 
171         open(tftp);
172 
173         // Try to send local file via TFTP
174         try
175         {
176             String [] parts = hostname.split(":");
177             if (parts.length == 2) {
178                 tftp.sendFile(remoteFilename, transferMode, input, parts[0], Integer.parseInt(parts[1]));
179             } else {
180                 tftp.sendFile(remoteFilename, transferMode, input, hostname);
181             }
182         }
183         catch (UnknownHostException e)
184         {
185             System.err.println("Error: could not resolve hostname.");
186             System.err.println(e.getMessage());
187             System.exit(1);
188         }
189         catch (IOException e)
190         {
191             System.err.println("Error: I/O exception occurred while sending file.");
192             System.err.println(e.getMessage());
193             System.exit(1);
194         }
195         finally
196         {
197             // Close local socket and input file
198             closed = close(tftp, input);
199         }
200 
201         return closed;
202     }
203 
204     private static boolean receive(int transferMode, String hostname, String localFilename, String remoteFilename,
205             TFTPClient tftp) {
206         boolean closed;
207         FileOutputStream output = null;
208         File file;
209 
210         file = new File(localFilename);
211 
212         // If file exists, don't overwrite it.
213         if (file.exists())
214         {
215             System.err.println("Error: " + localFilename + " already exists.");
216             System.exit(1);
217         }
218 
219         // Try to open local file for writing
220         try
221         {
222             output = new FileOutputStream(file);
223         }
224         catch (IOException e)
225         {
226             tftp.close();
227             System.err.println("Error: could not open local file for writing.");
228             System.err.println(e.getMessage());
229             System.exit(1);
230         }
231 
232         open(tftp);
233 
234         // Try to receive remote file via TFTP
235         try
236         {
237             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 (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 (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(TFTPClient tftp, 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 (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(TFTPClient tftp) {
286         try
287         {
288             tftp.open();
289         }
290         catch (SocketException e)
291         {
292             System.err.println("Error: could not open local UDP socket.");
293             System.err.println(e.getMessage());
294             System.exit(1);
295         }
296     }
297 
298 }
299 
300