Example usage for org.apache.commons.net.ftp FTPClient getReplyString

List of usage examples for org.apache.commons.net.ftp FTPClient getReplyString

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient getReplyString.

Prototype

public String getReplyString() 

Source Link

Document

Returns the entire text of the last FTP server response exactly as it was received, including all end of line markers in NETASCII format.

Usage

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Sends a single file to the remote host. <code>filename</code> may
 * contain a relative path specification. When this is the case, <code>sendFile</code>
 * will attempt to create any necessary parent directories before sending
 * the file. The file will then be sent using the entire relative path
 * spec - no attempt is made to change directories. It is anticipated that
 * this may eventually cause problems with some FTP servers, but it
 * simplifies the coding./*from  ww  w  . j a  v a  2  s  .co m*/
 * @param ftp ftp client
 * @param dir base directory of the file to be sent (local)
 * @param filename relative path of the file to be send
 *        locally relative to dir
 *        remotely relative to the remotedir attribute
 * @throws IOException  in unknown circumstances
 * @throws BuildException in unknown circumstances
 */
protected void sendFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException {
    InputStream instream = null;

    try {
        // XXX - why not simply new File(dir, filename)?
        File file = getProject().resolveFile(new File(dir, filename).getPath());

        if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) {
            return;
        }

        if (verbose) {
            log("transferring " + file.getAbsolutePath());
        }

        instream = new BufferedInputStream(new FileInputStream(file));

        createParents(ftp, filename);

        ftp.storeFile(resolveFile(filename), instream);

        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());

        if (!success) {
            String s = "could not put file: " + ftp.getReplyString();

            if (skipFailedTransfers) {
                log(s, Project.MSG_WARN);
                skipped++;
            } else {
                throw new BuildException(s);
            }

        } else {
            // see if we should issue a chmod command
            if (chmod != null) {
                doSiteCommand(ftp, "chmod " + chmod + " " + resolveFile(filename));
            }
            log("File " + file.getAbsolutePath() + " copied to " + server, Project.MSG_VERBOSE);
            transferred++;
        }
    } finally {
        FileUtils.close(instream);
    }
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Checks to see if the remote file is current as compared with the local
 * file. Returns true if the target file is up to date.
 * @param ftp ftpclient/* w  w  w. jav  a  2 s  .  c o m*/
 * @param localFile local file
 * @param remoteFile remote file
 * @return true if the target file is up to date
 * @throws IOException  in unknown circumstances
 * @throws BuildException if the date of the remote files cannot be found and the action is
 * GET_FILES
 */
