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.FileInputStream;
021import java.io.FileOutputStream;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.io.PrintWriter;
026
027import org.apache.commons.net.PrintCommandListener;
028import org.apache.commons.net.ftp.FTP;
029import org.apache.commons.net.ftp.FTPClient;
030import org.apache.commons.net.ftp.FTPConnectionClosedException;
031import org.apache.commons.net.ftp.FTPReply;
032
033/***
034 * This is an example program demonstrating how to use the FTPClient class.
035 * This program connects to an FTP server and retrieves the specified
036 * file.  If the -s flag is used, it stores the local file at the FTP server.
037 * Just so you can see what's happening, all reply strings are printed.
038 * If the -b flag is used, a binary transfer is assumed (default is ASCII).
039 * <p>
040 * Usage: ftp [-s] [-b] <hostname> <username> <password> <remote file> <local file>
041 * <p>
042 ***/
043public final class FTPExample
044{
045
046    public static final String USAGE =
047        "Usage: ftp [-s] [-b] <hostname> <username> <password> <remote file> <local file>\n" +
048        "\nDefault behavior is to download a file and use ASCII transfer mode.\n" +
049        "\t-s store file on server (upload)\n" +
050        "\t-b use binary transfer mode\n";
051
052    public static final void main(String[] args)
053    {
054        int base = 0;
055        boolean storeFile = false, binaryTransfer = false, error = false;
056        String server, username, password, remote, local;
057        FTPClient ftp;
058
059        for (base = 0; base < args.length; base++)
060        {
061            if (args[base].startsWith("-s"))
062                storeFile = true;
063            else if (args[base].startsWith("-b"))
064                binaryTransfer = true;
065            else
066                break;
067        }
068
069        if ((args.length - base) != 5)
070        {
071            System.err.println(USAGE);
072            System.exit(1);
073        }
074
075        server = args[base++];
076        username = args[base++];
077        password = args[base++];
078        remote = args[base++];
079        local = args[base];
080
081        ftp = new FTPClient();
082        ftp.addProtocolCommandListener(new PrintCommandListener(
083                                           new PrintWriter(System.out)));
084
085        try
086        {
087            int reply;
088            ftp.connect(server);
089            System.out.println("Connected to " + server + ".");
090
091            // After connection attempt, you should check the reply code to verify
092            // success.
093            reply = ftp.getReplyCode();
094
095            if (!FTPReply.isPositiveCompletion(reply))
096            {
097                ftp.disconnect();
098                System.err.println("FTP server refused connection.");
099                System.exit(1);
100            }
101        }
102        catch (IOException e)
103        {
104            if (ftp.isConnected())
105            {
106                try
107                {
108                    ftp.disconnect();
109                }
110                catch (IOException f)
111                {
112                    // do nothing
113                }
114            }
115            System.err.println("Could not connect to server.");
116            e.printStackTrace();
117            System.exit(1);
118        }
119
120__main:
121        try
122        {
123            if (!ftp.login(username, password))
124            {
125                ftp.logout();
126                error = true;
127                break __main;
128            }
129
130            System.out.println("Remote system is " + ftp.getSystemName());
131
132            if (binaryTransfer)
133                ftp.setFileType(FTP.BINARY_FILE_TYPE);
134
135            // Use passive mode as default because most of us are
136            // behind firewalls these days.
137            ftp.enterLocalPassiveMode();
138
139            if (storeFile)
140            {
141                InputStream input;
142
143                input = new FileInputStream(local);
144
145                ftp.storeFile(remote, input);
146
147                input.close();
148            }
149            else
150            {
151                OutputStream output;
152
153                output = new FileOutputStream(local);
154
155                ftp.retrieveFile(remote, output);
156
157                output.close();
158            }
159
160            ftp.logout();
161        }
162        catch (FTPConnectionClosedException e)
163        {
164            error = true;
165            System.err.println("Server closed connection.");
166            e.printStackTrace();
167        }
168        catch (IOException e)
169        {
170            error = true;
171            e.printStackTrace();
172        }
173        finally
174        {
175            if (ftp.isConnected())
176            {
177                try
178                {
179                    ftp.disconnect();
180                }
181                catch (IOException f)
182                {
183                    // do nothing
184                }
185            }
186        }
187
188        System.exit(error ? 1 : 0);
189    } // end main
190
191}
192