001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package examples;
019
020import java.io.File;
021import java.io.FileInputStream;
022import java.io.FileOutputStream;
023import java.io.IOException;
024import java.net.SocketException;
025import java.net.UnknownHostException;
026import org.apache.commons.net.tftp.TFTP;
027import org.apache.commons.net.tftp.TFTPClient;
028
029/***
030 * This is an example of a simple Java tftp client using NetComponents.
031 * Notice how all of the code is really just argument processing and
032 * error handling.
033 * <p>
034 * Usage: tftp [options] hostname localfile remotefile
035 * hostname   - The name of the remote host
036 * localfile  - The name of the local file to send or the name to use for
037 *              the received file
038 * remotefile - The name of the remote file to receive or the name for
039 *              the remote server to use to name the local file being sent.
040 * options: (The default is to assume -r -b)
041 *        -s Send a local file
042 *        -r Receive a remote file
043 *        -a Use ASCII transfer mode
044 *        -b Use binary transfer mode
045 * <p>
046 ***/
047public final class tftp
048{
049    static final String USAGE =
050        "Usage: tftp [options] hostname localfile remotefile\n\n" +
051        "hostname   - The name of the remote host\n" +
052        "localfile  - The name of the local file to send or the name to use for\n" +
053        "\tthe received file\n" +
054        "remotefile - The name of the remote file to receive or the name for\n" +
055        "\tthe remote server to use to name the local file being sent.\n\n" +
056        "options: (The default is to assume -r -b)\n" +
057        "\t-s Send a local file\n" +
058        "\t-r Receive a remote file\n" +
059        "\t-a Use ASCII transfer mode\n" +
060        "\t-b Use binary transfer mode\n";
061
062    public final static void main(String[] args)
063    {
064        boolean receiveFile = true, closed;
065        int transferMode = TFTP.BINARY_MODE, argc;
066        String arg, hostname, localFilename, remoteFilename;
067        TFTPClient tftp;
068
069        // Parse options
070        for (argc = 0; argc < args.length; argc++)
071        {
072            arg = args[argc];
073            if (arg.startsWith("-"))
074            {
075                if (arg.equals("-r"))
076                    receiveFile = true;
077                else if (arg.equals("-s"))
078                    receiveFile = false;
079                else if (arg.equals("-a"))
080                    transferMode = TFTP.ASCII_MODE;
081                else if (arg.equals("-b"))
082                    transferMode = TFTP.BINARY_MODE;
083                else
084                {
085                    System.err.println("Error: unrecognized option.");
086                    System.err.print(USAGE);
087                    System.exit(1);
088                }
089            }
090            else
091                break;
092        }
093
094        // Make sure there are enough arguments
095        if (args.length - argc != 3)
096        {
097            System.err.println("Error: invalid number of arguments.");
098            System.err.print(USAGE);
099            System.exit(1);
100        }
101
102        // Get host and file arguments
103        hostname = args[argc];
104        localFilename = args[argc + 1];
105        remoteFilename = args[argc + 2];
106
107        // Create our TFTP instance to handle the file transfer.
108        tftp = new TFTPClient();
109
110        // We want to timeout if a response takes longer than 60 seconds
111        tftp.setDefaultTimeout(60000);
112
113        // Open local socket
114        try
115        {
116            tftp.open();
117        }
118        catch (SocketException e)
119        {
120            System.err.println("Error: could not open local UDP socket.");
121            System.err.println(e.getMessage());
122            System.exit(1);
123        }
124
125        // We haven't closed the local file yet.
126        closed = false;
127
128        // If we're receiving a file, receive, otherwise send.
129        if (receiveFile)
130        {
131            FileOutputStream output = null;
132            File file;
133
134            file = new File(localFilename);
135
136            // If file exists, don't overwrite it.
137            if (file.exists())
138            {
139                System.err.println("Error: " + localFilename + " already exists.");
140                System.exit(1);
141            }
142
143            // Try to open local file for writing
144            try
145            {
146                output = new FileOutputStream(file);
147            }
148            catch (IOException e)
149            {
150                tftp.close();
151                System.err.println("Error: could not open local file for writing.");
152                System.err.println(e.getMessage());
153                System.exit(1);
154            }
155
156            // Try to receive remote file via TFTP
157            try
158            {
159                tftp.receiveFile(remoteFilename, transferMode, output, hostname);
160            }
161            catch (UnknownHostException e)
162            {
163                System.err.println("Error: could not resolve hostname.");
164                System.err.println(e.getMessage());
165                System.exit(1);
166            }
167            catch (IOException e)
168            {
169                System.err.println(
170                    "Error: I/O exception occurred while receiving file.");
171                System.err.println(e.getMessage());
172                System.exit(1);
173            }
174            finally
175            {
176                // Close local socket and output file
177                tftp.close();
178                try
179                {
180                    output.close();
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        {
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                    input.close();
238                    closed = true;
239                }
240                catch (IOException e)
241                {
242                    closed = false;
243                    System.err.println("Error: error closing file.");
244                    System.err.println(e.getMessage());
245                }
246            }
247
248            if (!closed)
249                System.exit(1);
250
251        }
252
253    }
254
255}
256
257