protected boolean isUpToDate(FTPClient ftp, File localFile, String remoteFile)
        throws IOException, BuildException {
    log("checking date for " + remoteFile, Project.MSG_VERBOSE);

    FTPFile[] files = ftp.listFiles(remoteFile);

    // For Microsoft's Ftp-Service an Array with length 0 is
    // returned if configured to return listings in "MS-DOS"-Format
    if (files == null || files.length == 0) {
        // If we are sending files, then assume out of date.
        // If we are getting files, then throw an error

        if (action == SEND_FILES) {
            log("Could not date test remote file: " + remoteFile + "assuming out of date.",
                    Project.MSG_VERBOSE);
            return false;
        } else {
            throw new BuildException("could not date test remote file: " + ftp.getReplyString());
        }
    }

    long remoteTimestamp = files[0].getTimestamp().getTime().getTime();
    long localTimestamp = localFile.lastModified();
    long adjustedRemoteTimestamp = remoteTimestamp + this.timeDiffMillis + this.granularityMillis;

    StringBuffer msg;
    synchronized (TIMESTAMP_LOGGING_SDF) {
        msg = new StringBuffer("   [").append(TIMESTAMP_LOGGING_SDF.format(new Date(localTimestamp)))
                .append("] local");
    }
    log(msg.toString(), Project.MSG_VERBOSE);

    synchronized (TIMESTAMP_LOGGING_SDF) {
        msg = new StringBuffer("   [").append(TIMESTAMP_LOGGING_SDF.format(new Date(adjustedRemoteTimestamp)))
                .append("] remote");
    }
    if (remoteTimestamp != adjustedRemoteTimestamp) {
        synchronized (TIMESTAMP_LOGGING_SDF) {
            msg.append(" - (raw: ").append(TIMESTAMP_LOGGING_SDF.format(new Date(remoteTimestamp))).append(")");
        }
    }
    log(msg.toString(), Project.MSG_VERBOSE);

    if (this.action == SEND_FILES) {
        return adjustedRemoteTimestamp >= localTimestamp;
    } else {
        return localTimestamp >= adjustedRemoteTimestamp;
    }
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Retrieve a single file from the remote host. <code>filename</code> may
 * contain a relative path specification. <p>
 *
 * The file will then be retreived using the entire relative path spec -
 * no attempt is made to change directories. It is anticipated that this
 * may eventually cause problems with some FTP servers, but it simplifies
 * the coding.</p>/*  ww w. j  a  v a 2s  .c o m*/
 * @param ftp the ftp client
 * @param dir local base directory to which the file should go back
 * @param filename relative path of the file based upon the ftp remote directory
 *        and/or the local base directory (dir)
 * @throws IOException  in unknown circumstances
 * @throws BuildException if skipFailedTransfers is false
 * and the file cannot be retrieved.
 */
protected void getFile(FTPClient ftp, String dir, String filename) throws IOException, BuildException {
    OutputStream outstream = null;
    try {
        File file = getProject().resolveFile(new File(dir, filename).getPath());

        if (newerOnly && isUpToDate(ftp, file, resolveFile(filename))) {
            return;
        }

        if (verbose) {
            log("transferring " + filename + " to " + file.getAbsolutePath());
        }

        File pdir = file.getParentFile();

        if (!pdir.exists()) {
            pdir.mkdirs();
        }
        outstream = new BufferedOutputStream(new FileOutputStream(file));
        ftp.retrieveFile(resolveFile(filename), outstream);

        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            String s = "could not get file: " + ftp.getReplyString();

            if (skipFailedTransfers) {
                log(s, Project.MSG_WARN);
                skipped++;
            } else {
                throw new BuildException(s);
            }

        } else {
            log("File " + file.getAbsolutePath() + " copied from " + server, Project.MSG_VERBOSE);
            transferred++;
            if (preserveLastModified) {
                outstream.close();
                outstream = null;
                FTPFile[] remote = ftp.listFiles(resolveFile(filename));
                if (remote.length > 0) {
                    FILE_UTILS.setFileLastModified(file, remote[0].getTimestamp().getTime().getTime());
                }
            }
        }
    } finally {
        FileUtils.close(outstream);
    }
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Creates all parent directories specified in a complete relative
 * pathname. Attempts to create existing directories will not cause
 * errors./*from  w w  w .j av a  2  s  .c o  m*/
 *
 * @param ftp the FTP client instance to use to execute FTP actions on
 *        the remote server.
 * @param filename the name of the file whose parents should be created.
 * @throws IOException under non documented circumstances
 * @throws BuildException if it is impossible to cd to a remote directory
 *
 */
protected void createParents(FTPClient ftp, String filename) throws IOException, BuildException {

    File dir = new File(filename);
    if (dirCache.contains(dir)) {
        return;
    }

    Vector parents = new Vector();
    String dirname;

    while ((dirname = dir.getParent()) != null) {
        File checkDir = new File(dirname);
        if (dirCache.contains(checkDir)) {
            break;
        }
        dir = checkDir;
        parents.addElement(dir);
    }

    // find first non cached dir
    int i = parents.size() - 1;

    if (i >= 0) {
        String cwd = ftp.printWorkingDirectory();
        String parent = dir.getParent();
        if (parent != null) {
            if (!ftp.changeWorkingDirectory(resolveFile(parent))) {
                throw new BuildException("could not change to " + "directory: " + ftp.getReplyString());
            }
        }

        while (i >= 0) {
            dir = (File) parents.elementAt(i--);
            // check if dir exists by trying to change into it.
            if (!ftp.changeWorkingDirectory(dir.getName())) {
                // could not change to it - try to create it
                log("creating remote directory " + resolveFile(dir.getPath()), Project.MSG_VERBOSE);
                if (!ftp.makeDirectory(dir.getName())) {
                    handleMkDirFailure(ftp);
                }
                if (!ftp.changeWorkingDirectory(dir.getName())) {
                    throw new BuildException("could not change to " + "directory: " + ftp.getReplyString());
                }
            }
            dirCache.add(dir);
        }
        ftp.changeWorkingDirectory(cwd);
    }
}

From source file:com.github.goldin.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Runs the task./*from  w w  w  . j  a  v a2s. c  o  m*/
 *
 * @throws BuildException if the task fails or is not configured
 *         correctly.
 */
public void execute() throws BuildException {
    checkAttributes();

    FTPClient ftp = null;

    try {
        log("Opening FTP connection to " + server, Project.MSG_VERBOSE);

        /**
         * "verbose" version of <code>FTPClient</code> prints progress indicator
         * See http://evgeny-goldin.com/blog/2010/08/18/ant-ftp-task-progress-indicator-timeout/
         */
        ftp = (verbose
                ? new com.github.goldin.org.apache.tools.ant.taskdefs.optional.net.FTPClient(getProject())
                : new org.apache.commons.net.ftp.FTPClient());

        ftp.setDataTimeout(5 * 60 * 1000); // 5 minutes

        if (this.isConfigurationSet) {
            ftp = FTPConfigurator.configure(ftp, this);
        }

        ftp.setRemoteVerificationEnabled(enableRemoteVerification);
        ftp.connect(server, port);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            throw new BuildException("FTP connection failed: " + ftp.getReplyString());
        }

        log("connected", Project.MSG_VERBOSE);
        log("logging in to FTP server", Project.MSG_VERBOSE);

        if ((this.account != null && !ftp.login(userid, password, account))
                || (this.account == null && !ftp.login(userid, password))) {
            throw new BuildException("Could not login to FTP server");
        }

        log("login succeeded", Project.MSG_VERBOSE);

        if (binary) {
            ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not set transfer type: " + ftp.getReplyString());
            }
        } else {
            ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not set transfer type: " + ftp.getReplyString());
            }
        }

        if (passive) {
            log("entering passive mode", Project.MSG_VERBOSE);
            ftp.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString());
            }
        }

        // If an initial command was configured then send it.
        // Some FTP servers offer different modes of operation,
        // E.G. switching between a UNIX file system mode and
        // a legacy file system.
        if (this.initialSiteCommand != null) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP.this.initialSiteCommand);
                }
            }, "initial site command: " + this.initialSiteCommand);
        }

        // For a unix ftp server you can set the default mask for all files
        // created.

        if (umask != null) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    doSiteCommand(lftp, "umask " + umask);
                }
            }, "umask " + umask);
        }

        // If the action is MK_DIR, then the specified remote
        // directory is the directory to create.

        if (action == MK_DIR) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    makeRemoteDir(lftp, remotedir);
                }
            }, remotedir);
        } else if (action == SITE_CMD) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP.this.siteCommand);
                }
            }, "Site Command: " + this.siteCommand);
        } else {
            if (remotedir != null) {
                log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE);
                ftp.changeWorkingDirectory(remotedir);
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString());
                }
            }
            if (newerOnly && timeDiffAuto) {
                // in this case we want to find how much time span there is between local
                // and remote
                timeDiffMillis = getTimeDiff(ftp);
            }
            log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]);
            transferFiles(ftp);
        }

    } catch (IOException ex) {
        throw new BuildException("error during FTP transfer: " + ex, ex);
    } finally {
        if (ftp != null && ftp.isConnected()) {
            try {
                log("disconnecting", Project.MSG_VERBOSE);
                ftp.logout();
                ftp.disconnect();
            } catch (IOException ex) {
                // ignore it
            }
        }
    }
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Runs the task./*from   w  w w . j  a  v  a  2  s . co m*/
 *
 * @throws BuildException if the task fails or is not configured
 *         correctly.
 */
