Example usage for org.apache.commons.net.ftp FTPReply isPositiveCompletion

List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion

Introduction

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

Prototype

public static boolean isPositiveCompletion(int reply) 

Source Link

Document

Determine if a reply code is a positive completion response.

Usage

From source file:org.apache.nutch.protocol.ftp.FtpResponse.java

private void getFileAsHttpResponse(String path, long lastModified) throws IOException {

    ByteArrayOutputStream os = null;
    List<FTPFile> list = null;

    try {/*  www.j a v  a  2 s  . c o  m*/
        // first get its possible attributes
        list = new LinkedList<FTPFile>();
        ftp.client.retrieveList(path, list, ftp.maxContentLength, ftp.parser);

        FTPFile ftpFile = (FTPFile) list.get(0);
        this.headers.set(Response.CONTENT_LENGTH, new Long(ftpFile.getSize()).toString());
        this.headers.set(Response.LAST_MODIFIED, HttpDateFormat.toString(ftpFile.getTimestamp()));
        // don't retrieve the file if not changed.
        if (ftpFile.getTimestamp().getTimeInMillis() <= lastModified) {
            code = 304;
            return;
        }
        os = new ByteArrayOutputStream(ftp.getBufferSize());
        ftp.client.retrieveFile(path, os, ftp.maxContentLength);

        this.content = os.toByteArray();

        // // approximate bytes sent and read
        // if (this.httpAccounting != null) {
        // this.httpAccounting.incrementBytesSent(path.length());
        // this.httpAccounting.incrementBytesRead(this.content.length);
        // }

        this.code = 200; // http OK

    } catch (FtpExceptionControlClosedByForcedDataClose e) {

        // control connection is off, clean up
        // ftp.client.disconnect();
        if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
            Ftp.LOG.info("delete client because server cut off control channel: " + e);
        }
        ftp.client = null;

        // in case this FtpExceptionControlClosedByForcedDataClose is
        // thrown by retrieveList() (not retrieveFile()) above,
        if (os == null) { // indicating throwing by retrieveList()
            // throw new FtpException("fail to get attibutes: "+path);
            if (Ftp.LOG.isWarnEnabled()) {
                Ftp.LOG.warn("Please try larger maxContentLength for ftp.client.retrieveList(). " + e);
            }
            // in a way, this is our request fault
            this.code = 400; // http Bad request
            return;
        }

        FTPFile ftpFile = (FTPFile) list.get(0);
        this.headers.set(Response.CONTENT_LENGTH, new Long(ftpFile.getSize()).toString());
        // this.headers.put("content-type", "text/html");
        this.headers.set(Response.LAST_MODIFIED, HttpDateFormat.toString(ftpFile.getTimestamp()));
        this.content = os.toByteArray();
        if (ftpFile.getTimestamp().getTimeInMillis() <= lastModified) {
            code = 304;
            return;
        }

        // // approximate bytes sent and read
        // if (this.httpAccounting != null) {
        // this.httpAccounting.incrementBytesSent(path.length());
        // this.httpAccounting.incrementBytesRead(this.content.length);
        // }

        this.code = 200; // http OK

    } catch (FtpExceptionCanNotHaveDataConnection e) {

        if (FTPReply.isPositiveCompletion(ftp.client.cwd(path))) {
            // it is not a file, but dir, so redirect as a dir
            this.headers.set(Response.LOCATION, path + "/");
            this.code = 300; // http redirect
            // fixme, should we do ftp.client.cwd("/"), back to top dir?
        } else {
            // it is not a dir either
            this.code = 404; // http Not Found
        }

    } catch (FtpExceptionUnknownForcedDataClose e) {
        // Please note control channel is still live.
        // in a way, this is our request fault
        if (Ftp.LOG.isWarnEnabled()) {
            Ftp.LOG.warn("Unrecognized reply after forced close of data channel. "
                    + "If this is acceptable, please modify Client.java accordingly. " + e);
        }
        this.code = 400; // http Bad Request
    }

}

