Docjar: A Java Source and Docuemnt Enginecom.*    java.*    javax.*    org.*    all    new    plug-in

Quick Search    Search Deep

Source code: org/apache/commons/net/ftp/FTPClient.java


1   /*
2    * Copyright 2001-2005 The Apache Software Foundation
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    *     http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  package org.apache.commons.net.ftp;
17  import java.io.BufferedInputStream;
18  import java.io.BufferedOutputStream;
19  import java.io.BufferedReader;
20  import java.io.IOException;
21  import java.io.InputStream;
22  import java.io.InputStreamReader;
23  import java.io.OutputStream;
24  import java.net.InetAddress;
25  import java.net.ServerSocket;
26  import java.net.Socket;
27  import java.util.Vector;
28  
29  import org.apache.commons.net.MalformedServerReplyException;
30  import org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory;
31  import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
32  import org.apache.commons.net.ftp.parser.ParserInitializationException;
33  import org.apache.commons.net.io.CopyStreamEvent;
34  import org.apache.commons.net.io.CopyStreamException;
35  import org.apache.commons.net.io.FromNetASCIIInputStream;
36  import org.apache.commons.net.io.ToNetASCIIOutputStream;
37  import org.apache.commons.net.io.Util;
38  
39  /***
40   * FTPClient encapsulates all the functionality necessary to store and
41   * retrieve files from an FTP server.  This class takes care of all
42   * low level details of interacting with an FTP server and provides
43   * a convenient higher level interface.  As with all classes derived
44   * from {@link org.apache.commons.net.SocketClient},
45   * you must first connect to the server with
46   * {@link org.apache.commons.net.SocketClient#connect  connect }
47   * before doing anything, and finally
48   * {@link org.apache.commons.net.SocketClient#disconnect  disconnect }
49   * after you're completely finished interacting with the server.
50   * Then you need to check the FTP reply code to see if the connection
51   * was successful.  For example:
52   * <pre>
53   *    boolean error = false;
54   *    try {
55   *      int reply;
56   *      ftp.connect("ftp.foobar.com");
57   *      System.out.println("Connected to " + server + ".");
58   *      System.out.print(ftp.getReplyString());
59   *
60   *      // After connection attempt, you should check the reply code to verify
61   *      // success.
62   *      reply = ftp.getReplyCode();
63   *
64   *      if(!FTPReply.isPositiveCompletion(reply)) {
65   *        ftp.disconnect();
66   *        System.err.println("FTP server refused connection.");
67   *        System.exit(1);
68   *      }
69   *      ... // transfer files
70   *      ftp.logout();
71   *    } catch(IOException e) {
72   *      error = true;
73   *      e.printStackTrace();
74   *    } finally {
75   *      if(ftp.isConnected()) {
76   *        try {
77   *          ftp.disconnect();
78   *        } catch(IOException ioe) {
79   *          // do nothing
80   *        }
81   *      }
82   *      System.exit(error ? 1 : 0);
83   *    }
84   * </pre>
85   * <p>
86   * Immediately after connecting is the only real time you need to check the
87   * reply code (because connect is of type void).  The convention for all the
88   * FTP command methods in FTPClient is such that they either return a
89   * boolean value or some other value.
90   * The boolean methods return true on a successful completion reply from
91   * the FTP server and false on a reply resulting in an error condition or
92   * failure.  The methods returning a value other than boolean return a value
93   * containing the higher level data produced by the FTP command, or null if a
94   * reply resulted in an error condition or failure.  If you want to access
95   * the exact FTP reply code causing a success or failure, you must call
96   * {@link org.apache.commons.net.ftp.FTP#getReplyCode  getReplyCode } after
97   * a success or failure.
98   * <p>
99   * The default settings for FTPClient are for it to use
100  * <code> FTP.ASCII_FILE_TYPE </code>,
101  * <code> FTP.NON_PRINT_TEXT_FORMAT </code>,
102  * <code> FTP.STREAM_TRANSFER_MODE </code>, and
103  * <code> FTP.FILE_STRUCTURE </code>.  The only file types directly supported
104  * are <code> FTP.ASCII_FILE_TYPE </code> and
105  * <code> FTP.IMAGE_FILE_TYPE </code> (which is the same as
106  * <code> FTP.BINARY_FILE_TYPE </code>).  Because there are at lest 4
107  * different EBCDIC encodings, we have opted not to provide direct support
108  * for EBCDIC.  To transfer EBCDIC and other unsupported file types you
109  * must create your own filter InputStreams and OutputStreams and wrap
110  * them around the streams returned or required by the FTPClient methods.
111  * FTPClient uses the {@link ToNetASCIIOutputStream NetASCII}  
112  * filter streams to provide transparent handling of ASCII files.  We will 
113  * consider incorporating EBCDIC support if there is enough demand.
114  * <p>
115  * <code> FTP.NON_PRINT_TEXT_FORMAT </code>,
116  * <code> FTP.STREAM_TRANSFER_MODE </code>, and
117  * <code> FTP.FILE_STRUCTURE </code> are the only supported formats,
118  * transfer modes, and file structures.
119  * <p>
120  * Because the handling of sockets on different platforms can differ
121  * significantly, the FTPClient automatically issues a new PORT command
122  * prior to every transfer requiring that the server connect to the client's
123  * data port.  This ensures identical problem-free behavior on Windows, Unix,
124  * and Macintosh platforms.  Additionally, it relieves programmers from
125  * having to issue the PORT command themselves and dealing with platform
126  * dependent issues.
127  * <p>
128  * Additionally, for security purposes, all data connections to the
129  * client are verified to ensure that they originated from the intended
130  * party (host and port).  If a data connection is initiated by an unexpected
131  * party, the command will close the socket and throw an IOException.  You
132  * may disable this behavior with
133  * {@link #setRemoteVerificationEnabled setRemoteVerificationEnabled()}.
134  * <p>
135  * You should keep in mind that the FTP server may choose to prematurely
136  * close a connection if the client has been idle for longer than a
137  * given time period (usually 900 seconds).  The FTPClient class will detect a
138  * premature FTP server connection closing when it receives a
139  * {@link org.apache.commons.net.ftp.FTPReply#SERVICE_NOT_AVAILABLE FTPReply.SERVICE_NOT_AVAILABLE }
140  *  response to a command.
141  * When that occurs, the FTP class method encountering that reply will throw
142  * an {@link org.apache.commons.net.ftp.FTPConnectionClosedException}
143  * .
144  * <code>FTPConnectionClosedException</code>
145  * is a subclass of <code> IOException </code> and therefore need not be
146  * caught separately, but if you are going to catch it separately, its
147  * catch block must appear before the more general <code> IOException </code>
148  * catch block.  When you encounter an
149  * {@link org.apache.commons.net.ftp.FTPConnectionClosedException}
150  * , you must disconnect the connection with
151  * {@link #disconnect  disconnect() } to properly clean up the
152  * system resources used by FTPClient.  Before disconnecting, you may check the
153  * last reply code and text with
154  * {@link org.apache.commons.net.ftp.FTP#getReplyCode  getReplyCode },
155  * {@link org.apache.commons.net.ftp.FTP#getReplyString  getReplyString },
156  * and
157  * {@link org.apache.commons.net.ftp.FTP#getReplyStrings  getReplyStrings}.
158  * You may avoid server disconnections while the client is idle by
159  * periodicaly sending NOOP commands to the server.
160  * <p>
161  * Rather than list it separately for each method, we mention here that
162  * every method communicating with the server and throwing an IOException
163  * can also throw a
164  * {@link org.apache.commons.net.MalformedServerReplyException}
165  * , which is a subclass
166  * of IOException.  A MalformedServerReplyException will be thrown when
167  * the reply received from the server deviates enough from the protocol
168  * specification that it cannot be interpreted in a useful manner despite
169  * attempts to be as lenient as possible.
170  * <p>
171  * Listing API Examples
172  * Both paged and unpaged examples of directory listings are available,
173  * as follows:
174  * <p>
175  * Unpaged (whole list) access, using a parser accessible by auto-detect:
176  * <pre>
177  *    FTPClient f=FTPClient();
178  *    f.connect(server);
179  *    f.login(username, password);
180  *    FTPFile[] files = listFiles(directory);
181  * </pre>
182  * <p>
183  * Paged access, using a parser not accessible by auto-detect.  The class
184  * defined in the first parameter of initateListParsing should be derived
185  * from org.apache.commons.net.FTPFileEntryParser:
186  * <pre>
187  *    FTPClient f=FTPClient();
188  *    f.connect(server);
189  *    f.login(username, password);
190  *    FTPListParseEngine engine =
191  *       f.initiateListParsing("com.whatever.YourOwnParser", directory);
192  *
193  *    while (engine.hasNext()) {
194  *       FTPFile[] files = engine.getNext(25);  // "page size" you want
195  *       //do whatever you want with these files, display them, etc.
196  *       //expensive FTPFile objects not created until needed.
197  *    }
198  * </pre>
199  * <p>
200  * Paged access, using a parser accessible by auto-detect:
201  * <pre>
202  *    FTPClient f=FTPClient();
203  *    f.connect(server);
204  *    f.login(username, password);
205  *    FTPListParseEngine engine = f.initiateListParsing(directory);
206  *
207  *    while (engine.hasNext()) {
208  *       FTPFile[] files = engine.getNext(25);  // "page size" you want
209  *       //do whatever you want with these files, display them, etc.
210  *       //expensive FTPFile objects not created until needed.
211  *    }
212  * </pre>
213  * <p>
214  * For examples of using FTPClient on servers whose directory listings 
215  * <ul> 
216  * <li>use languages other than English</li>
217  * <li>use date formats other than the American English "standard" <code>MM d yyyy</code></li>
218  * <li>are in different timezones and you need accurate timestamps for dependency checking 
219  *     as in Ant</li>
220  * </ul>see {@link  FTPClientConfig  FTPClientConfig}.
221  * <p>
222  * NOTE: If you experience problems with unwanted firing of <pre>setSoTimeout()</pre> 
223  * during periods of client inactivity, this can be alleviated by calling <pre>setReaderThread(false)</pre>.
224  * For more details, see <a href="http://issues.apache.org/bugzilla/show_bug.cgi?id=31122">this thread</a>. 
225  * </p>
226  * <p> 
227  * @author Daniel F. Savarese
228  * @see FTP
229  * @see FTPConnectionClosedException
230  * @see FTPFileEntryParser
231  * @see FTPFileEntryParserFactory
232  * @see DefaultFTPFileEntryParserFactory
233  * @see FTPClientConfig
234  * @see org.apache.commons.net.MalformedServerReplyException
235  **/
236 public class FTPClient extends FTP
237 implements Configurable
238 {
239     /***
240      * A constant indicating the FTP session is expecting all transfers
241      * to occur between the client (local) and server and that the server
242      * should connect to the client's data port to initiate a data transfer.
243      * This is the default data connection mode when and FTPClient instance
244      * is created.
245      ***/
246     public static final int ACTIVE_LOCAL_DATA_CONNECTION_MODE = 0;
247     /***
248      * A constant indicating the FTP session is expecting all transfers
249      * to occur between two remote servers and that the server
250      * the client is connected to should connect to the other server's
251      * data port to initiate a data transfer.
252      ***/
253     public static final int ACTIVE_REMOTE_DATA_CONNECTION_MODE = 1;
254     /***
255      * A constant indicating the FTP session is expecting all transfers
256      * to occur between the client (local) and server and that the server
257      * is in passive mode, requiring the client to connect to the
258      * server's data port to initiate a transfer.
259      ***/
260     public static final int PASSIVE_LOCAL_DATA_CONNECTION_MODE = 2;
261     /***
262      * A constant indicating the FTP session is expecting all transfers
263      * to occur between two remote servers and that the server
264      * the client is connected to is in passive mode, requiring the other
265      * server to connect to the first server's data port to initiate a data
266      * transfer.
267      ***/
268     public static final int PASSIVE_REMOTE_DATA_CONNECTION_MODE = 3;
269 
270     private int __dataConnectionMode, __dataTimeout;
271     private int __passivePort;
272     private String __passiveHost;
273     private int __fileType, __fileFormat, __fileStructure, __fileTransferMode;
274     private boolean __remoteVerificationEnabled;
275     private long __restartOffset;
276     private FTPFileEntryParserFactory __parserFactory;
277     private int __bufferSize;
278 
279     // __systemName is a cached value that should not be referenced directly
280     // except when assigned in getSystemName and __initDefaults.
281     private String __systemName;
282 
283     // __entryParser is a cached value that should not be referenced directly
284     // except when assigned in listFiles(String, String) and __initDefaults.
285     private FTPFileEntryParser __entryParser;
286     
287     private FTPClientConfig __configuration;
288 
289     /***
290      * Default FTPClient constructor.  Creates a new FTPClient instance
291      * with the data connection mode set to
292      * <code> ACTIVE_LOCAL_DATA_CONNECTION_MODE </code>, the file type
293      * set to <code> FTP.ASCII_FILE_TYPE </code>, the
294      * file format set to <code> FTP.NON_PRINT_TEXT_FORMAT </code>,
295      * the file structure set to <code> FTP.FILE_STRUCTURE </code>, and
296      * the transfer mode set to <code> FTP.STREAM_TRANSFER_MODE </code>.
297      ***/
298     public FTPClient()
299     {
300         __initDefaults();
301         __dataTimeout = -1;
302         __remoteVerificationEnabled = true;
303         __parserFactory = new DefaultFTPFileEntryParserFactory();
304         __configuration      = null;
305     }
306 
307 
308     private void __initDefaults()
309     {
310         __dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE;
311         __passiveHost        = null;
312         __passivePort        = -1;
313         __fileType           = FTP.ASCII_FILE_TYPE;
314         __fileStructure      = FTP.FILE_STRUCTURE;
315         __fileFormat         = FTP.NON_PRINT_TEXT_FORMAT;
316         __fileTransferMode   = FTP.STREAM_TRANSFER_MODE;
317         __restartOffset      = 0;
318         __systemName         = null;
319         __entryParser        = null;
320         __bufferSize      = Util.DEFAULT_COPY_BUFFER_SIZE;
321     }
322     
323     private String __parsePathname(String reply)
324     {
325         int begin, end;
326 
327         begin = reply.indexOf('"') + 1;
328         end = reply.indexOf('"', begin);
329 
330         return reply.substring(begin, end);
331     }
332 
333 
334     private void __parsePassiveModeReply(String reply)
335     throws MalformedServerReplyException
336     {
337         int i, index, lastIndex;
338         String octet1, octet2;
339         StringBuffer host;
340 
341         reply = reply.substring(reply.indexOf('(') + 1,
342                                 reply.indexOf(')')).trim();
343 
344         host = new StringBuffer(24);
345         lastIndex = 0;
346         index = reply.indexOf(',');
347         host.append(reply.substring(lastIndex, index));
348 
349         for (i = 0; i < 3; i++)
350         {
351             host.append('.');
352             lastIndex = index + 1;
353             index = reply.indexOf(',', lastIndex);
354             host.append(reply.substring(lastIndex, index));
355         }
356 
357         lastIndex = index + 1;
358         index = reply.indexOf(',', lastIndex);
359 
360         octet1 = reply.substring(lastIndex, index);
361         octet2 = reply.substring(index + 1);
362 
363         // index and lastIndex now used as temporaries
364         try
365         {
366             index = Integer.parseInt(octet1);
367             lastIndex = Integer.parseInt(octet2);
368         }
369         catch (NumberFormatException e)
370         {
371             throw new MalformedServerReplyException(
372                 "Could not parse passive host information.\nServer Reply: " + reply);
373         }
374 
375         index <<= 8;
376         index |= lastIndex;
377 
378         __passiveHost = host.toString();
379         __passivePort = index;
380     }
381 
382     private boolean __storeFile(int command, String remote, InputStream local)
383     throws IOException
384     {
385         OutputStream output;
386         Socket socket;
387 
388         if ((socket = _openDataConnection_(command, remote)) == null)
389             return false;
390 
391         output = new BufferedOutputStream(socket.getOutputStream(),
392                                           getBufferSize()
393                                           );
394         if (__fileType == ASCII_FILE_TYPE)
395             output = new ToNetASCIIOutputStream(output);
396         // Treat everything else as binary for now
397         try
398         {
399             Util.copyStream(local, output, getBufferSize(),
400                             CopyStreamEvent.UNKNOWN_STREAM_SIZE, null,
401                             false);
402         }
403         catch (IOException e)
404         {
405             try
406             {
407                 socket.close();
408             }
409             catch (IOException f)
410             {}
411             throw e;
412         }
413         output.close();
414         socket.close();
415         return completePendingCommand();
416     }
417 
418     private OutputStream __storeFileStream(int command, String remote)
419     throws IOException
420     {
421         OutputStream output;
422         Socket socket;
423 
424         if ((socket = _openDataConnection_(command, remote)) == null)
425             return null;
426 
427         output = socket.getOutputStream();
428         if (__fileType == ASCII_FILE_TYPE) {
429           // We buffer ascii transfers because the buffering has to
430           // be interposed between ToNetASCIIOutputSream and the underlying
431           // socket output stream.  We don't buffer binary transfers
432           // because we don't want to impose a buffering policy on the
433           // programmer if possible.  Programmers can decide on their
434           // own if they want to wrap the SocketOutputStream we return
435           // for file types other than ASCII.
436           output = new BufferedOutputStream(output,
437                                             getBufferSize());
438           output = new ToNetASCIIOutputStream(output);
439 
440         }
441         return new org.apache.commons.net.io.SocketOutputStream(socket, output);
442     }
443 
444 
445     /**
446      * Establishes a data connection with the FTP server, returning
447      * a Socket for the connection if successful.  If a restart
448      * offset has been set with {@link #setRestartOffset(long)},
449      * a REST command is issued to the server with the offset as
450      * an argument before establishing the data connection.  Active
451      * mode connections also cause a local PORT command to be issued.
452      * <p>
453      * @param command  The text representation of the FTP command to send.
454      * @param arg The arguments to the FTP command.  If this parameter is
455      *             set to null, then the command is sent with no argument.
456      * @return A Socket corresponding to the established data connection.
457      *         Null is returned if an FTP protocol error is reported at
458      *         any point during the establishment and initialization of
459      *         the connection.
460      * @exception IOException  If an I/O error occurs while either sending a
461      *      command to the server or receiving a reply from the server.
462      */
463     protected Socket _openDataConnection_(int command, String arg)
464       throws IOException
465     {
466         Socket socket;
467 
468         if (__dataConnectionMode != ACTIVE_LOCAL_DATA_CONNECTION_MODE &&
469                 __dataConnectionMode != PASSIVE_LOCAL_DATA_CONNECTION_MODE)
470             return null;
471 
472         if (__dataConnectionMode == ACTIVE_LOCAL_DATA_CONNECTION_MODE)
473         {
474             ServerSocket server;
475             server = _socketFactory_.createServerSocket(0, 1, getLocalAddress());
476 
477             if (!FTPReply.isPositiveCompletion(port(getLocalAddress(),
478                                                     server.getLocalPort())))
479             {
480                 server.close();
481                 return null;
482             }
483 
484             if ((__restartOffset > 0) && !restart(__restartOffset))
485             {
486                 server.close();
487                 return null;
488             }
489 
490             if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))
491             {
492                 server.close();
493                 return null;
494             }
495 
496             // For now, let's just use the data timeout value for waiting for
497             // the data connection.  It may be desirable to let this be a
498             // separately configurable value.  In any case, we really want
499             // to allow preventing the accept from blocking indefinitely.
500             if (__dataTimeout >= 0)
501                 server.setSoTimeout(__dataTimeout);
502             socket = server.accept();
503             server.close();
504         }
505         else
506         { // We must be in PASSIVE_LOCAL_DATA_CONNECTION_MODE
507 
508             if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
509                 return null;
510 
511             __parsePassiveModeReply((String)_replyLines.elementAt(0));
512 
513             socket = _socketFactory_.createSocket(__passiveHost, __passivePort);
514             if ((__restartOffset > 0) && !restart(__restartOffset))
515             {
516                 socket.close();
517                 return null;
518             }
519 
520             if (!FTPReply.isPositivePreliminary(sendCommand(command, arg)))
521             {
522                 socket.close();
523                 return null;
524             }
525         }
526 
527         if (__remoteVerificationEnabled && !verifyRemote(socket))
528         {
529             InetAddress host1, host2;
530 
531             host1 = socket.getInetAddress();
532             host2 = getRemoteAddress();
533 
534             socket.close();
535 
536             throw new IOException(
537                 "Host attempting data connection " + host1.getHostAddress() +
538                 " is not same as server " + host2.getHostAddress());
539         }
540 
541         if (__dataTimeout >= 0)
542             socket.setSoTimeout(__dataTimeout);
543 
544         return socket;
545     }
546 
547 
548     protected void _connectAction_() throws IOException
549     {
550         super._connectAction_();
551         __initDefaults();
552     }
553 
554 
555     /***
556      * Sets the timeout in milliseconds to use when reading from the
557      * data connection.  This timeout will be set immediately after
558      * opening the data connection.
559      * <p>
560      * @param  timeout The default timeout in milliseconds that is used when
561      *        opening a data connection socket.
562      ***/
563     public void setDataTimeout(int timeout)
564     {
565         __dataTimeout = timeout;
566     }
567 
568     /**
569      * set the factory used for parser creation to the supplied factory object.
570      *
571      * @param parserFactory
572      *               factory object used to create FTPFileEntryParsers
573      *
574      * @see org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory
575      * @see org.apache.commons.net.ftp.parser.DefaultFTPFileEntryParserFactory
576      */
577     public void setParserFactory(FTPFileEntryParserFactory parserFactory) {
578         __parserFactory = parserFactory;
579     }
580 
581 
582     /***
583      * Closes the connection to the FTP server and restores
584      * connection parameters to the default values.
585      * <p>
586      * @exception IOException If an error occurs while disconnecting.
587      ***/
588     public void disconnect() throws IOException
589     {
590         super.disconnect();
591         __initDefaults();
592     }
593 
594 
595     /***
596      * Enable or disable verification that the remote host taking part
597      * of a data connection is the same as the host to which the control
598      * connection is attached.  The default is for verification to be
599      * enabled.  You may set this value at any time, whether the
600      * FTPClient is currently connected or not.
601      * <p>
602      * @param enable True to enable verification, false to disable verification.
603      ***/
604     public void setRemoteVerificationEnabled(boolean enable)
605     {
606         __remoteVerificationEnabled = enable;
607     }
608 
609     /***
610      * Return whether or not verification of the remote host participating
611      * in data connections is enabled.  The default behavior is for
612      * verification to be enabled.
613      * <p>
614      * @return True if verification is enabled, false if not.
615      ***/
616     public boolean isRemoteVerificationEnabled()
617     {
618         return __remoteVerificationEnabled;
619     }
620 
621     /***
622      * Login to the FTP server using the provided username and password.
623      * <p>
624      * @param username The username to login under.
625      * @param password The password to use.
626      * @return True if successfully completed, false if not.
627      * @exception FTPConnectionClosedException
628      *      If the FTP server prematurely closes the connection as a result
629      *      of the client being idle or some other reason causing the server
630      *      to send FTP reply code 421.  This exception may be caught either
631      *      as an IOException or independently as itself.
632      * @exception IOException  If an I/O error occurs while either sending a
633      *      command to the server or receiving a reply from the server.
634      ***/
635     public boolean login(String username, String password) throws IOException
636     {
637         user(username);
638 
639         if (FTPReply.isPositiveCompletion(_replyCode))
640             return true;
641 
642         // If we get here, we either have an error code, or an intermmediate
643         // reply requesting password.
644         if (!FTPReply.isPositiveIntermediate(_replyCode))
645             return false;
646 
647         return FTPReply.isPositiveCompletion(pass(password));
648     }
649 
650 
651     /***
652      * Login to the FTP server using the provided username, password,
653      * and account.  If no account is required by the server, only
654      * the username and password, the account information is not used.
655      * <p>
656      * @param username The username to login under.
657      * @param password The password to use.
658      * @param account  The account to use.
659      * @return True if successfully completed, false if not.
660      * @exception FTPConnectionClosedException
661      *      If the FTP server prematurely closes the connection as a result
662      *      of the client being idle or some other reason causing the server
663      *      to send FTP reply code 421.  This exception may be caught either
664      *      as an IOException or independently as itself.
665      * @exception IOException  If an I/O error occurs while either sending a
666      *      command to the server or receiving a reply from the server.
667      ***/
668     public boolean login(String username, String password, String account)
669     throws IOException
670     {
671         user(username);
672 
673         if (FTPReply.isPositiveCompletion(_replyCode))
674             return true;
675 
676         // If we get here, we either have an error code, or an intermmediate
677         // reply requesting password.
678         if (!FTPReply.isPositiveIntermediate(_replyCode))
679             return false;
680 
681         pass(password);
682 
683         if (FTPReply.isPositiveCompletion(_replyCode))
684             return true;
685 
686         if (!FTPReply.isPositiveIntermediate(_replyCode))
687             return false;
688 
689         return FTPReply.isPositiveCompletion(acct(account));
690     }
691 
692     /***
693      * Logout of the FTP server by sending the QUIT command.
694      * <p>
695      * @return True if successfully completed, false if not.
696      * @exception FTPConnectionClosedException
697      *      If the FTP server prematurely closes the connection as a result
698      *      of the client being idle or some other reason causing the server
699      *      to send FTP reply code 421.  This exception may be caught either
700      *      as an IOException or independently as itself.
701      * @exception IOException  If an I/O error occurs while either sending a
702      *      command to the server or receiving a reply from the server.
703      ***/
704     public boolean logout() throws IOException
705     {
706         return FTPReply.isPositiveCompletion(quit());
707     }
708 
709 
710     /***
711      * Change the current working directory of the FTP session.
712      * <p>
713      * @param pathname  The new current working directory.
714      * @return True if successfully completed, false if not.
715      * @exception FTPConnectionClosedException
716      *      If the FTP server prematurely closes the connection as a result
717      *      of the client being idle or some other reason causing the server
718      *      to send FTP reply code 421.  This exception may be caught either
719      *      as an IOException or independently as itself.
720      * @exception IOException  If an I/O error occurs while either sending a
721      *      command to the server or receiving a reply from the server.
722      ***/
723     public boolean changeWorkingDirectory(String pathname) throws IOException
724     {
725         return FTPReply.isPositiveCompletion(cwd(pathname));
726     }
727 
728 
729     /***
730      * Change to the parent directory of the current working directory.
731      * <p>
732      * @return True if successfully completed, false if not.
733      * @exception FTPConnectionClosedException
734      *      If the FTP server prematurely closes the connection as a result
735      *      of the client being idle or some other reason causing the server
736      *      to send FTP reply code 421.  This exception may be caught either
737      *      as an IOException or independently as itself.
738      * @exception IOException  If an I/O error occurs while either sending a
739      *      command to the server or receiving a reply from the server.
740      ***/
741     public boolean changeToParentDirectory() throws IOException
742     {
743         return FTPReply.isPositiveCompletion(cdup());
744     }
745 
746 
747     /***
748      * Issue the FTP SMNT command.
749      * <p>
750      * @param pathname The pathname to mount.
751      * @return True if successfully completed, false if not.
752      * @exception FTPConnectionClosedException
753      *      If the FTP server prematurely closes the connection as a result
754      *      of the client being idle or some other reason causing the server
755      *      to send FTP reply code 421.  This exception may be caught either
756      *      as an IOException or independently as itself.
757      * @exception IOException  If an I/O error occurs while either sending a
758      *      command to the server or receiving a reply from the server.
759      ***/
760     public boolean structureMount(String pathname) throws IOException
761     {
762         return FTPReply.isPositiveCompletion(smnt(pathname));
763     }
764 
765     /***
766      * Reinitialize the FTP session.  Not all FTP servers support this
767      * command, which issues the FTP REIN command.
768      * <p>
769      * @return True if successfully completed, false if not.
770      * @exception FTPConnectionClosedException
771      *      If the FTP server prematurely closes the connection as a result
772      *      of the client being idle or some other reason causing the server
773      *      to send FTP reply code 421.  This exception may be caught either
774      *      as an IOException or independently as itself.
775      * @exception IOException  If an I/O error occurs while either sending a
776      *      command to the server or receiving a reply from the server.
777      ***/
778     boolean reinitialize() throws IOException
779     {
780         rein();
781 
782         if (FTPReply.isPositiveCompletion(_replyCode) ||
783                 (FTPReply.isPositivePreliminary(_replyCode) &&
784                  FTPReply.isPositiveCompletion(getReply())))
785         {
786 
787             __initDefaults();
788 
789             return true;
790         }
791 
792         return false;
793     }
794 
795 
796     /***
797      * Set the current data connection mode to
798      * <code>ACTIVE_LOCAL_DATA_CONNECTION_MODE</code>.  No communication
799      * with the FTP server is conducted, but this causes all future data
800      * transfers to require the FTP server to connect to the client's
801      * data port.  Additionally, to accommodate differences between socket
802      * implementations on different platforms, this method causes the
803      * client to issue a PORT command before every data transfer.
804      ***/
805     public void enterLocalActiveMode()
806     {
807         __dataConnectionMode = ACTIVE_LOCAL_DATA_CONNECTION_MODE;
808         __passiveHost = null;
809         __passivePort = -1;
810     }
811 
812 
813     /***
814      * Set the current data connection mode to
815      * <code> PASSIVE_LOCAL_DATA_CONNECTION_MODE </code>.  Use this
816      * method only for data transfers between the client and server.
817      * This method causes a PASV command to be issued to the server
818      * before the opening of every data connection, telling the server to
819      * open a data port to which the client will connect to conduct
820      * data transfers.  The FTPClient will stay in
821      * <code> PASSIVE_LOCAL_DATA_CONNECTION_MODE </code> until the
822      * mode is changed by calling some other method such as
823      * {@link #enterLocalActiveMode  enterLocalActiveMode() }
824      ***/
825     public void enterLocalPassiveMode()
826     {
827         __dataConnectionMode = PASSIVE_LOCAL_DATA_CONNECTION_MODE;
828         // These will be set when just before a data connection is opened
829         // in _openDataConnection_()
830         __passiveHost = null;
831         __passivePort = -1;
832     }
833 
834 
835     /***
836      * Set the current data connection mode to
837      * <code> ACTIVE_REMOTE_DATA_CONNECTION </code>.  Use this method only
838      * for server to server data transfers.  This method issues a PORT
839      * command to the server, indicating the other server and port to which
840      * it should connect for data transfers.  You must call this method
841      * before EVERY server to server transfer attempt.  The FTPClient will
842      * NOT automatically continue to issue PORT commands.  You also
843      * must remember to call
844      * {@link #enterLocalActiveMode  enterLocalActiveMode() } if you
845      * wish to return to the normal data connection mode.
846      * <p>
847      * @param host The passive mode server accepting connections for data
848      *             transfers.
849      * @param port The passive mode server's data port.
850      * @return True if successfully completed, false if not.
851      * @exception FTPConnectionClosedException
852      *      If the FTP server prematurely closes the connection as a result
853      *      of the client being idle or some other reason causing the server
854      *      to send FTP reply code 421.  This exception may be caught either
855      *      as an IOException or independently as itself.
856      * @exception IOException  If an I/O error occurs while either sending a
857      *      command to the server or receiving a reply from the server.
858      ***/
859     public boolean enterRemoteActiveMode(InetAddress host, int port)
860     throws IOException
861     {
862         if (FTPReply.isPositiveCompletion(port(host, port)))
863         {
864             __dataConnectionMode = ACTIVE_REMOTE_DATA_CONNECTION_MODE;
865             __passiveHost = null;
866             __passivePort = -1;
867             return true;
868         }
869         return false;
870     }
871 
872     /***
873      * Set the current data connection mode to
874      * <code> PASSIVE_REMOTE_DATA_CONNECTION_MODE </code>.  Use this
875      * method only for server to server data transfers.
876      * This method issues a PASV command to the server, telling it to
877      * open a data port to which the active server will connect to conduct
878      * data transfers.  You must call this method
879      * before EVERY server to server transfer attempt.  The FTPClient will
880      * NOT automatically continue to issue PASV commands.  You also
881      * must remember to call
882      * {@link #enterLocalActiveMode  enterLocalActiveMode() } if you
883      * wish to return to the normal data connection mode.
884      * <p>
885      * @return True if successfully completed, false if not.
886      * @exception FTPConnectionClosedException
887      *      If the FTP server prematurely closes the connection as a result
888      *      of the client being idle or some other reason causing the server
889      *      to send FTP reply code 421.  This exception may be caught either
890      *      as an IOException or independently as itself.
891      * @exception IOException  If an I/O error occurs while either sending a
892      *      command to the server or receiving a reply from the server.
893      ***/
894     public boolean enterRemotePassiveMode() throws IOException
895     {
896         if (pasv() != FTPReply.ENTERING_PASSIVE_MODE)
897             return false;
898 
899         __dataConnectionMode = PASSIVE_REMOTE_DATA_CONNECTION_MODE;
900         __parsePassiveModeReply((String)_replyLines.elementAt(0));
901 
902         return true;
903     }
904 
905     /***
906      * Returns the hostname or IP address (in the form of a string) returned
907      * by the server when entering passive mode.  If not in passive mode,
908      * returns null.  This method only returns a valid value AFTER a
909      * data connection has been opened after a call to
910      * {@link #enterLocalPassiveMode enterLocalPassiveMode()}.
911      * This is because FTPClient sends a PASV command to the server only
912      * just before opening a data connection, and not when you call
913      * {@link #enterLocalPassiveMode enterLocalPassiveMode()}.
914      * <p>
915      * @return The passive host name if in passive mode, otherwise null.
916      ***/
917     public String getPassiveHost()
918     {
919         return __passiveHost;
920     }
921 
922     /***
923      * If in passive mode, returns the data port of the passive host.
924      * This method only returns a valid value AFTER a
925      * data connection has been opened after a call to
926      * {@link #enterLocalPassiveMode enterLocalPassiveMode()}.
927      * This is because FTPClient sends a PASV command to the server only
928      * just before opening a data connection, and not when you call
929      * {@link #enterLocalPassiveMode enterLocalPassiveMode()}.
930      * <p>
931      * @return The data port of the passive server.  If not in passive
932      *         mode, undefined.
933      ***/
934     public int getPassivePort()
935     {
936         return __passivePort;
937     }
938 
939 
940     /***
941      * Returns the current data connection mode (one of the
942      * <code> _DATA_CONNECTION_MODE </code> constants.
943      * <p>
944      * @return The current data connection mode (one of the
945      * <code> _DATA_CONNECTION_MODE </code> constants.
946      ***/
947     public int getDataConnectionMode()
948     {
949         return __dataConnectionMode;
950     }
951 
952 
953     /***
954      * Sets the file type to be transferred.  This should be one of
955      * <code> FTP.ASCII_FILE_TYPE </code>, <code> FTP.IMAGE_FILE_TYPE </code>,
956      * etc.  The file type only needs to be set when you want to change the
957      * type.  After changing it, the new type stays in effect until you change
958      * it again.  The default file type is <code> FTP.ASCII_FILE_TYPE </code>
959      * if this method is never called.
960      * <p>
961      * @param fileType The <code> _FILE_TYPE </code> constant indcating the
962      *                 type of file.
963      * @return True if successfully completed, false if not.
964      * @exception FTPConnectionClosedException
965      *      If the FTP server prematurely closes the connection as a result
966      *      of the client being idle or some other reason causing the server
967      *      to send FTP reply code 421.  This exception may be caught either
968      *      as an IOException or independently as itself.
969      * @exception IOException  If an I/O error occurs while either sending a
970      *      command to the server or receiving a reply from the server.
971      ***/
972     public boolean setFileType(int fileType) throws IOException
973     {
974         if (FTPReply.isPositiveCompletion(type(fileType)))
975         {
976             __fileType = fileType;
977             __fileFormat = FTP.NON_PRINT_TEXT_FORMAT;
978             return true;
979         }
980         return false;
981     }
982 
983 
984     /***
985      * Sets the file type to be transferred and the format.  The type should be
986      * one of  <code> FTP.ASCII_FILE_TYPE </code>,
987      * <code> FTP.IMAGE_FILE_TYPE </code>, etc.  The file type only needs to
988      * be set when you want to change the type.  After changing it, the new
989      * type stays in effect until you change it again.  The default file type
990      * is <code> FTP.ASCII_FILE_TYPE </code> if this method is never called.
991      * The format should be one of the FTP class <code> TEXT_FORMAT </code>
992      * constants, or if the type is <code> FTP.LOCAL_FILE_TYPE </code>, the
993      * format should be the byte size for that type.  The default format
994      * is <code> FTP.NON_PRINT_TEXT_FORMAT </code> if this method is never
995      * called.
996      * <p>
997      * @param fileType The <code> _FILE_TYPE </code> constant indcating the
998      *                 type of file.
999      * @param formatOrByteSize  The format of the file (one of the
1000     *              <code>_FORMAT</code> constants.  In the case of
1001     *              <code>LOCAL_FILE_TYPE</code>, the byte size.
1002     * <p>
1003     * @return True if successfully completed, false if not.
1004     * @exception FTPConnectionClosedException
1005     *      If the FTP server prematurely closes the connection as a result
1006     *      of the client being idle or some other reason causing the server
1007     *      to send FTP reply code 421.  This exception may be caught either
1008     *      as an IOException or independently as itself.
1009     * @exception IOException  If an I/O error occurs while either sending a
1010     *      command to the server or receiving a reply from the server.
1011     ***/
1012    public boolean setFileType(int fileType, int formatOrByteSize)
1013    throws IOException
1014    {
1015        if (FTPReply.isPositiveCompletion(type(fileType, formatOrByteSize)))
1016        {
1017            __fileType = fileType;
1018            __fileFormat = formatOrByteSize;
1019            return true;
1020        }
1021        return false;
1022    }
1023
1024
1025    /***
1026     * Sets the file structure.  The default structure is
1027     * <code> FTP.FILE_STRUCTURE </code> if this method is never called.
1028     * <p>
1029     * @param structure  The structure of the file (one of the FTP class
1030     *         <code>_STRUCTURE</code> constants).
1031     * @return True if successfully completed, false if not.
1032     * @exception FTPConnectionClosedException
1033     *      If the FTP server prematurely closes the connection as a result
1034     *      of the client being idle or some other reason causing the server
1035     *      to send FTP reply code 421.  This exception may be caught either
1036     *      as an IOException or independently as itself.
1037     * @exception IOException  If an I/O error occurs while either sending a
1038     *      command to the server or receiving a reply from the server.
1039     ***/
1040    public boolean setFileStructure(int structure) throws IOException
1041    {
1042        if (FTPReply.isPositiveCompletion(stru(structure)))
1043        {
1044            __fileStructure = structure;
1045            return true;
1046        }
1047        return false;
1048    }
1049
1050
1051    /***
1052     * Sets the transfer mode.  The default transfer mode
1053     * <code> FTP.STREAM_TRANSFER_MODE </code> if this method is never called.
1054     * <p>
1055     * @param mode  The new transfer mode to use (one of the FTP class
1056     *         <code>_TRANSFER_MODE</code> constants).
1057     * @return True if successfully completed, false if not.
1058     * @exception FTPConnectionClosedException
1059     *      If the FTP server prematurely closes the connection as a result
1060     *      of the client being idle or some other reason causing the server
1061     *      to send FTP reply code 421.  This exception may be caught either
1062     *      as an IOException or independently as itself.
1063     * @exception IOException  If an I/O error occurs while either sending a
1064     *      command to the server or receiving a reply from the server.
1065     ***/
1066    public boolean setFileTransferMode(int mode) throws IOException
1067    {
1068        if (FTPReply.isPositiveCompletion(mode(mode)))
1069        {
1070            __fileTransferMode = mode;
1071            return true;
1072        }
1073        return false;
1074    }
1075
1076
1077    /***
1078     * Initiate a server to server file transfer.  This method tells the
1079     * server to which the client is connected to retrieve a given file from
1080     * the other server.
1081     * <p>
1082     * @param filename  The name of the file to retrieve.
1083     * @return True if successfully completed, false if not.
1084     * @exception FTPConnectionClosedException
1085     *      If the FTP server prematurely closes the connection as a result
1086     *      of the client being idle or some other reason causing the server
1087     *      to send FTP reply code 421.  This exception may be caught either
1088     *      as an IOException or independently as itself.
1089     * @exception IOException  If an I/O error occurs while either sending a
1090     *      command to the server or receiving a reply from the server.
1091     ***/
1092    public boolean remoteRetrieve(String filename) throws IOException
1093    {
1094        if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
1095                __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
1096            return FTPReply.isPositivePreliminary(retr(filename));
1097        return false;
1098    }
1099
1100
1101    /***
1102     * Initiate a server to server file transfer.  This method tells the
1103     * server to which the client is connected to store a file on
1104     * the other server using the given filename.  The other server must
1105     * have had a <code> remoteRetrieve </code> issued to it by another
1106     * FTPClient.
1107     * <p>
1108     * @param filename  The name to call the file that is to be stored.
1109     * @return True if successfully completed, false if not.
1110     * @exception FTPConnectionClosedException
1111     *      If the FTP server prematurely closes the connection as a result
1112     *      of the client being idle or some other reason causing the server
1113     *      to send FTP reply code 421.  This exception may be caught either
1114     *      as an IOException or independently as itself.
1115     * @exception IOException  If an I/O error occurs while either sending a
1116     *      command to the server or receiving a reply from the server.
1117     ***/
1118    public boolean remoteStore(String filename) throws IOException
1119    {
1120        if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
1121                __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
1122            return FTPReply.isPositivePreliminary(stor(filename));
1123        return false;
1124    }
1125
1126
1127    /***
1128     * Initiate a server to server file transfer.  This method tells the
1129     * server to which the client is connected to store a file on
1130     * the other server using a unique filename based on the given filename.
1131     * The other server must have had a <code> remoteRetrieve </code> issued
1132     * to it by another FTPClient.
1133     * <p>
1134     * @param filename  The name on which to base the filename of the file
1135     *                  that is to be stored.
1136     * @return True if successfully completed, false if not.
1137     * @exception FTPConnectionClosedException
1138     *      If the FTP server prematurely closes the connection as a result
1139     *      of the client being idle or some other reason causing the server
1140     *      to send FTP reply code 421.  This exception may be caught either
1141     *      as an IOException or independently as itself.
1142     * @exception IOException  If an I/O error occurs while either sending a
1143     *      command to the server or receiving a reply from the server.
1144     ***/
1145    public boolean remoteStoreUnique(String filename) throws IOException
1146    {
1147        if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
1148                __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
1149            return FTPReply.isPositivePreliminary(stou(filename));
1150        return false;
1151    }
1152
1153
1154    /***
1155     * Initiate a server to server file transfer.  This method tells the
1156     * server to which the client is connected to store a file on
1157     * the other server using a unique filename.
1158     * The other server must have had a <code> remoteRetrieve </code> issued
1159     * to it by another FTPClient.  Many FTP servers require that a base
1160     * filename be given from which the unique filename can be derived.  For
1161     * those servers use the other version of <code> remoteStoreUnique</code>
1162     * <p>
1163     * @return True if successfully completed, false if not.
1164     * @exception FTPConnectionClosedException
1165     *      If the FTP server prematurely closes the connection as a result
1166     *      of the client being idle or some other reason causing the server
1167     *      to send FTP reply code 421.  This exception may be caught either
1168     *      as an IOException or independently as itself.
1169     * @exception IOException  If an I/O error occurs while either sending a
1170     *      command to the server or receiving a reply from the server.
1171     ***/
1172    public boolean remoteStoreUnique() throws IOException
1173    {
1174        if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
1175                __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
1176            return FTPReply.isPositivePreliminary(stou());
1177        return false;
1178    }
1179
1180    // For server to server transfers
1181    /***
1182     * Initiate a server to server file transfer.  This method tells the
1183     * server to which the client is connected to append to a given file on
1184     * the other server.  The other server must have had a
1185     * <code> remoteRetrieve </code> issued to it by another FTPClient.
1186     * <p>
1187     * @param filename  The name of the file to be appended to, or if the
1188     *        file does not exist, the name to call the file being stored.
1189     * <p>
1190     * @return True if successfully completed, false if not.
1191     * @exception FTPConnectionClosedException
1192     *      If the FTP server prematurely closes the connection as a result
1193     *      of the client being idle or some other reason causing the server
1194     *      to send FTP reply code 421.  This exception may be caught either
1195     *      as an IOException or independently as itself.
1196     * @exception IOException  If an I/O error occurs while either sending a
1197     *      command to the server or receiving a reply from the server.
1198     ***/
1199    public boolean remoteAppend(String filename) throws IOException
1200    {
1201        if (__dataConnectionMode == ACTIVE_REMOTE_DATA_CONNECTION_MODE ||
1202                __dataConnectionMode == PASSIVE_REMOTE_DATA_CONNECTION_MODE)
1203            return FTPReply.isPositivePreliminary(stor(filename));
1204        return false;
1205    }
1206
1207    /***
1208     * There are a few FTPClient methods that do not complete the
1209     * entire sequence of FTP commands to complete a transaction.  These
1210     * commands require some action by the programmer after the reception
1211     * of a positive intermediate command.  After the programmer's code
1212     * completes its actions, it must call this method to receive
1213     * the completion reply from the server and verify the success of the
1214     * entire transaction.
1215     * <p>
1216     * For example,
1217     * <pre>
1218     * InputStream input;
1219     * OutputStream output;
1220     * input  = new FileInputStream("foobaz.txt");
1221     * output = ftp.storeFileStream("foobar.txt")
1222     * if(!FTPReply.isPositiveIntermediate(ftp.getReplyCode())) {
1223     *     input.close();
1224     *     output.close();
1225     *     ftp.logout();
1226     *     ftp.disconnect();
1227     *     System.err.println("File transfer failed.");
1228     *     System.exit(1);
1229     * }
1230     * Util.copyStream(input, output);
1231     * input.close();
1232     * output.close();
1233     * // Must call completePendingCommand() to finish command.
1234     * if(!ftp.completePendingCommand()) {
1235     *     ftp.logout();
1236     *     ftp.disconnect();
1237     *     System.err.println("File transfer failed.");
1238     *     System.exit(1);
1239     * }
1240     * </pre>
1241     * <p>
1242     * @return True if successfully completed, false if not.
1243     * @exception FTPConnectionClosedException
1244     *      If the FTP server prematurely closes the connection as a result
1245     *      of the client being idle or some other reason causing the server
1246     *      to send FTP reply code 421.  This exception may be caught either
1247     *      as an IOException or independently as itself.
1248     * @exception IOException  If an I/O error occurs while either sending a
1249     *      command to the server or receiving a reply from the server.
1250     ***/
1251    public boolean completePendingCommand() throws IOException
1252    {
1253        return FTPReply.isPositiveCompletion(getReply());
1254    }
1255
1256
1257    /***
1258     * Retrieves a named file from the server and writes it to the given
1259     * OutputStream.  This method does NOT close the given OutputStream.
1260     * If the current file type is ASCII, line separators in the file are
1261     * converted to the local representation.
1262     * <p>
1263     * @param remote  The name of the remote file.
1264     * @param local   The local OutputStream to which to write the file.
1265     * @return True if successfully completed, false if not.
1266     * @exception FTPConnectionClosedException
1267     *      If the FTP server prematurely closes the connection as a result
1268     *      of the client being idle or some other reason causing the server
1269     *      to send FTP reply code 421.  This exception may be caught either
1270     *      as an IOException or independently as itself.
1271     * @exception CopyStreamException  If an I/O error occurs while actually
1272     *      transferring the file.  The CopyStreamException allows you to
1273     *      determine the number of bytes transferred and the IOException
1274     *      causing the error.  This exception may be caught either
1275     *      as an IOException or independently as itself.
1276     * @exception IOException  If an I/O error occurs while either sending a
1277     *      command to the server or receiving a reply from the server.
1278     ***/
1279    public boolean retrieveFile(String remote, OutputStream local)
1280    throws IOException
1281    {
1282        InputStream input;
1283        Socket socket;
1284
1285        if ((socket = _openDataConnection_(FTPCommand.RETR, remote)) == null)
1286            return false;
1287
1288        input = new BufferedInputStream(socket.getInputStream(),
1289                                        getBufferSize());
1290        if (__fileType == ASCII_FILE_TYPE)
1291          input = new FromNetASCIIInputStream(input);
1292        // Treat everything else as binary for now
1293        try
1294        {
1295            Util.copyStream(input, local, getBufferSize(),
1296                            CopyStreamEvent.UNKNOWN_STREAM_SIZE, null,
1297                            false);
1298        }
1299        catch (IOException e)
1300        {
1301            try
1302            {
1303                socket.close();
1304            }
1305            catch (IOException f)
1306            {}
1307            throw e;
1308        }
1309        socket.close();
1310        return completePendingCommand();
1311    }
1312
1313    /***
1314     * Returns an InputStream from which a named file from the server
1315     * can be read.  If the current file type is ASCII, the returned
1316     * InputStream will convert line separators in the file to
1317     * the local representation.  You must close the InputStream when you
1318     * finish reading from it.  The InputStream itself will take care of
1319     * closing the parent data connection socket upon being closed.  To
1320     * finalize the file transfer you must call
1321     * {@link #completePendingCommand  completePendingCommand } and
1322     * check its return value to verify success.
1323     * <p>
1324     * @param remote  The name of the remote file.
1325     * @return An InputStream from which the remote file can be read.  If
1326     *      the data connection cannot be opened (e.g., the file does not
1327     *      exist), null is returned (in which case you may check the reply
1328     *      code to determine the exact reason for failure).
1329     * @exception FTPConnectionClosedException
1330     *      If the FTP server prematurely closes the connection as a result
1331     *      of the client being idle or some other reason causing the server
1332     *      to send FTP reply code 421.  This exception may be caught either
1333     *      as an IOException or independently as itself.
1334     * @exception IOException  If an I/O error occurs while either sending a
1335     *      command to the server or receiving a reply from the server.
1336     ***/
1337    public InputStream retrieveFileStream(String remote) throws IOException
1338    {
1339        InputStream input;
1340        Socket socket;
1341
1342        if ((socket = _openDataConnection_(FTPCommand.RETR, remote)) == null)
1343            return null;
1344
1345        input = socket.getInputStream();
1346        if (__fileType == ASCII_FILE_TYPE) {
1347          // We buffer ascii transfers because the buffering has to
1348          // be interposed between FromNetASCIIOutputSream and the underlying
1349          // socket input stream.  We don't buffer binary transfers
1350          // because we don't want to impose a buffering policy on the
1351          // programmer if possible.  Programmers can decide on their
1352          // own if they want to wrap the SocketInputStream we return
1353          // for file types other than ASCII.
1354          input = new BufferedInputStream(input,
1355                                          getBufferSize());
1356          input = new FromNetASCIIInputStream(input);
1357        }
1358        return new org.apache.commons.net.io.SocketInputStream(socket, input);
1359    }
1360
1361
1362    /***
1363     * Stores a file on the server using the given name and taking input
1364     * from the given InputStream.  This method does NOT close the given
1365     * InputStream.  If the current file type is ASCII, line separators in
1366     * the file are transparently converted to the NETASCII format (i.e.,
1367     * you should not attempt to create a special InputStream to do this).
1368     * <p>
1369     * @param remote  The name to give the remote file.
1370     * @param local   The local InputStream from which to read the file.
1371     * @return True if successfully completed, false if not.
1372     * @exception FTPConnectionClosedException
1373     *      If the FTP server prematurely closes the connection as a result
1374     *      of the client being idle or some other reason causing the server
1375     *      to send FTP reply code 421.  This exception may be caught either
1376     *      as an IOException or independently as itself.
1377     * @exception CopyStreamException  If an I/O error occurs while actually
1378     *      transferring the file.  The CopyStreamException allows you to
1379     *      determine the number of bytes transferred and the IOException
1380     *      causing the error.  This exception may be caught either
1381     *      as an IOException or independently as itself.
1382     * @exception IOException  If an I/O error occurs while either sending a
1383     *      command to the server or receiving a reply from the server.
1384     ***/
1385    public boolean storeFile(String remote, InputStream local)
1386    throws IOException
1387    {
1388        return __storeFile(FTPCommand.STOR, remote, local);
1389    }
1390
1391
1392    /***
1393     * Returns an OutputStream through which data can be written to store
1394     * a file on the server using the given name.  If the current file type
1395     * is ASCII, the returned OutputStream will convert line separators in
1396     * the file to the NETASCII format  (i.e., you should not attempt to
1397     * create a special OutputStream to do this).  You must close the
1398     * OutputStream when you finish writing to it.  The OutputStream itself
1399     * will take care of closing the parent data connection socket upon being
1400     * closed.  To finalize the file transfer you must call
1401     * {@link #completePendingCommand  completePendingCommand } and
1402     * check its return value to verify success.
1403     * <p>
1404     * @param remote  The name to give the remote file.
1405     * @return An OutputStream through which the remote file can be written.  If
1406     *      the data connection cannot be opened (e.g., the file does not
1407     *      exist), null is returned (in which case you may check the reply
1408     *      code to determine the exact reason for failure).
1409     * @exception FTPConnectionClosedException
1410     *      If the FTP server prematurely closes the connection as a result
1411     *      of the client being idle or some other reason causing the server
1412     *      to send FTP reply code 421.  This exception may be caught either
1413     *      as an IOException or independently as itself.
1414     * @exception IOException  If an I/O error occurs while either sending a
1415     *      command to the server or receiving a reply from the server.
1416     ***/
1417    public OutputStream storeFileStream(String remote) throws IOException
1418    {
1419        return __storeFileStream(FTPCommand.STOR, remote);
1420    }
1421
1422    /***
1423     * Appends to a file on the server with the given name, taking input
1424     * from the given InputStream.  This method does NOT close the given
1425     * InputStream.  If the current file type is ASCII, line separators in
1426     * the file are transparently converted to the NETASCII format (i.e.,
1427     * you should not attempt to create a special InputStream to do this).
1428     * <p>
1429     * @param remote  The name of the remote file.
1430     * @param local   The local InputStream from which to read the data to
1431     *                be appended to the remote file.
1432     * @return True if successfully completed, false if not.
1433     * @exception FTPConnectionClosedException
1434     *      If the FTP server prematurely closes the connection as a result
1435     *      of the client being idle or some other reason causing the server
1436     *      to send FTP reply code 421.  This exception may be caught either
1437     *      as an IOException or independently as itself.
1438     * @exception CopyStreamException  If an I/O error occurs while actually
1439     *      transferring the file.  The CopyStreamException allows you to
1440     *      determine the number of bytes transferred and the IOException
1441     *      causing the error.  This exception may be caught either
1442     *      as an IOException or independently as itself.
1443     * @exception IOException  If an I/O error occurs while either sending a
1444     *      command to the server or receiving a reply from the server.
1445     ***/
1446    public boolean appendFile(String remote, InputStream local)
1447    throws IOException
1448    {
1449        return __storeFile(FTPCommand.APPE, remote, local);
1450    }
1451
1452    /***
1453     * Returns an OutputStream through which data can be written to append
1454     * to a file on the server with the given name.  If the current file type
1455     * is ASCII, the returned OutputStream will convert line separators in
1456     * the file to the NETASCII format  (i.e., you should not attempt to
1457     * create a special OutputStream to do this).  You must close the
1458     * OutputStream when you finish writing to it.  The OutputStream itself
1459     * will take care of closing the parent data connection socket upon being
1460     * closed.  To finalize the file transfer you must call
1461     * {@link #completePendingCommand  completePendingCommand } and
1462     * check its return value to verify success.
1463     * <p>
1464     * @param remote  The name of the remote file.
1465     * @return An OutputStream through which the remote file can be appended.
1466     *      If the data connection cannot be opened (e.g., the file does not
1467     *      exist), n