public void execute() throws BuildException {
    checkAttributes();

    FTPClient ftp = null;

    try {
        log("Opening FTP connection to " + server, Project.MSG_VERBOSE);

        /**
         * "verbose" version of <code>FTPClient</code> prints progress indicator
         * See http://evgeny-goldin.com/blog/2010/08/18/ant-ftp-task-progress-indicator-timeout/
         */
        ftp = (verbose
                ? new com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTPClient(getProject())
                : new org.apache.commons.net.ftp.FTPClient());

        ftp.setDataTimeout(5 * 60 * 1000); // 5 minutes

        if (this.isConfigurationSet) {
            ftp = FTPConfigurator.configure(ftp, this);
        }

        ftp.setRemoteVerificationEnabled(enableRemoteVerification);
        ftp.connect(server, port);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            throw new BuildException("FTP connection failed: " + ftp.getReplyString());
        }

        log("connected", Project.MSG_VERBOSE);
        log("logging in to FTP server", Project.MSG_VERBOSE);

        if ((this.account != null && !ftp.login(userid, password, account))
                || (this.account == null && !ftp.login(userid, password))) {
            throw new BuildException("Could not login to FTP server");
        }

        log("login succeeded", Project.MSG_VERBOSE);

        if (binary) {
            ftp.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not set transfer type: " + ftp.getReplyString());
            }
        } else {
            ftp.setFileType(org.apache.commons.net.ftp.FTP.ASCII_FILE_TYPE);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not set transfer type: " + ftp.getReplyString());
            }
        }

        if (passive) {
            log("entering passive mode", Project.MSG_VERBOSE);
            ftp.enterLocalPassiveMode();
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("could not enter into passive " + "mode: " + ftp.getReplyString());
            }
        }

        // If an initial command was configured then send it.
        // Some FTP servers offer different modes of operation,
        // E.G. switching between a UNIX file system mode and
        // a legacy file system.
        if (this.initialSiteCommand != null) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP.this.initialSiteCommand);
                }
            }, "initial site command: " + this.initialSiteCommand);
        }

        // For a unix ftp server you can set the default mask for all files
        // created.

        if (umask != null) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    doSiteCommand(lftp, "umask " + umask);
                }
            }, "umask " + umask);
        }

        // If the action is MK_DIR, then the specified remote
        // directory is the directory to create.

        if (action == MK_DIR) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    makeRemoteDir(lftp, remotedir);
                }
            }, remotedir);
        } else if (action == SITE_CMD) {
            RetryHandler h = new RetryHandler(this.retriesAllowed, this);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP.this.siteCommand);
                }
            }, "Site Command: " + this.siteCommand);
        } else {
            if (remotedir != null) {
                log("changing the remote directory to " + remotedir, Project.MSG_VERBOSE);
                ftp.changeWorkingDirectory(remotedir);
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    throw new BuildException("could not change remote " + "directory: " + ftp.getReplyString());
                }
            }
            if (newerOnly && timeDiffAuto) {
                // in this case we want to find how much time span there is between local
                // and remote
                timeDiffMillis = getTimeDiff(ftp);
            }
            log(ACTION_STRS[action] + " " + ACTION_TARGET_STRS[action]);
            transferFiles(ftp);
        }

    } catch (IOException ex) {
        throw new BuildException("error during FTP transfer: " + ex, ex);
    } finally {
        if (ftp != null && ftp.isConnected()) {
            try {
                log("disconnecting", Project.MSG_VERBOSE);
                ftp.logout();
                ftp.disconnect();
            } catch (IOException ex) {
                // ignore it
            }
        }
    }
}