From source file:org.apache.nutch.protocol.ftp.FtpResponse.java

private void getDirAsHttpResponse(String path, long lastModified) throws IOException {
    List<FTPFile> list = new LinkedList<FTPFile>();

    try {/*w w w .  j  av a2  s  .co  m*/

        // change to that dir first
        if (!FTPReply.isPositiveCompletion(ftp.client.cwd(path))) {
            this.code = 404; // http Not Found
            return;
        }

        // fixme, should we do ftp.client.cwd("/"), back to top dir?

        ftp.client.retrieveList(null, list, ftp.maxContentLength, ftp.parser);
        this.content = list2html(list, path, "/".equals(path) ? false : true);
        this.headers.set(Response.CONTENT_LENGTH, new Integer(this.content.length).toString());
        this.headers.set(Response.CONTENT_TYPE, "text/html");
        // this.headers.put("Last-Modified", null);

        // // approximate bytes sent and read
        // if (this.httpAccounting != null) {
        // this.httpAccounting.incrementBytesSent(path.length());
        // this.httpAccounting.incrementBytesRead(this.content.length);
        // }

        this.code = 200; // http OK

    } catch (FtpExceptionControlClosedByForcedDataClose e) {

        // control connection is off, clean up
        // ftp.client.disconnect();
        if ((ftp.followTalk) && (Ftp.LOG.isInfoEnabled())) {
            Ftp.LOG.info("delete client because server cut off control channel: " + e);
        }
        ftp.client = null;

        this.content = list2html(list, path, "/".equals(path) ? false : true);
        this.headers.set(Response.CONTENT_LENGTH, new Integer(this.content.length).toString());
        this.headers.set(Response.CONTENT_TYPE, "text/html");
        // this.headers.put("Last-Modified", null);

        // // approximate bytes sent and read
        // if (this.httpAccounting != null) {
        // this.httpAccounting.incrementBytesSent(path.length());
        // this.httpAccounting.incrementBytesRead(this.content.length);
        // }

        this.code = 200; // http OK

    } catch (FtpExceptionUnknownForcedDataClose e) {
        // Please note control channel is still live.
        // in a way, this is our request fault
        if (Ftp.LOG.isWarnEnabled()) {
            Ftp.LOG.warn("Unrecognized reply after forced close of data channel. "
                    + "If this is acceptable, please modify Client.java accordingly. " + e);
        }
        this.code = 400; // http Bad Request
    } catch (FtpExceptionCanNotHaveDataConnection e) {
        if (Ftp.LOG.isWarnEnabled()) {
            Ftp.LOG.warn("" + e);
        }
        this.code = 500; // http Iternal Server Error
    }

}

From source file:org.apache.ofbiz.common.FtpServices.java

