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

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

Introduction

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

Prototype

public void connect(InetAddress host, int port) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.

Usage

From source file:org.apache.ftpserver.clienttests.LoginTest.java

public void testLoginWithMaxConnections() throws Exception {
    FTPClient client1 = new FTPClient();
    FTPClient client2 = new FTPClient();
    FTPClient client3 = new FTPClient();
    FTPClient client4 = new FTPClient();

    try {//from  ww  w .  j  a  va 2 s  . c  o  m
        client1.connect("localhost", getListenerPort());
        client2.connect("localhost", getListenerPort());
        client3.connect("localhost", getListenerPort());
        client4.connect("localhost", getListenerPort());

        assertTrue(client1.login(TESTUSER1_USERNAME, TESTUSER_PASSWORD));
        assertTrue(client2.login(TESTUSER1_USERNAME, TESTUSER_PASSWORD));
        assertTrue(client3.login(TESTUSER1_USERNAME, TESTUSER_PASSWORD));

        try {
            assertTrue(client4.login(TESTUSER1_USERNAME, TESTUSER_PASSWORD));
            assertEquals(421, client.getReplyCode());
            fail("Must throw FTPConnectionClosedException");
        } catch (FTPConnectionClosedException e) {
            // expected
        }
    } finally {
        closeQuitely(client1);
        closeQuitely(client2);
        closeQuitely(client3);
        closeQuitely(client4);
    }
}

From source file:org.apache.ftpserver.clienttests.SiteTest.java

public void testSiteStat() throws Exception {
    // reboot server to clear stats
    server.stop();/*from   w  w w  .  jav  a 2s  .c  om*/
    initServer();

    // let's generate some stats
    FTPClient client1 = new FTPClient();
    client1.connect("localhost", getListenerPort());

    assertTrue(client1.login(ADMIN_USERNAME, ADMIN_PASSWORD));
    assertTrue(client1.makeDirectory("foo"));
    assertTrue(client1.makeDirectory("foo2"));
    assertTrue(client1.removeDirectory("foo2"));
    assertTrue(client1.storeFile(TEST_FILENAME, new ByteArrayInputStream(TESTDATA)));
    assertTrue(client1.storeFile(TEST_FILENAME, new ByteArrayInputStream(TESTDATA)));
    assertTrue(client1.retrieveFile(TEST_FILENAME, new ByteArrayOutputStream()));
    assertTrue(client1.deleteFile(TEST_FILENAME));

    assertTrue(client1.logout());
    client1.disconnect();

    FTPClient client2 = new FTPClient();
    client2.connect("localhost", getListenerPort());

    assertTrue(client2.login(ANONYMOUS_USERNAME, ANONYMOUS_PASSWORD));
    // done setting up stats

    client.connect("localhost", getListenerPort());
    client.login(ADMIN_USERNAME, ADMIN_PASSWORD);

    client.sendCommand("SITE STAT");
    String[] siteReplies = client.getReplyString().split("\r\n");

    assertEquals("200-", siteReplies[0]);

    String pattern = "Start Time               : " + TIMESTAMP_PATTERN;
    assertTrue(Pattern.matches(pattern, siteReplies[1]));

    assertTrue(Pattern.matches("File Upload Number       : 2", siteReplies[2]));
    assertTrue(Pattern.matches("File Download Number     : 1", siteReplies[3]));
    assertTrue(Pattern.matches("File Delete Number       : 1", siteReplies[4]));
    assertTrue(Pattern.matches("File Upload Bytes        : 16", siteReplies[5]));
    assertTrue(Pattern.matches("File Download Bytes      : 8", siteReplies[6]));
    assertTrue(Pattern.matches("Directory Create Number  : 2", siteReplies[7]));
    assertTrue(Pattern.matches("Directory Remove Number  : 1", siteReplies[8]));
    assertTrue(Pattern.matches("Current Logins           : 2", siteReplies[9]));
    assertTrue(Pattern.matches("Total Logins             : 3", siteReplies[10]));
    assertTrue(Pattern.matches("Current Anonymous Logins : 1", siteReplies[11]));
    assertTrue(Pattern.matches("Total Anonymous Logins   : 1", siteReplies[12]));
    assertTrue(Pattern.matches("Current Connections      : 2", siteReplies[13]));
    assertTrue(Pattern.matches("200 Total Connections        : 3", siteReplies[14]));
}