From source file:com.github.carlosrubio.org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Create the specified directory on the remote host.
 *
 * @param ftp The FTP client connection//from   ww w . jav a  2s  . c o m
 * @param dir The directory to create (format must be correct for host
 *      type)
 * @throws IOException  in unknown circumstances
 * @throws BuildException if ignoreNoncriticalErrors has not been set to true
 *         and a directory could not be created, for instance because it was
 *         already existing. Precisely, the codes 521, 550 and 553 will trigger
 *         a BuildException
 */
protected void makeRemoteDir(FTPClient ftp, String dir) throws IOException, BuildException {
    String workingDirectory = ftp.printWorkingDirectory();
    if (verbose) {
        if (dir.indexOf("/") == 0 || workingDirectory == null) {
            log("Creating directory: " + dir + " in /");
        } else {
            log("Creating directory: " + dir + " in " + workingDirectory);
        }
    }
    if (dir.indexOf("/") == 0) {
        ftp.changeWorkingDirectory("/");
    }
    String subdir = "";
    StringTokenizer st = new StringTokenizer(dir, "/");
    while (st.hasMoreTokens()) {
        subdir = st.nextToken();
        log("Checking " + subdir, Project.MSG_DEBUG);
        if (!ftp.changeWorkingDirectory(subdir)) {
            if (!ftp.makeDirectory(subdir)) {
                // codes 521, 550 and 553 can be produced by FTP Servers
                //  to indicate that an attempt to create a directory has
                //  failed because the directory already exists.
                int rc = ftp.getReplyCode();
                if (!(ignoreNoncriticalErrors
                        && (rc == FTPReply.CODE_550 || rc == FTPReply.CODE_553 || rc == CODE_521))) {
                    throw new BuildException("could not create directory: " + ftp.getReplyString());
                }
                if (verbose) {
                    log("Directory already exists");
                }
            } else {
                if (verbose) {
                    log("Directory created OK");
                }
                ftp.changeWorkingDirectory(subdir);
            }
        }
    }
    if (workingDirectory != null) {
        ftp.changeWorkingDirectory(workingDirectory);
    }
}