public static Map<String, Object> putFile(DispatchContext dctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    Debug.logInfo("[putFile] starting...", module);
    InputStream localFile = null;
    try {/*w w w. j  a va 2 s  . c om*/
        localFile = new FileInputStream((String) context.get("localFilename"));
    } catch (IOException ioe) {
        Debug.logError(ioe, "[putFile] Problem opening local file", module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
    }
    List<String> errorList = new LinkedList<String>();
    FTPClient ftp = new FTPClient();
    try {
        Integer defaultTimeout = (Integer) context.get("defaultTimeout");
        if (UtilValidate.isNotEmpty(defaultTimeout)) {
            Debug.logInfo("[putFile] set default timeout to: " + defaultTimeout.intValue() + " milliseconds",
                    module);
            ftp.setDefaultTimeout(defaultTimeout.intValue());
        }
        Debug.logInfo("[putFile] connecting to: " + (String) context.get("hostname"), module);
        ftp.connect((String) context.get("hostname"));
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            Debug.logInfo("[putFile] Server refused connection", module);
            errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
        } else {
            String username = (String) context.get("username");
            String password = (String) context.get("password");
            Debug.logInfo("[putFile] logging in: username=" + username + ", password=" + password, module);
            if (!ftp.login(username, password)) {
                Debug.logInfo("[putFile] login failed", module);
                errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure",
                        UtilMisc.toMap("username", username, "password", password), locale));
            } else {
                Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                if (binary) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                Boolean passiveMode = (Boolean) context.get("passiveMode");
                boolean passive = (passiveMode == null) ? true : passiveMode.booleanValue();
                if (passive) {
                    ftp.enterLocalPassiveMode();
                }
                Debug.logInfo("[putFile] storing local file remotely as: " + context.get("remoteFilename"),
                        module);
                if (!ftp.storeFile((String) context.get("remoteFilename"), localFile)) {
                    Debug.logInfo("[putFile] store was unsuccessful", module);
                    errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully",
                            UtilMisc.toMap("replyString", ftp.getReplyString()), locale));
                } else {
                    Debug.logInfo("[putFile] store was successful", module);
                    List<String> siteCommands = checkList(context.get("siteCommands"), String.class);
                    if (siteCommands != null) {
                        for (String command : siteCommands) {
                            Debug.logInfo("[putFile] sending SITE command: " + command, module);
                            if (!ftp.sendSiteCommand(command)) {
                                errorList.add(UtilProperties.getMessage(resource, "CommonFtpSiteCommandFailed",
                                        UtilMisc.toMap("command", command, "replyString", ftp.getReplyString()),
                                        locale));
                            }
                        }
                    }
                }
            }
            ftp.logout();
        }
    } catch (IOException ioe) {
        Debug.logWarning(ioe, "[putFile] caught exception: " + ioe.getMessage(), module);
        errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer",
                UtilMisc.toMap("errorString", ioe.getMessage()), locale));
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "[putFile] Problem with FTP disconnect: ", module);
        }
        try {
            localFile.close();
        } catch (Exception e) {
            Debug.logWarning(e, "[putFile] Problem closing local file: ", module);
        }
    }
    if (errorList.size() > 0) {
        Debug.logError("[putFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList,
                module);
        return ServiceUtil.returnError(errorList);
    }
    Debug.logInfo("[putFile] finished successfully", module);
    return ServiceUtil.returnSuccess();
}

From source file:org.apache.ofbiz.common.FtpServices.java

