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

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

Introduction

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

Prototype

@Override
public void disconnect() throws IOException 

Source Link

Document

Closes the connection to the FTP server and restores connection parameters to the default values.

Usage

From source file:com.zxy.commons.net.ftp.FtpUtils.java

/**
 * FTP handle/*  ww  w  .j  a v a  2  s .  co  m*/
 * 
 * @param <T> return object type
 * @param ftpConfig ftp config
 * @param callback ftp callback
 * @return value
*/
public static <T> T ftpHandle(FtpConfig ftpConfig, FtpCallback<T> callback) {
    FTPClient client = null;
    if (ftpConfig.isFtps() && ftpConfig.getSslContext() != null) {
        client = new FTPSClient(ftpConfig.getSslContext());
    } else if (ftpConfig.isFtps()) {
        client = new FTPSClient();
    } else {
        client = new FTPClient();
    }

    client.configure(ftpConfig.getFtpClientConfig());
    try {
        //            client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        client.connect(ftpConfig.getHost(), ftpConfig.getPort());
        client.setConnectTimeout(ftpConfig.getConnectTimeoutMs());
        client.setControlKeepAliveTimeout(ftpConfig.getKeepAliveTimeoutSeconds());
        if (!Strings.isNullOrEmpty(ftpConfig.getUsername())) {
            client.login(ftpConfig.getUsername(), ftpConfig.getPassword());
        }
        LOGGER.trace("Connected to {}, reply: {}", ftpConfig.getHost(), client.getReplyString());

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
            throw new NetException("FTP server refused connection.");
        }
        return callback.process(client);
    } catch (Exception e) {
        throw new NetException(e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
            } catch (IOException ioe) {
                LOGGER.warn(ioe.getMessage());
            }
            try {
                client.disconnect();
            } catch (IOException ioe) {
                LOGGER.warn(ioe.getMessage());
            }
        }
    }
}

From source file:com.microsoft.azuretools.utils.WebAppUtils.java

public static void uploadWebConfig(WebApp webApp, InputStream fileStream, IProgressIndicator indicator)
        throws IOException {
    FTPClient ftp = null;
    try {//from w w w. j  a  va 2  s.  c  o  m
        PublishingProfile pp = webApp.getPublishingProfile();
        ftp = getFtpConnection(pp);

        if (indicator != null)
            indicator.setText("Stopping the service...");
        webApp.stop();

        if (indicator != null)
            indicator.setText("Uploading " + webConfigFilename + "...");
        ftp.storeFile(ftpRootPath + webConfigFilename, fileStream);

        if (indicator != null)
            indicator.setText("Starting the service...");
        webApp.start();
    } finally {
        if (ftp != null && ftp.isConnected()) {
            ftp.disconnect();
        }
    }
}

From source file:net.paissad.jcamstream.utils.FTPUtils.java

/**
 * Logout and then disconnect from the FTP server.
 * //from  ww w  .j  a  v a  2 s  .c o m
 * @throws IOException
 * 
 * @see org.apache.commons.net.ftp.FTPClient#logout()
 * @see org.apache.commons.net.ftp.FTPClient#disconnect()
 */
public void logoutAndDisconnect() throws IOException {
    FTPClient client = this.getFtpClient();

    if (client.isConnected() && !FTPReply.isPositiveIntermediate(client.getReplyCode())) {
        client.logout();
        client.disconnect();
        System.out.println("Disconnected successfully from FTP server.");
    }

    if (client.isConnected() && !client.completePendingCommand()) {
        System.err.println("Something failed !");
    }
}

From source file:com.globalsight.smartbox.util.FtpHelper.java

public synchronized boolean closeFtpClient(FTPClient ftpClient) {
    if (ftpClient == null)
        return true;

    try {/*from  w w  w . java 2 s . c  o  m*/
        ftpClient.disconnect();
        if (busyFtpClientNumber > 0)
            busyFtpClientNumber--;
    } catch (Exception e) {
        String message = "Ftp close exception";
        LogUtil.fail(message, e);
        return false;
    }
    return true;
}