From source file:com.mozilla.SUTAgentAndroid.service.DoCommand.java

public String FTPGetFile(String sServer, String sSrcFileName, String sDstFileName, OutputStream out) {
    byte[] buffer = new byte[4096];
    int nRead = 0;
    long lTotalRead = 0;
    String sRet = sErrorPrefix + "FTP Get failed for " + sSrcFileName;
    String strRet = "";
    int reply = 0;
    FileOutputStream outStream = null;
    String sTmpDstFileName = fixFileName(sDstFileName);

    FTPClient ftp = new FTPClient();
    try {//w  ww.j a v  a2 s  .com
        ftp.connect(sServer);
        reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            ftp.login("anonymous", "b@t.com");
            reply = ftp.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                ftp.enterLocalPassiveMode();
                if (ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
                    File dstFile = new File(sTmpDstFileName);
                    outStream = new FileOutputStream(dstFile);
                    FTPFile[] ftpFiles = ftp.listFiles(sSrcFileName);
                    if (ftpFiles.length > 0) {
                        long lFtpSize = ftpFiles[0].getSize();
                        if (lFtpSize <= 0)
                            lFtpSize = 1;

                        InputStream ftpIn = ftp.retrieveFileStream(sSrcFileName);
                        while ((nRead = ftpIn.read(buffer)) != -1) {
                            lTotalRead += nRead;
                            outStream.write(buffer, 0, nRead);
                            strRet = "\r" + lTotalRead + " of " + lFtpSize + " bytes received "
                                    + ((lTotalRead * 100) / lFtpSize) + "% completed";
                            out.write(strRet.getBytes());
                            out.flush();
                        }
                        ftpIn.close();
                        @SuppressWarnings("unused")
                        boolean bRet = ftp.completePendingCommand();
                        outStream.flush();
                        outStream.close();
                        strRet = ftp.getReplyString();
                        reply = ftp.getReplyCode();
                    } else {
                        strRet = sRet;
                    }
                }
                ftp.logout();
                ftp.disconnect();
                sRet = "\n" + strRet;
            } else {
                ftp.disconnect();
                System.err.println("FTP server refused login.");
            }
        } else {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
        }
    } catch (SocketException e) {
        sRet = e.getMessage();
        strRet = ftp.getReplyString();
        reply = ftp.getReplyCode();
        sRet += "\n" + strRet;
        e.printStackTrace();
    } catch (IOException e) {
        sRet = e.getMessage();
        strRet = ftp.getReplyString();
        reply = ftp.getReplyCode();
        sRet += "\n" + strRet;
        e.printStackTrace();
    }
    return (sRet);
}

From source file:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java