public static Map<String, Object> getFile(DispatchContext dctx, Map<String, ?> context) {
    Locale locale = (Locale) context.get("locale");
    String localFilename = (String) context.get("localFilename");
    OutputStream localFile = null;
    try {//from  w w  w  . j ava2 s .  c o m
        localFile = new FileOutputStream(localFilename);
    } catch (IOException ioe) {
        Debug.logError(ioe, "[getFile] Problem opening local file", module);
        return ServiceUtil
                .returnError(UtilProperties.getMessage(resource, "CommonFtpFileCannotBeOpen", locale));
    }
    List<String> errorList = new LinkedList<String>();
    FTPClient ftp = new FTPClient();
    try {
        Integer defaultTimeout = (Integer) context.get("defaultTimeout");
        if (UtilValidate.isNotEmpty(defaultTimeout)) {
            Debug.logInfo("[getFile] Set default timeout to: " + defaultTimeout.intValue() + " milliseconds",
                    module);
            ftp.setDefaultTimeout(defaultTimeout.intValue());
        }
        ftp.connect((String) context.get("hostname"));
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            errorList.add(UtilProperties.getMessage(resource, "CommonFtpConnectionRefused", locale));
        } else {
            String username = (String) context.get("username");
            String password = (String) context.get("password");
            if (!ftp.login(username, password)) {
                errorList.add(UtilProperties.getMessage(resource, "CommonFtpLoginFailure",
                        UtilMisc.toMap("username", username, "password", password), locale));
            } else {
                Boolean binaryTransfer = (Boolean) context.get("binaryTransfer");
                boolean binary = (binaryTransfer == null) ? false : binaryTransfer.booleanValue();
                if (binary) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                Boolean passiveMode = (Boolean) context.get("passiveMode");
                boolean passive = (passiveMode == null) ? false : passiveMode.booleanValue();
                if (passive) {
                    ftp.enterLocalPassiveMode();
                }
                if (!ftp.retrieveFile((String) context.get("remoteFilename"), localFile)) {
                    errorList.add(UtilProperties.getMessage(resource, "CommonFtpFileNotSentSuccesfully",
                            UtilMisc.toMap("replyString", ftp.getReplyString()), locale));
                }
            }
            ftp.logout();
        }
    } catch (IOException ioe) {
        Debug.logWarning(ioe, "[getFile] caught exception: " + ioe.getMessage(), module);
        errorList.add(UtilProperties.getMessage(resource, "CommonFtpProblemWithTransfer",
                UtilMisc.toMap("errorString", ioe.getMessage()), locale));
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.disconnect();
            }
        } catch (Exception e) {
            Debug.logWarning(e, "[getFile] Problem with FTP disconnect: ", module);
        }
        try {
            localFile.close();
        } catch (Exception e) {
            Debug.logWarning(e, "[getFile] Problem closing local file: ", module);
        }
    }
    if (errorList.size() > 0) {
        Debug.logError("[getFile] The following error(s) (" + errorList.size() + ") occurred: " + errorList,
                module);
        return ServiceUtil.returnError(errorList);
    }
    return ServiceUtil.returnSuccess();
}

From source file:org.apache.sqoop.connector.ftp.ftpclient.FtpConnectorClient.java

/**
 * Connect to the FTP server./*w  w  w. j  ava2  s .c om*/
 *
 * @param username Username for server login.
 * @param pass Password for server login.
 *
 * @throws SqoopException Thrown if an error occurs while connecting to server.
 */
public void connect(String username, String pass) throws SqoopException {

    try {
        ftpClient.connect(ftpServer, ftpPort);
        LOG.info(getServerReplyAsString());
        int replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftpClient.disconnect();
            LOG.error("Operation failed. Server reply code: " + replyCode);
            throw new SqoopException(FtpConnectorError.FTP_CONNECTOR_0001, "Server reply code=" + replyCode);
        }

        boolean success = ftpClient.login(username, pass);
        LOG.info(getServerReplyAsString());
        if (!success) {
            ftpClient.disconnect();
            LOG.error("Could not login to the server" + ftpServer);
            throw new SqoopException(FtpConnectorError.FTP_CONNECTOR_0001);
        } else {
            LOG.info("logged into " + ftpServer);
        }
    } catch (IOException e) {
        LOG.error("Caught IOException connecting to FTP server: " + e.getMessage());
        throw new SqoopException(FtpConnectorError.FTP_CONNECTOR_0001, "Caught IOException: " + e.getMessage(),
                e);
    }
}

From source file:org.apache.sqoop.connector.mainframe.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(TransferableContext context, LinkConfiguration linkConfiguration)
        throws IOException {
    FTPClient ftp = null;//from w  w  w . ja  v a2s . c  o m
    try {
        String username = linkConfiguration.linkConfig.username;
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = linkConfiguration.linkConfig.password;
        }

        String connectString = linkConfiguration.linkConfig.uri;
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }

        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        // The following section to get the system key for FTPClientConfig is just there for testing purposes
        String systemKey = null;
        String systemTypeString = context.getString("spark.mainframe.connector.system.type", "MVS");
        if (systemTypeString.equals("MVS")) {
            systemKey = FTPClientConfig.SYST_MVS;
        } else if (systemTypeString.equals("UNIX")) {
            systemKey = FTPClientConfig.SYST_UNIX;
        } else {
            assert (false);
        }

        FTPClientConfig config = new FTPClientConfig(systemKey);
        ftp.configure(config);

        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set ASCII transfer mode
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}

