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:com.droid.app.fotobot.FotoBot.java

public boolean files_to_ftp(List<String> FTP_files) {
    String server;//  w  w w. j a  v  a 2 s .c  o  m
    int port;
    String user;
    String pass;

    String FTP_folder = "";

    if (FTP_server.contains("/")) {

        FTP_folder = FTP_server.substring(FTP_server.indexOf("/", 1));
        FTP_folder = FTP_folder.substring(1);

        server = FTP_server.substring(0, FTP_server.indexOf("/", 1));
    } else {
        server = FTP_server;
    }

    port = Integer.parseInt(FTP_port);
    user = FTP_username;
    pass = FTP_password;

    SendMessage("FTP user: " + "<br>" + user, MSG_PASS);
    SendMessage("FTP folder: " + "<br>" + FTP_folder, MSG_PASS);
    SendMessage("FTP server: " + "<br>" + server, MSG_PASS);

    FTPClient ftpClient = new FTPClient();

    try {
        int reply;

        ftpClient.connect(server, port);
        System.out.println("Connected to " + server + ".");
        System.out.print(ftpClient.getReplyString());
        reply = ftpClient.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpClient.disconnect();
            System.err.println("FTP server refused connection.");
            SendMessage("FTP   ?", MSG_FAIL);
            return false;
        }
    } catch (Exception e) {
    }

    try {
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SendMessage(
                    " ?   FTP ?,      FTP  ?.",
                    MSG_FAIL);
            return false;
        }
    } catch (Exception e) {

    }

    // chdir

    if (FTP_folder.length() > 1) {
        try {
            ftpClient.changeWorkingDirectory(FTP_folder);

            if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                ftpClient.disconnect();
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.err.println("FTP chdir error");
                SendMessage(
                        "FTP  ?    <br>" + FTP_folder,
                        MSG_FAIL);
                return false;
            }

            SendMessage("FTP   <br>" + FTP_folder, MSG_PASS);
            System.out.println("Successfully changed working directory.");
        } catch (Exception e) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            SendMessage("FTP  ?    <br>" + FTP_folder,
                    MSG_FAIL);
            System.out.println("Failed to change working directory.");
            return false;
        }
    }

    try {
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (Exception e) {
        SendMessage("FTP   BINARY_FILE_TYPE", MSG_FAIL);
        System.out.println("Failed to change to BINARY_FILE_TYPE.");
        return false;
    }

    // APPROACH #1: uploads first file using an InputStream

    for (String str : FTP_files) {
        File firstLocalFile = new File(str);

        String firstRemoteFile = firstLocalFile.getName();

        try {
            InputStream inputStream = new FileInputStream(firstLocalFile);

            SendMessage("? ", MSG_PASS);
            boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
            inputStream.close();

            if (done) {
                SendMessage(" " + "<br>" + str + "<br>" + " ", MSG_PASS);
            }
        } catch (IOException ex) {
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            SendMessage(" ?  " + "<br>" + str + "<br>"
                    + ftpClient.getReplyCode() + "\n" + ftpClient.getReplyString() + "\n" + ex.getMessage()
                    + "<br>"
                    + "     FTP  ?.",
                    MSG_FAIL);
            ex.printStackTrace();
        }

    }

    try {
        if (ftpClient.isConnected()) {
            ftpClient.logout();
            ftpClient.disconnect();
            SendMessage("FTP ???? ", MSG_PASS);
            fbpause(h, 3);
            return true;
        }
    } catch (IOException ex) {
        ex.printStackTrace();
        SendMessage("FTP ???? ", MSG_FAIL);
    }

    return false;

}

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

/**
 * auto find the time difference between local and remote
 * @param ftp handle to ftp client// w ww  .  j  a va 2 s . co  m
 * @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 occuring 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:com.microsoft.tooling.msservices.helpers.azure.AzureManagerImpl.java

@Override
public void publishWebArchiveArtifact(@NotNull String subscriptionId, @NotNull String webSpaceName,
        @NotNull String webSiteName, @NotNull String artifactPath, @NotNull boolean isDeployRoot,
        @NotNull String artifactName) throws AzureCmdException {
    WebSitePublishSettings webSitePublishSettings = getWebSitePublishSettings(subscriptionId, webSpaceName,
            webSiteName);/*  w ww  . j a v  a2s .co  m*/
    WebSitePublishSettings.FTPPublishProfile publishProfile = null;
    for (PublishProfile pp : webSitePublishSettings.getPublishProfileList()) {
        if (pp instanceof FTPPublishProfile) {
            publishProfile = (FTPPublishProfile) pp;
            break;
        }
    }

    if (publishProfile == null) {
        throw new AzureCmdException("Unable to retrieve FTP credentials to publish web site");
    }

    URI uri;

    try {
        uri = new URI(publishProfile.getPublishUrl());
    } catch (URISyntaxException e) {
        throw new AzureCmdException("Unable to parse FTP Publish Url information", e);
    }

    final FTPClient ftp = new FTPClient();

    try {
        ftp.connect(uri.getHost());
        final int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new AzureCmdException("Unable to connect to FTP server");
        }

        if (!ftp.login(publishProfile.getUserName(), publishProfile.getPassword())) {
            ftp.logout();
            throw new AzureCmdException("Unable to login to FTP server");
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (publishProfile.isFtpPassiveMode()) {
            ftp.enterLocalPassiveMode();
        }

        String targetDir = getAbsolutePath(uri.getPath());
        targetDir += "/webapps";

        InputStream input = new FileInputStream(artifactPath);
        if (isDeployRoot) {
            ftp.storeFile(targetDir + "/ROOT.war", input);
        } else {
            ftp.storeFile(targetDir + "/" + artifactName + ".war", input);
        }
        input.close();
        ftp.logout();
    } catch (IOException e) {
        throw new AzureCmdException("Unable to connect to the FTP server", e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ignored) {
            }
        }
    }
}