From source file:org.apache.hadoop.fs.ftp.FTPFileSystem.java

/**
 * Connect to the FTP server using configuration parameters *
 * //from ww  w  . ja  v a  2  s  .co m
 * @return An FTPClient instance
 * @throws IOException
 */
private FTPClient connect() throws IOException {
    FTPClient client = null;
    Configuration conf = getConf();
    String host = conf.get("fs.ftp.host");
    int port = conf.getInt("fs.ftp.host.port", FTP.DEFAULT_PORT);
    String user = conf.get("fs.ftp.user." + host);
    String password = conf.get("fs.ftp.password." + host);
    client = new FTPClient();
    client.connect(host, port);
    int reply = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        throw new IOException("Server - " + host + " refused connection on port - " + port);
    } else if (client.login(user, password)) {
        client.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
        client.setFileType(FTP.BINARY_FILE_TYPE);
        client.setBufferSize(DEFAULT_BUFFER_SIZE);
    } else {
        throw new IOException("Login failed on server - " + host + ", port - " + port);
    }

    return client;
}

From source file:org.apache.jmeter.protocol.ftp.sampler.FTPSampler.java

@Override
public SampleResult sample(Entry e) {
    SampleResult res = new SampleResult();
    res.setSuccessful(false); // Assume failure
    String remote = getRemoteFilename();
    String local = getLocalFilename();
    boolean binaryTransfer = isBinaryMode();
    res.setSampleLabel(getName());//w ww .j a v  a2 s .  c  om
    final String label = getLabel();
    res.setSamplerData(label);
    try {
        res.setURL(new URL(label));
    } catch (MalformedURLException e1) {
        log.warn("Cannot set URL: " + e1.getLocalizedMessage());
    }
    InputStream input = null;
    OutputStream output = null;

    res.sampleStart();
    FTPClient ftp = new FTPClient();
    try {
        savedClient = ftp;
        final int port = getPortAsInt();
        if (port > 0) {
            ftp.connect(getServer(), port);
        } else {
            ftp.connect(getServer());
        }
        res.latencyEnd();
        int reply = ftp.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            if (ftp.login(getUsername(), getPassword())) {
                if (binaryTransfer) {
                    ftp.setFileType(FTP.BINARY_FILE_TYPE);
                }
                ftp.enterLocalPassiveMode();// should probably come from the setup dialog
                boolean ftpOK = false;
                if (isUpload()) {
                    String contents = getLocalFileContents();
                    if (contents.length() > 0) {
                        byte[] bytes = contents.getBytes(); // TODO - charset?
                        input = new ByteArrayInputStream(bytes);
                        res.setBytes(bytes.length);
                    } else {
                        File infile = new File(local);
                        res.setBytes((int) infile.length());
                        input = new BufferedInputStream(new FileInputStream(infile));
                    }
                    ftpOK = ftp.storeFile(remote, input);
                } else {
                    final boolean saveResponse = isSaveResponse();
                    ByteArrayOutputStream baos = null; // No need to close this
                    OutputStream target = null; // No need to close this
                    if (saveResponse) {
                        baos = new ByteArrayOutputStream();
                        target = baos;
                    }
                    if (local.length() > 0) {
                        output = new FileOutputStream(local);
                        if (target == null) {
                            target = output;
                        } else {
                            target = new TeeOutputStream(output, baos);
                        }
                    }
                    if (target == null) {
                        target = new NullOutputStream();
                    }
                    input = ftp.retrieveFileStream(remote);
                    if (input == null) {// Could not access file or other error
                        res.setResponseCode(Integer.toString(ftp.getReplyCode()));
                        res.setResponseMessage(ftp.getReplyString());
                    } else {
                        long bytes = IOUtils.copy(input, target);
                        ftpOK = bytes > 0;
                        if (saveResponse && baos != null) {
                            res.setResponseData(baos.toByteArray());
                            if (!binaryTransfer) {
                                res.setDataType(SampleResult.TEXT);
                            }
                        } else {
                            res.setBytes((int) bytes);
                        }
                    }
                }

                if (ftpOK) {
                    res.setResponseCodeOK();
                    res.setResponseMessageOK();
                    res.setSuccessful(true);
                } else {
                    res.setResponseCode(Integer.toString(ftp.getReplyCode()));
                    res.setResponseMessage(ftp.getReplyString());
                }
            } else {
                res.setResponseCode(Integer.toString(ftp.getReplyCode()));
                res.setResponseMessage(ftp.getReplyString());
            }
        } else {
            res.setResponseCode("501"); // TODO
            res.setResponseMessage("Could not connect");
            //res.setResponseCode(Integer.toString(ftp.getReplyCode()));
            res.setResponseMessage(ftp.getReplyString());
        }
    } catch (IOException ex) {
        res.setResponseCode("000"); // TODO
        res.setResponseMessage(ex.toString());
    } finally {
        savedClient = null;
        if (ftp.isConnected()) {
            try {
                ftp.logout();
            } catch (IOException ignored) {
            }
            try {
                ftp.disconnect();
            } catch (IOException ignored) {
            }
        }
        IOUtils.closeQuietly(input);
        IOUtils.closeQuietly(output);
    }

    res.sampleEnd();
    return res;
}