From source file:edu.mda.bioinfo.ids.DownloadFiles.java

private void downloadFromFtpToFile(String theServer, String theServerFile, String theLocalFile)
        throws IOException, Exception {
    FTPClient ftp = new FTPClient();
    try {/*from w  w  w  .j  ava  2s .  c o  m*/
        int reply = 0;
        boolean replyB = false;
        ftp.connect(theServer);
        System.out.print(ftp.getReplyString());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
        } else {
            ftp.login("anonymous", "anonymous");
            replyB = ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.print(ftp.getReplyString());
            System.out.println("replyB= " + replyB);
            if (false == replyB) {
                throw new Exception("Unable to login to " + theServer);
            }
            OutputStream output = new FileOutputStream(theLocalFile);
            replyB = ftp.retrieveFile(theServerFile, output);
            System.out.print(ftp.getReplyString());
            System.out.println("replyB= " + replyB);
            if (false == replyB) {
                throw new Exception("Unable to retrieve " + theServerFile);
            }
        }
        ftp.logout();
    } catch (IOException rethrownExp) {
        System.err.println("exception " + rethrownExp.getMessage());
        throw rethrownExp;
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ignore) {
                // do nothing
            }
        }
    }
}

From source file:com.claim.support.FtpUtil.java

public void uploadMutiFileWithFTP(String targetDirectory, FileTransferController fileTransferController) {
    try {/*from  ww w  .java 2s. com*/
        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        FTPClient ftp = new FTPClient();
        ftp.connect(properties.getFtp_server());
        if (!ftp.login(properties.getFtp_username(), properties.getFtp_password())) {
            ftp.logout();
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        ftp.enterLocalPassiveMode();
        System.out.println("Remote system is " + ftp.getSystemName());
        ftp.changeWorkingDirectory(targetDirectory);
        System.out.println("Current directory is " + ftp.printWorkingDirectory());
        FTPFile[] ftpFiles = ftp.listFiles();
        if (ftpFiles != null && ftpFiles.length > 0) {
            for (FTPFile file : ftpFiles) {
                if (!file.isFile()) {
                    continue;
                }
                System.out.println("File is " + file.getName());
                OutputStream output;
                output = new FileOutputStream(
                        properties.getFtp_remote_directory() + File.separator + file.getName());
                ftp.retrieveFile(file.getName(), output);
                output.close();
            }
        }
        ftp.logout();
        ftp.disconnect();
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:com.clican.pluto.cms.core.service.impl.SiteServiceImpl.java

public FTPClient getFTPClient(ISite site) throws IOException {
    String url = site.getUrl();/*from w w  w. j  av a 2  s .  c o m*/
    if (url == null) {
        return null;
    }
    if (url.startsWith("ftp://")) {
        int port = 21;
        String hostname = null;
        try {
            url = url.substring(6);
            if (url.indexOf(":") != -1) {
                hostname = url.substring(0, url.indexOf(":"));
                if (url.endsWith("/")) {
                    port = Integer.parseInt(url.substring(url.indexOf(":") + 1, url.length() - 1));
                } else {
                    port = Integer.parseInt(url.substring(url.indexOf(":") + 1));
                }
            } else {
                if (url.endsWith("/")) {
                    hostname = url.substring(0, url.length() - 1);
                } else {
                    hostname = url;
                }
            }
        } catch (Exception e) {
            throw new UnknownHostException(url);
        }
        FTPClient client = new FTPClient();
        client.connect(hostname, port);
        if (log.isDebugEnabled()) {
            log.debug("Connected to " + url + ".");
            log.debug(client.getReplyString());
        }
        int reply = client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
            log.warn("FTP server " + url + " refused connection.");
            return null;
        }
        if (StringUtils.isNotEmpty(site.getUsername())) {
            boolean login = client.login(site.getUsername(), site.getPassword());
            if (!login) {
                client.disconnect();
                return null;
            }
        }

        return client;
    }
    return null;
}

From source file:com.bbytes.jfilesync.sync.ftp.FTPClientFactory.java

/**
 * Get {@link FTPClient} with initialized connects to server given in properties file
 * @return/*from  w  w w .  ja v a  2 s.  c om*/
 */
public FTPClient getClientInstance() {

    ExecutorService ftpclientConnThreadPool = Executors.newSingleThreadExecutor();
    Future<FTPClient> future = ftpclientConnThreadPool.submit(new Callable<FTPClient>() {

        FTPClient ftpClient = new FTPClient();

        boolean connected;

        public FTPClient call() throws Exception {

            try {
                while (!connected) {
                    try {
                        ftpClient.connect(host, port);
                        if (!ftpClient.login(username, password)) {
                            ftpClient.logout();
                        }
                        connected = true;
                        return ftpClient;
                    } catch (Exception e) {
                        connected = false;
                    }

                }

                int reply = ftpClient.getReplyCode();
                // FTPReply stores a set of constants for FTP reply codes.
                if (!FTPReply.isPositiveCompletion(reply)) {
                    ftpClient.disconnect();
                }

                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
            return ftpClient;
        }
    });

    FTPClient ftpClient = new FTPClient();
    try {
        // wait for 100 secs for acquiring conn else terminate
        ftpClient = future.get(100, TimeUnit.SECONDS);
    } catch (TimeoutException e) {
        log.info("FTP client Conn wait thread terminated!");
    } catch (InterruptedException e) {
        log.error(e.getMessage(), e);
    } catch (ExecutionException e) {
        log.error(e.getMessage(), e);
    }

    ftpclientConnThreadPool.shutdownNow();
    return ftpClient;

}

From source file:com.eryansky.common.utils.ftp.FtpFactory.java

/**
 * ?FTP?.//  w  w w  . ja v a2 s  .  c  o m
 * 
 * @param path
 *            FTP??
 * @param filename
 *            FTP???
 * @param input
 *            ?
 * @return ?true?false
 */
public boolean ftpUploadFile(String path, String filename, InputStream input) {
    boolean success = false;
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("UTF-8");
    try {
        int reply;
        ftp.connect(url, port);
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(path);
        ftp.setBufferSize(1024);
        ftp.setFileType(FTPClient.ASCII_FILE_TYPE);
        // 
        ftp.storeFile(filename, input);
        input.close();
        ftp.logout();
        success = true;
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return success;
}

From source file:com.seajas.search.contender.service.modifier.AbstractModifierService.java

/**
 * Retrieve the FTP client belonging to the given URI.
 * /*from   www.  j a va  2s  . c  o  m*/
 * @param uri
 * @return FTPClient
 */
protected FTPClient retrieveFtpClient(final URI uri) {
    // Create the FTP client

    FTPClient ftpClient = uri.getScheme().equalsIgnoreCase("ftps") ? new FTPSClient() : new FTPClient();

    try {
        ftpClient.connect(uri.getHost(), uri.getPort() != -1 ? uri.getPort() : 21);

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not connect to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        if (StringUtils.hasText(uri.getUserInfo())) {
            if (uri.getUserInfo().contains(":"))
                ftpClient.login(uri.getUserInfo().substring(0, uri.getUserInfo().indexOf(":")),
                        uri.getUserInfo().substring(uri.getUserInfo().indexOf(":") + 1));
            else
                ftpClient.login(uri.getUserInfo(), "");
        }

        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            ftpClient.disconnect();

            logger.error("Could not login to the given FTP server " + uri.getHost()
                    + (uri.getPort() != -1 ? ":" + uri.getPort() : "") + " - " + ftpClient.getReplyString());

            return null;
        }

        // Switch to PASV and BINARY mode

        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        return ftpClient;
    } catch (IOException e) {
        logger.error("Could not close input stream during archive processing", e);
    }

    return null;
}