From source file:org.apache.sqoop.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;// www .j  a v a 2 s . c  om
    try {
        String username = conf.get(DBConfiguration.USERNAME_PROPERTY);
        String password;
        if (username == null) {
            username = "anonymous";
            password = "";
        } else {
            password = DBConfiguration.getPassword((JobConf) conf);
        }

        String connectString = conf.get(DBConfiguration.URL_PROPERTY);
        String server = connectString;
        int port = 0;
        String[] parts = connectString.split(":");
        if (parts.length == 2) {
            server = parts[0];
            try {
                port = Integer.parseInt(parts[1]);
            } catch (NumberFormatException e) {
                LOG.warn("Invalid port number: " + e.toString());
            }
        }

        if (null != mockFTPClient) {
            ftp = mockFTPClient;
        } else {
            ftp = new FTPClient();
        }

        FTPClientConfig config = new FTPClientConfig(FTPClientConfig.SYST_MVS);
        ftp.configure(config);

        if (conf.getBoolean(JobBase.PROPERTY_VERBOSE, false)) {
            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
        }
        try {
            if (port > 0) {
                ftp.connect(server, port);
            } else {
                ftp.connect(server);
            }
        } catch (IOException ioexp) {
            throw new IOException("Could not connect to server " + server, ioexp);
        }

        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new IOException("FTP server " + server + " refused connection:" + ftp.getReplyString());
        }
        LOG.info("Connected to " + server + " on " + (port > 0 ? port : ftp.getDefaultPort()));
        if (!ftp.login(username, password)) {
            ftp.logout();
            throw new IOException("Could not login to server " + server + ":" + ftp.getReplyString());
        }
        // set ASCII transfer mode
        ftp.setFileType(FTP.ASCII_FILE_TYPE);
        // Use passive mode as default.
        ftp.enterLocalPassiveMode();
        LOG.info("System type detected: " + ftp.getSystemType());
    } catch (IOException ioe) {
        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
                // do nothing
            }
        }
        ftp = null;
        throw ioe;
    }
    return ftp;
}

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

/**
 * auto find the time difference between local and remote
 * @param ftp handle to ftp client//from  w ww . ja  v a2  s .  c om
 * @return number of millis to add to remote time to make it comparable to local time
 * @since ant 1.6
 */
private long getTimeDiff(FTPClient ftp) {
    long returnValue = 0;
    File tempFile = findFileName(ftp);
    try {
        // create a local temporary file
        FILE_UTILS.createNewFile(tempFile);
        long localTimeStamp = tempFile.lastModified();
        BufferedInputStream instream = new BufferedInputStream(new FileInputStream(tempFile));
        ftp.storeFile(tempFile.getName(), instream);
        instream.close();
        boolean success = FTPReply.isPositiveCompletion(ftp.getReplyCode());
        if (success) {
            FTPFile[] ftpFiles = ftp.listFiles(tempFile.getName());
            if (ftpFiles.length == 1) {
                long remoteTimeStamp = ftpFiles[0].getTimestamp().getTime().getTime();
                returnValue = localTimeStamp - remoteTimeStamp;
            }
            ftp.deleteFile(ftpFiles[0].getName());
        }
        // delegate the deletion of the local temp file to the delete task
        // because of race conditions occurring on Windows
        Delete mydelete = new Delete();
        mydelete.bindToOwner(this);
        mydelete.setFile(tempFile.getCanonicalFile());
        mydelete.execute();
    } catch (Exception e) {
        throw new BuildException(e, getLocation());
    }
    return returnValue;
}

From source file: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 w  ww  .  jav a 2 s  .  com
 * @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 {
        // TODO - 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:org.apache.tools.ant.taskdefs.optional.net.FTP.java

/**
 * Runs the task.//from ww w .j a va  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);

        ftp = new FTPClient();
        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
            }
        }
    }
}