From source file:org.apache.nifi.processors.standard.util.FTPTransfer.java

private FTPClient getClient(final FlowFile flowFile) throws IOException {
    if (client != null) {
        String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
        if (remoteHostName.equals(desthost)) {
            // destination matches so we can keep our current session
            resetWorkingDirectory();/*from  www .ja  va  2s .c o m*/
            return client;
        } else {
            // this flowFile is going to a different destination, reset session
            close();
        }
    }

    final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue());
    final String proxyHost = ctx.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger();
    FTPClient client;
    if (proxyType == Proxy.Type.HTTP) {
        client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(),
                ctx.getProperty(HTTP_PROXY_PASSWORD).getValue());
    } else {
        client = new FTPClient();
        if (proxyType == Proxy.Type.SOCKS) {
            client.setSocketFactory(new SocksProxySocketFactory(
                    new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort))));
        }
    }
    this.client = client;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setDefaultTimeout(
            ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setRemoteVerificationEnabled(false);

    final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
    this.remoteHostName = remoteHostname;
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }

    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(remoteHostname);
    }

    client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger());
    this.closed = false;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());

    final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
    final boolean loggedIn = client.login(username, password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + username + "'");
    }

    final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue();
    if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) {
        client.enterLocalActiveMode();
    } else {
        client.enterLocalPassiveMode();
    }

    final String transferMode = ctx.getProperty(TRANSFER_MODE).getValue();
    final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE
            : FTPClient.BINARY_FILE_TYPE;
    if (!client.setFileType(fileType)) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    this.homeDirectory = client.printWorkingDirectory();
    return client;
}

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

public static FTPClient getFTPConnection(TransferableContext context, LinkConfiguration linkConfiguration)
        throws IOException {
    FTPClient ftp = null;
    try {// ww  w.j a  va  2  s  .c  o m
        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;
    try {/* w w  w. j  a  v  a 2  s .  c  om*/
        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

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

        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
            }
        }
    }
}

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