From source file:com.ut.healthelink.service.impl.transactionOutManagerImpl.java

/**
 * The 'FTPTargetFile' function will get the FTP details and send off the generated file
 *
 * @param batchId The id of the batch to FTP the file for
 *//* ww w .j  av a2s.c  o  m*/
private void FTPTargetFile(int batchId, configurationTransport transportDetails) throws Exception {

    try {

        /* Update the status of the batch to locked */
        transactionOutDAO.updateBatchStatus(batchId, 22);

        List<transactionTarget> targets = transactionOutDAO.getTransactionsByBatchDLId(batchId);

        if (!targets.isEmpty()) {

            for (transactionTarget target : targets) {

                /* Need to update the uploaded batch status */
                transactionInManager.updateBatchStatus(target.getbatchUploadId(), 22, "");

                /* Need to update the uploaded batch transaction status */
                transactionInManager.updateTransactionStatus(target.getbatchUploadId(),
                        target.gettransactionInId(), 0, 37);

                /* Update the downloaded batch transaction status */
                transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 37);

            }

        }

        /* get the batch details */
        batchDownloads batchFTPFileInfo = transactionOutDAO.getBatchDetails(batchId);

        /* Get the FTP Details */
        configurationFTPFields ftpDetails = configurationTransportManager
                .getTransportFTPDetailsPush(transportDetails.getId());

        if ("SFTP".equals(ftpDetails.getprotocol())) {

            JSch jsch = new JSch();
            Session session = null;
            ChannelSftp channel = null;
            FileInputStream localFileStream = null;

            String user = ftpDetails.getusername();
            int port = ftpDetails.getport();
            String host = ftpDetails.getip();

            Organization orgDetails = organizationManager.getOrganizationById(
                    configurationManager.getConfigurationById(transportDetails.getconfigId()).getorgId());

            if (ftpDetails.getcertification() != null && !"".equals(ftpDetails.getcertification())) {

                File newFile = null;

                fileSystem dir = new fileSystem();
                dir.setDir(orgDetails.getcleanURL(), "certificates");

                jsch.addIdentity(new File(dir.getDir() + ftpDetails.getcertification()).getAbsolutePath());
                session = jsch.getSession(user, host, port);
            } else if (ftpDetails.getpassword() != null && !"".equals(ftpDetails.getpassword())) {
                session = jsch.getSession(user, host, port);
                session.setPassword(ftpDetails.getpassword());
            }

            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(2000);

            session.connect();

            channel = (ChannelSftp) session.openChannel("sftp");

            channel.connect();

            if (ftpDetails.getdirectory() != null && !"".equals(ftpDetails.getdirectory())) {
                channel.cd(ftpDetails.getdirectory());

                String fileName = null;

                int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf(".");

                if (findExt >= 0) {
                    fileName = batchFTPFileInfo.getoutputFIleName();
                } else {
                    fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".")
                            .append(transportDetails.getfileExt()).toString();
                }

                //Set the directory to save the brochures to
                fileSystem dir = new fileSystem();

                String filelocation = transportDetails.getfileLocation();
                filelocation = filelocation.replace("/bowlink/", "");
                dir.setDirByName(filelocation);

                File file = new File(dir.getDir() + fileName);

                if (file.exists()) {
                    FileInputStream fileInput = new FileInputStream(file);

                    channel.put(fileInput, fileName);
                }

            }

            channel.disconnect();
            session.disconnect();

        } else {
            FTPClient ftp;

            if ("FTP".equals(ftpDetails.getprotocol())) {
                ftp = new FTPClient();
            } else {
                FTPSClient ftps;
                ftps = new FTPSClient(true);

                ftp = ftps;
                ftps.setTrustManager(null);
            }

            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            ftp.setDefaultTimeout(3000);
            ftp.setConnectTimeout(3000);

            if (ftpDetails.getport() > 0) {
                ftp.connect(ftpDetails.getip(), ftpDetails.getport());
            } else {
                ftp.connect(ftpDetails.getip());
            }

            int reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
            } else {
                ftp.login(ftpDetails.getusername(), ftpDetails.getpassword());

                ftp.enterLocalPassiveMode();

                String fileName = null;

                int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf(".");

                if (findExt >= 0) {
                    fileName = batchFTPFileInfo.getoutputFIleName();
                } else {
                    fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".")
                            .append(transportDetails.getfileExt()).toString();
                }

                //Set the directory to save the brochures to
                fileSystem dir = new fileSystem();

                String filelocation = transportDetails.getfileLocation();
                filelocation = filelocation.replace("/bowlink/", "");
                dir.setDirByName(filelocation);

                File file = new File(dir.getDir() + fileName);

                FileInputStream fileInput = new FileInputStream(file);

                ftp.changeWorkingDirectory(ftpDetails.getdirectory());
                ftp.storeFile(fileName, fileInput);
                ftp.logout();
                ftp.disconnect();

            }
        }

        // we should delete file now that we ftp'ed the file
        try {
            fileSystem dir = new fileSystem();
            String filelocation = transportDetails.getfileLocation();
            filelocation = filelocation.replace("/bowlink/", "");
            dir.setDirByName(filelocation);

            File sourceFile = new File(dir.getDir() + batchFTPFileInfo.getoutputFIleName());
            if (sourceFile.exists()) {
                sourceFile.delete();
            }

            transactionOutDAO.updateBatchStatus(batchId, 23);

            for (transactionTarget target : targets) {

                /* Need to update the uploaded batch status */
                transactionInManager.updateBatchStatus(target.getbatchUploadId(), 23, "");

                /* Need to update the uploaded batch transaction status */
                transactionInManager.updateTransactionStatus(target.getbatchUploadId(),
                        target.gettransactionInId(), 0, 20);

                /* Update the downloaded batch transaction status */
                transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 20);

            }

        } catch (Exception e) {
            throw new Exception(
                    "Error occurred during FTP - delete file and update statuses. batchId: " + batchId, e);

        }
    } catch (Exception e) {
        throw new Exception("Error occurred trying to FTP a batch target. batchId: " + batchId, e);
    }

}

