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