public void doFTP() throws BuildException {
    FTPClient ftp = null;

    try {//w  w w .  ja  v a2  s  .c o m
        task.log("Opening FTP connection to " + task.getServer(), Project.MSG_VERBOSE);

        ftp = new FTPClient();
        if (task.isConfigurationSet()) {
            ftp = FTPConfigurator.configure(ftp, task);
        }

        ftp.setRemoteVerificationEnabled(task.getEnableRemoteVerification());
        ftp.connect(task.getServer(), task.getPort());
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            throw new BuildException("FTP connection failed: " + ftp.getReplyString());
        }

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

        if ((task.getAccount() != null && !ftp.login(task.getUserid(), task.getPassword(), task.getAccount()))
                || (task.getAccount() == null && !ftp.login(task.getUserid(), task.getPassword()))) {
            throw new BuildException("Could not login to FTP server");
        }

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

        if (task.isBinary()) {
            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 (task.isPassive()) {
            task.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 (task.getInitialSiteCommand() != null) {
            RetryHandler h = new RetryHandler(task.getRetriesAllowed(), task);
            final FTPClient lftp = ftp;
            executeRetryable(h, new Retryable() {
                public void execute() throws IOException {
                    doSiteCommand(lftp, task.getInitialSiteCommand());
                }
            }, "initial site command: " + task.getInitialSiteCommand());
        }

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

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

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

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

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

From source file:org.apache.tools.ant.taskdefs.optional.net2.FTP2.java

/**
 * Runs the task.//from   ww w. j ava 2 s.  c  o  m
 *
 * @throws BuildException if the task fails or is not configured
 *         correctly.
 */
@Override
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);

        if (this.proxyServer != null) {

            // Connect through an FTP proxy.

            // Get FTP proxy credentials (optional).
            String proxyUserId;
            char[] proxyPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.proxyServer, this.proxyPort,
                        this.proxyUserid, this.proxyPassword, RequestorType.PROXY);
                if (pa == null) {
                    proxyUserId = null;
                    proxyPassword = null;
                } else {
                    proxyUserId = pa.getUserName();
                    if (proxyUserId == null)
                        throw new BuildException("Proxy user ID missing");
                    proxyPassword = pa.getPassword();
                    if (proxyPassword == null)
                        throw new BuildException("Proxy password missing");
                }
            }

            // Get remote FTP server credentials (mandatory).
            String serverUserId;
            char[] serverPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.server, this.port, this.userid,
                        this.password, RequestorType.SERVER);
                if (pa == null)
                    throw new BuildException("User ID and password missing");
                serverUserId = pa.getUserName();
                if (serverUserId == null)
                    throw new BuildException("User ID missing");
                serverPassword = pa.getPassword();
                if (serverPassword == null)
                    throw new BuildException("Password missing");
            }

            // Connect to the FTP proxy.
            this.log("Opening FTP connection to proxy server \"" + this.proxyServer + "\" on port "
                    + this.proxyPort, Project.MSG_VERBOSE);
            ftp.connect(this.proxyServer, this.proxyPort);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("FTP connection to proxy server failed: " + ftp.getReplyString());
            }
            this.log("connected to proxy server", Project.MSG_VERBOSE);

            // Authenticate with the FTP proxy (optional).
            if (proxyUserId != null) {
                this.log("logging in to FTP proxy server", Project.MSG_VERBOSE);
                if (!ftp.login(proxyUserId, new String(proxyPassword))) {
                    throw new BuildException("Could not login to FTP proxy server");
                }
            }

            // Log in to the remote FTP server.
            this.log("logging in to FTP server", Project.MSG_VERBOSE);
            String userid2 = serverUserId + '@' + this.server;
            if (this.port != FTP2.DEFAULT_FTP_PORT)
                userid2 += ":" + this.port;
            if (this.account == null ? !ftp.login(userid2, new String(serverPassword))
                    : !ftp.login(userid2, new String(serverPassword), this.account))
                throw new BuildException("Could not login to FTP server");
            this.log("login succeeded", Project.MSG_VERBOSE);
        } else {

            // Direct connection to remote FTP server.

            // Get remote FTP server credentials (mandatory).
            String serverUserId;
            char[] serverPassword;
            {
                PasswordAuthentication pa = FTP2.getPasswordAuthentication(this.server, this.port, this.userid,
                        this.password, RequestorType.SERVER);
                if (pa == null)
                    throw new BuildException("User ID and password missing");
                serverUserId = pa.getUserName();
                if (serverUserId == null)
                    throw new BuildException("User ID missing");
                serverPassword = pa.getPassword();
                if (serverPassword == null)
                    throw new BuildException("Password missing");
            }

            // Connect to the remote FTP server.
            this.log("Opening FTP connection to " + this.server, Project.MSG_VERBOSE);
            ftp.connect(this.server, this.port);
            if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                throw new BuildException("FTP connection failed: " + ftp.getReplyString());
            }
            this.log("connected", Project.MSG_VERBOSE);

            // Log in to the remote FTP server.
            this.log("logging in to FTP server", Project.MSG_VERBOSE);
            if (this.account == null ? !ftp.login(serverUserId, new String(serverPassword))
                    : !ftp.login(serverUserId, new String(serverPassword), this.account))
                throw new BuildException("Could not login to FTP server");
            this.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() {
                @Override
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP2.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() {
                @Override
                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() {
                @Override
                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() {
                @Override
                public void execute() throws IOException {
                    doSiteCommand(lftp, FTP2.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
            }
        }
    }
}