From source file:com.atomicleopard.thundr.ftp.commons.FTPClient.java

/**
 * There are a few FTPClient methods that do not complete the
 * entire sequence of FTP commands to complete a transaction.  These
 * commands require some action by the programmer after the reception
 * of a positive intermediate command.  After the programmer's code
 * completes its actions, it must call this method to receive
 * the completion reply from the server and verify the success of the
 * entire transaction.//  w w w . j av  a 2 s  . c om
 * <p>
 * For example,
 * <pre>
 * InputStream input;
 * OutputStream output;
 * input  = new FileInputStream("foobaz.txt");
 * output = ftp.storeFileStream("foobar.txt")
 * if(!FTPReply.isPositiveIntermediate(ftp.getReplyCode())) {
 *     input.close();
 *     output.close();
 *     ftp.logout();
 *     ftp.disconnect();
 *     System.err.println("File transfer failed.");
 *     System.exit(1);
 * }
 * Util.copyStream(input, output);
 * input.close();
 * output.close();
 * // Must call completePendingCommand() to finish command.
 * if(!ftp.completePendingCommand()) {
 *     ftp.logout();
 *     ftp.disconnect();
 *     System.err.println("File transfer failed.");
 *     System.exit(1);
 * }
 * </pre>
 * <p>
 * @return True if successfully completed, false if not.
 * @exception FTPConnectionClosedException
 *      If the FTP server prematurely closes the connection as a result
 *      of the client being idle or some other reason causing the server
 *      to send FTP reply code 421.  This exception may be caught either
 *      as an IOException or independently as itself.
 * @exception IOException  If an I/O error occurs while either sending a
 *      command to the server or receiving a reply from the server.
 */
public boolean completePendingCommand() throws IOException {
    return FTPReply.isPositiveCompletion(getReply());
}

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 a2s .c  o  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.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 {//from   w ww . j a  v  a  2  s  .c  om
        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: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>//from ww  w. j a  va  2  s  .  c  om
 * @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:ProtocolRunner.java

private static void handleFTP(
    FTPClient client, //from ww w .  j  a  v a 2s .  c  o m
    ProtocolRunner runner, 
    String commandString) 
    throws IOException {
        
    if(commandString == null) { // means just connected        
            
        // check if the server response was valid
        if(!FTPReply.isPositiveCompletion(client.getReplyCode())) {
            runner.handleDisconnect();
            return;
        }
            
    } else { // need to handle a command
        client.sendCommand(commandString);
    }
        
    runner.getTCPServerResponse().append(client.getReplyString());
}

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

/**
 * Runs the task./*  ww w. j a v  a  2  s  .  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
            }
        }
    }
}