public FTPClient getFtpClient() throws IOException {
    FTPClient aClient = new FTPClient();

    // Debug output
    // aClient.addProtocolCommandListener(new PrintCommandListener(new
    // PrintWriter(System.out), true));

    if (activeExternalIPAddress != null) {
        aClient.setActiveExternalIPAddress(activeExternalIPAddress);
    }//  w ww.  j  a v  a  2 s  .c o  m
    if (activeMinPort != null && activeMaxPort != null) {
        aClient.setActivePortRange(activeMinPort, activeMaxPort);
    }
    if (autodetectUTF8 != null) {
        aClient.setAutodetectUTF8(autodetectUTF8);
    }
    if (bufferSize != null) {
        aClient.setBufferSize(bufferSize);
    }
    if (charset != null) {
        aClient.setCharset(charset);
    }
    if (connectTimeout != null) {
        aClient.setConnectTimeout(connectTimeout);
    }
    if (controlEncoding != null) {
        aClient.setControlEncoding(controlEncoding);
    }
    if (controlKeepAliveReplyTimeout != null) {
        aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (controlKeepAliveTimeout != null) {
        aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout);
    }
    if (dataTimeout != null) {
        aClient.setDataTimeout(dataTimeout);
    }
    if (defaultPort != null) {
        aClient.setDefaultPort(defaultPort);
    }
    if (defaultTimeout != null) {
        aClient.setDefaultTimeout(defaultTimeout);
    }
    if (fileStructure != null) {
        aClient.setFileStructure(fileStructure);
    }
    if (keepAlive != null) {
        aClient.setKeepAlive(keepAlive);
    }
    if (listHiddenFiles != null) {
        aClient.setListHiddenFiles(listHiddenFiles);
    }
    if (parserFactory != null) {
        aClient.setParserFactory(parserFactory);
    }
    if (passiveLocalIPAddress != null) {
        aClient.setPassiveLocalIPAddress(passiveLocalIPAddress);
    }
    if (passiveNatWorkaround != null) {
        aClient.setPassiveNatWorkaround(passiveNatWorkaround);
    }
    if (proxy != null) {
        aClient.setProxy(proxy);
    }
    if (receieveDataSocketBufferSize != null) {
        aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize);
    }
    if (receiveBufferSize != null) {
        aClient.setReceiveBufferSize(receiveBufferSize);
    }
    if (remoteVerificationEnabled != null) {
        aClient.setRemoteVerificationEnabled(remoteVerificationEnabled);
    }
    if (reportActiveExternalIPAddress != null) {
        aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress);
    }
    if (sendBufferSize != null) {
        aClient.setSendBufferSize(sendBufferSize);
    }
    if (sendDataSocketBufferSize != null) {
        aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize);
    }
    if (strictMultilineParsing != null) {
        aClient.setStrictMultilineParsing(strictMultilineParsing);
    }
    if (tcpNoDelay != null) {
        aClient.setTcpNoDelay(tcpNoDelay);
    }
    if (useEPSVwithIPv4 != null) {
        aClient.setUseEPSVwithIPv4(useEPSVwithIPv4);
    }

    if (systemKey != null) {
        FTPClientConfig aClientConfig = new FTPClientConfig(systemKey);
        if (defaultDateFormat != null) {
            aClientConfig.setDefaultDateFormatStr(defaultDateFormat);
        }
        if (recentDateFormat != null) {
            aClientConfig.setRecentDateFormatStr(recentDateFormat);
        }
        if (serverLanguageCode != null) {
            aClientConfig.setServerLanguageCode(serverLanguageCode);
        }
        if (shortMonthNames != null) {
            aClientConfig.setShortMonthNames(shortMonthNames);
        }
        if (serverTimeZoneId != null) {
            aClientConfig.setServerTimeZoneId(serverTimeZoneId);
        }
        aClient.configure(aClientConfig);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Connecting to : {}", host);
    }

    if (port == null) {
        aClient.connect(host);
    } else {
        aClient.connect(host, port);
    }

    int aReplyCode = aClient.getReplyCode();

    if (!FTPReply.isPositiveCompletion(aReplyCode)) {
        aClient.disconnect();
        throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode);
    }

    try {
        if (localPassiveMode) {
            aClient.enterLocalPassiveMode();
        }

        boolean aIsLoggedIn = false;
        if (account == null) {
            aIsLoggedIn = aClient.login(username, password);
        } else {
            aIsLoggedIn = aClient.login(username, password, account);
        }
        if (!aIsLoggedIn) {
            throw new IOException(aClient.getReplyString());
        }
    } catch (IOException e) {
        aClient.disconnect();
        throw e;
    }

    if (fileTransferMode != null) {
        aClient.setFileTransferMode(fileTransferMode);
    }
    if (fileType != null) {
        aClient.setFileType(fileType);
    }

    return aClient;
}

