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