From source file:com.o6Systems.utils.net.FTPModule.java

private int executeFtpCommand(String[] args) throws UnknownHostException {
    boolean storeFile = false, binaryTransfer = false, error = false, listFiles = false, listNames = false,
            hidden = false;// ww  w .  jav  a  2s  .com
    boolean localActive = false, useEpsvWithIPv4 = false, feat = false, printHash = false;
    boolean mlst = false, mlsd = false;
    boolean lenient = false;
    long keepAliveTimeout = -1;
    int controlKeepAliveReplyTimeout = -1;
    int minParams = 5; // listings require 3 params
    String protocol = null; // SSL protocol
    String doCommand = null;
    String trustmgr = null;
    String proxyHost = null;
    int proxyPort = 80;
    String proxyUser = null;
    String proxyPassword = null;
    String username = null;
    String password = null;

    int base = 0;

    // Print the command

    System.out.println("----------FTP MODULE CALL----------");

    for (int i = 0; i < args.length; i++) {
        System.out.println(args[i]);
    }

    System.out.println("--------------------");
    //

    for (base = 0; base < args.length; base++) {
        if (args[base].equals("-s")) {
            storeFile = true;
        } else if (args[base].equals("-a")) {
            localActive = true;
        } else if (args[base].equals("-A")) {
            username = "anonymous";
            password = System.getProperty("user.name") + "@" + InetAddress.getLocalHost().getHostName();
        } else if (args[base].equals("-b")) {
            binaryTransfer = true;
        } else if (args[base].equals("-c")) {
            doCommand = args[++base];
            minParams = 3;
        } else if (args[base].equals("-d")) {
            mlsd = true;
            minParams = 3;
        } else if (args[base].equals("-e")) {
            useEpsvWithIPv4 = true;
        } else if (args[base].equals("-f")) {
            feat = true;
            minParams = 3;
        } else if (args[base].equals("-h")) {
            hidden = true;
        } else if (args[base].equals("-k")) {
            keepAliveTimeout = Long.parseLong(args[++base]);
        } else if (args[base].equals("-l")) {
            listFiles = true;
            minParams = 3;
        } else if (args[base].equals("-L")) {
            lenient = true;
        } else if (args[base].equals("-n")) {
            listNames = true;
            minParams = 3;
        } else if (args[base].equals("-p")) {
            protocol = args[++base];
        } else if (args[base].equals("-t")) {
            mlst = true;
            minParams = 3;
        } else if (args[base].equals("-w")) {
            controlKeepAliveReplyTimeout = Integer.parseInt(args[++base]);
        } else if (args[base].equals("-T")) {
            trustmgr = args[++base];
        } else if (args[base].equals("-PrH")) {
            proxyHost = args[++base];
            String parts[] = proxyHost.split(":");
            if (parts.length == 2) {
                proxyHost = parts[0];
                proxyPort = Integer.parseInt(parts[1]);
            }
        } else if (args[base].equals("-PrU")) {
            proxyUser = args[++base];
        } else if (args[base].equals("-PrP")) {
            proxyPassword = args[++base];
        } else if (args[base].equals("-#")) {
            printHash = true;
        } else {
            break;
        }
    }

    int remain = args.length - base;
    if (username != null) {
        minParams -= 2;
    }

    String server = args[base++];
    int port = 0;
    String parts[] = server.split(":");
    if (parts.length == 2) {
        server = parts[0];
        port = Integer.parseInt(parts[1]);
    }
    if (username == null) {
        username = args[base++];
        password = args[base++];
    }

    String remote = null;
    if (args.length - base > 0) {
        remote = args[base++];
    }

    String local = null;
    if (args.length - base > 0) {
        local = args[base++];
    }

    final FTPClient ftp;
    if (protocol == null) {
        if (proxyHost != null) {
            System.out.println("Using HTTP proxy server: " + proxyHost);
            ftp = new FTPHTTPClient(proxyHost, proxyPort, proxyUser, proxyPassword);
        } else {
            ftp = new FTPClient();
        }
    } else {
        FTPSClient ftps;
        if (protocol.equals("true")) {
            ftps = new FTPSClient(true);
        } else if (protocol.equals("false")) {
            ftps = new FTPSClient(false);
        } else {
            String prot[] = protocol.split(",");
            if (prot.length == 1) { // Just protocol
                ftps = new FTPSClient(protocol);
            } else { // protocol,true|false
                ftps = new FTPSClient(prot[0], Boolean.parseBoolean(prot[1]));
            }
        }
        ftp = ftps;
        if ("all".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        } else if ("valid".equals(trustmgr)) {
            ftps.setTrustManager(TrustManagerUtils.getValidateServerCertificateTrustManager());
        } else if ("none".equals(trustmgr)) {
            ftps.setTrustManager(null);
        }
    }

    if (printHash) {
        ftp.setCopyStreamListener(createListener());
    }
    if (keepAliveTimeout >= 0) {
        ftp.setControlKeepAliveTimeout(keepAliveTimeout);
    }
    if (controlKeepAliveReplyTimeout >= 0) {
        ftp.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    ftp.setListHiddenFiles(hidden);

    // suppress login details
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));

    try {
        int reply;
        if (port > 0) {
            ftp.connect(server, port);
        } else {
            ftp.connect(server);
        }
        System.out.println("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));

        // After connection attempt, you should check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            return 1;
        }
    } catch (IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        return 1;
    }

    __main: try {
        if (!ftp.login(username, password)) {
            ftp.logout();
            error = true;
            break __main;
        }

        System.out.println("Remote system is " + ftp.getSystemType());

        if (binaryTransfer) {
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
        } else {
            // in theory this should not be necessary as servers should default to ASCII
            // but they don't all do so - see NET-500
            ftp.setFileType(FTP.ASCII_FILE_TYPE);
        }

        // Use passive mode as default because most of us are
        // behind firewalls these days.
        if (localActive) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        ftp.setUseEPSVwithIPv4(useEpsvWithIPv4);

        if (storeFile) {
            InputStream input;

            input = new FileInputStream(local);

            ftp.storeFile(remote, input);

            input.close();
        } else if (listFiles) {
            if (lenient) {
                FTPClientConfig config = new FTPClientConfig();
                config.setLenientFutureDates(true);
                ftp.configure(config);
            }

            for (FTPFile f : ftp.listFiles(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlsd) {
            for (FTPFile f : ftp.mlistDir(remote)) {
                System.out.println(f.getRawListing());
                System.out.println(f.toFormattedString());
            }
        } else if (mlst) {
            FTPFile f = ftp.mlistFile(remote);
            if (f != null) {
                System.out.println(f.toFormattedString());
            }
        } else if (listNames) {
            for (String s : ftp.listNames(remote)) {
                System.out.println(s);
            }
        } else if (feat) {
            // boolean feature check
            if (remote != null) { // See if the command is present
                if (ftp.hasFeature(remote)) {
                    System.out.println("Has feature: " + remote);
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " was not detected");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }

                // Strings feature check
                String[] features = ftp.featureValues(remote);
                if (features != null) {
                    for (String f : features) {
                        System.out.println("FEAT " + remote + "=" + f + ".");
                    }
                } else {
                    if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                        System.out.println("FEAT " + remote + " is not present");
                    } else {
                        System.out.println("Command failed: " + ftp.getReplyString());
                    }
                }
            } else {
                if (ftp.features()) {
                    //                        Command listener has already printed the output
                } else {
                    System.out.println("Failed: " + ftp.getReplyString());
                }
            }
        } else if (doCommand != null) {
            if (ftp.doCommand(doCommand, remote)) {
                //                  Command listener has already printed the output
                //                    for(String s : ftp.getReplyStrings()) {
                //                        System.out.println(s);
                //                    }
            } else {
                System.out.println("Failed: " + ftp.getReplyString());
            }
        } else {
            OutputStream output;

            output = new FileOutputStream(local);

            ftp.retrieveFile(remote, output);

            output.close();
        }

        ftp.noop(); // check that control connection is working OK

        ftp.logout();
    } catch (FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
    }

    return error ? 1 : 0;
}