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:co.cask.hydrator.action.ftp.FTPCopyAction.java

@Override
public void run(ActionContext context) throws Exception {
    Path destination = new Path(config.getDestDirectory());
    FileSystem fileSystem = FileSystem.get(new Configuration());
    destination = fileSystem.makeQualified(destination);
    if (!fileSystem.exists(destination)) {
        fileSystem.mkdirs(destination);//from   w w w.  ja v a2  s .c  o m
    }

    FTPClient ftp;
    if ("ftp".equals(config.getProtocol().toLowerCase())) {
        ftp = new FTPClient();
    } else {
        ftp = new FTPSClient();
    }
    ftp.setControlKeepAliveTimeout(5);
    // UNIX type server
    FTPClientConfig ftpConfig = new FTPClientConfig();
    // Set additional parameters required for the ftp
    // for example config.setServerTimeZoneId("Pacific/Pitcairn")
    ftp.configure(ftpConfig);
    try {
        ftp.connect(config.getHost(), config.getPort());
        ftp.enterLocalPassiveMode();
        String replyString = ftp.getReplyString();
        LOG.info("Connected to server {} and port {} with reply from connect as {}.", config.getHost(),
                config.getPort(), replyString);

        // Check the reply code for actual success
        int replyCode = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftp.disconnect();
            throw new RuntimeException(String.format("FTP server refused connection with code %s and reply %s.",
                    replyCode, replyString));
        }

        if (!ftp.login(config.getUserName(), config.getPassword())) {
            LOG.error("login command reply code {}, {}", ftp.getReplyCode(), ftp.getReplyString());
            ftp.logout();
            throw new RuntimeException(String.format(
                    "Login to the FTP server %s and port %s failed. " + "Please check user name and password.",
                    config.getHost(), config.getPort()));
        }

        FTPFile[] ftpFiles = ftp.listFiles(config.getSrcDirectory());
        LOG.info("listFiles command reply code: {}, {}.", ftp.getReplyCode(), ftp.getReplyString());
        // Check the reply code for listFiles call.
        // If its "522 Data connections must be encrypted" then it means data channel also need to be encrypted
        if (ftp.getReplyCode() == 522 && "sftp".equalsIgnoreCase(config.getProtocol())) {
            // encrypt data channel and listFiles again
            ((FTPSClient) ftp).execPROT("P");
            LOG.info("Attempting command listFiles on encrypted data channel.");
            ftpFiles = ftp.listFiles(config.getSrcDirectory());
        }
        for (FTPFile file : ftpFiles) {
            String source = config.getSrcDirectory() + "/" + file.getName();

            LOG.info("Current file {}, source {}", file.getName(), source);
            if (config.getExtractZipFiles() && file.getName().endsWith(".zip")) {
                copyZip(ftp, source, fileSystem, destination);
            } else {
                Path destinationPath = fileSystem.makeQualified(new Path(destination, file.getName()));
                LOG.debug("Downloading {} to {}", file.getName(), destinationPath.toString());
                try (OutputStream output = fileSystem.create(destinationPath)) {
                    InputStream is = ftp.retrieveFileStream(source);
                    ByteStreams.copy(is, output);
                }
            }
            if (!ftp.completePendingCommand()) {
                LOG.error("Error completing command.");
            }
        }
        ftp.logout();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (Throwable e) {
                LOG.error("Failure to disconnect the ftp connection.", e);
            }
        }
    }
}

From source file:com.haha01haha01.harail.DatabaseDownloader.java

private Boolean downloadFile(String server, int portNumber, String user, String password, String filename,
        File localFile) throws IOException {
    FTPClient ftp = null;

    try {/*from  w w w. ja v  a  2 s .  c om*/
        ftp = new FTPClient();
        ftp.setBufferSize(1024 * 1024);
        ftp.connect(server, portNumber);
        Log.d(NAME, "Connected. Reply: " + ftp.getReplyString());
        if (!ftp.login(user, password)) {
            return false;
        }
        Log.d(NAME, "Logged in");
        if (!ftp.setFileType(FTP.BINARY_FILE_TYPE)) {
            return false;
        }
        Log.d(NAME, "Downloading");
        ftp.enterLocalPassiveMode();

        OutputStream outputStream = null;
        boolean success = false;
        try {
            outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
            success = ftp.retrieveFile(filename, outputStream);
        } finally {
            if (outputStream != null) {
                outputStream.close();
            }
        }

        return success;
    } finally {
        if (ftp != null) {
            ftp.logout();
            ftp.disconnect();
        }
    }
}

From source file:fr.bmartel.speedtest.SpeedTestTask.java

/**
 * logout & disconnect FTP client./*from  ww w  .j av  a2s.com*/
 *
 * @param ftpclient ftp client
 */
private void disconnectFtp(final FTPClient ftpclient) {

    try {
        if (ftpclient.isConnected()) {
            ftpclient.logout();
            ftpclient.disconnect();
        }
    } catch (IOException ex) {
        //ex.printStackTrace();
    }
}

From source file:conf.FTPConf.java

public String subirArchivo(File archivo) {

    FTPClient ftpClient = new FTPClient();
    try {/*from w w w .  j av a2  s  .  c o m*/

        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // APPROACH #2: uploads second file using an OutputStream
        String serverFile = dir + archivo.getName();
        InputStream inputStream = new FileInputStream(archivo);

        OutputStream outputStream = ftpClient.storeFileStream(serverFile);
        byte[] bytesIn = new byte[4096];
        int read = 0;

        while ((read = inputStream.read(bytesIn)) != -1) {
            outputStream.write(bytesIn, 0, read);
        }
        inputStream.close();
        outputStream.close();

        boolean completed = ftpClient.completePendingCommand();
        if (completed) {
            String link = "ftp://" + user + "@" + server + "/" + serverFile;
            return link;
        }

    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    return null;
}

From source file:edu.stanford.epad.common.util.FTPUtil.java

public void getFile(String remoteFile, File localFile) throws Exception {

    FTPClient ftpClient = new FTPClient();
    OutputStream outputStream = null;
    try {/*from  w ww .  j a  v  a2  s. co  m*/
        ftpClient.connect(ftpHost, ftpPort);
        ftpClient.enterLocalPassiveMode();
        if (ftpUser != null && ftpUser.length() > 0)
            ftpClient.login(ftpUser, ftpPassword);
        else
            ftpClient.login("anonymous", "");
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        outputStream = new BufferedOutputStream(new FileOutputStream(localFile));
        InputStream inputStream = ftpClient.retrieveFileStream(remoteFile);
        IOUtils.copy(inputStream, outputStream);
        outputStream.flush();
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(inputStream);
        boolean commandOK = ftpClient.completePendingCommand();
        //boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        //if (!success) {
        //   throw new Exception("Error retrieving remote file: " + remoteFile);
        //}   
    } finally {
        outputStream.close();
        ftpClient.disconnect();
    }
}

From source file:com.microsoft.intellij.forms.CreateWebSiteForm.java

private void copyWebConfigForCustom(WebSiteConfiguration config) throws AzureCmdException {
    if (config != null) {
        AzureManager manager = AzureManagerImpl.getManager(project);
        WebSitePublishSettings webSitePublishSettings = manager.getWebSitePublishSettings(
                config.getSubscriptionId(), config.getWebSpaceName(), config.getWebSiteName());
        // retrieve ftp publish profile
        WebSitePublishSettings.FTPPublishProfile ftpProfile = null;
        for (WebSitePublishSettings.PublishProfile pp : webSitePublishSettings.getPublishProfileList()) {
            if (pp instanceof WebSitePublishSettings.FTPPublishProfile) {
                ftpProfile = (WebSitePublishSettings.FTPPublishProfile) pp;
                break;
            }/*from www .  ja v  a 2  s  .  c  o m*/
        }

        if (ftpProfile != null) {
            FTPClient ftp = new FTPClient();
            try {
                URI uri = null;
                uri = new URI(ftpProfile.getPublishUrl());
                ftp.connect(uri.getHost());
                final int replyCode = ftp.getReplyCode();
                if (!FTPReply.isPositiveCompletion(replyCode)) {
                    ftp.disconnect();
                }
                if (!ftp.login(ftpProfile.getUserName(), ftpProfile.getPassword())) {
                    ftp.logout();
                }
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                if (ftpProfile.isFtpPassiveMode()) {
                    ftp.enterLocalPassiveMode();
                }
                ftp.deleteFile(ftpPath + message("configName"));
                String tmpPath = String.format("%s%s%s", System.getProperty("java.io.tmpdir"), File.separator,
                        message("configName"));
                File file = new File(tmpPath);
                if (file.exists()) {
                    file.delete();
                }

                WAEclipseHelperMethods.copyFile(WAHelper.getCustomJdkFile(message("configName")), tmpPath);
                String jdkFolderName = "";
                if (customJDKUser.isSelected()) {
                    String url = customUrl.getText();
                    jdkFolderName = url.substring(url.lastIndexOf("/") + 1, url.length());
                    jdkFolderName = jdkFolderName.substring(0, jdkFolderName.indexOf(".zip"));
                } else {
                    String cloudVal = WindowsAzureProjectManager
                            .getCloudValue((String) jdkNames.getSelectedItem(), AzurePlugin.cmpntFile);
                    jdkFolderName = cloudVal.substring(cloudVal.indexOf("\\") + 1, cloudVal.length());
                }
                String jdkPath = "%HOME%\\site\\wwwroot\\jdk\\" + jdkFolderName;
                String serverPath = "%programfiles(x86)%\\" + WAHelper
                        .generateServerFolderName(config.getJavaContainer(), config.getJavaContainerVersion());
                WebAppConfigOperations.prepareWebConfigForCustomJDKServer(tmpPath, jdkPath, serverPath);
                InputStream input = new FileInputStream(tmpPath);
                ftp.storeFile(ftpPath + message("configName"), input);
                cleanup(ftp);
                ftp.logout();
            } catch (Exception e) {
                AzurePlugin.log(e.getMessage(), e);
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
    }
}

From source file:facturacion.ftp.FtpServer.java

public static InputStream getTokenInputStream(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    try {//w w  w .j a va 2 s.  co  m
        //ftpClient.connect("127.0.0.1", 21 );
        //ftpClient.login("erpftp", "Tribut@2014");
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            //return -1;
        } else {
            System.out.println("se conecto al servidor");
        }
        //ftpClient.enterLocalPassiveMode();
        // crear directorio
        //OutputStream outputStream2 = new BufferedOutputStream(new FileOutputStream(file_ruta));
        //System.out.println("File #1 has been downloaded successfully. 1");
        //FileInputStream fis = new FileInputStream("C:\\Users\\aaguerra\\Desktop\\firmado2.p12");
        //InputStream is = fis;
        System.out.println("File rutaqq=" + "1-/" + remote_file_ruta);
        InputStream is = ftpClient.retrieveFileStream(remote_file_ruta);

        if (is == null)
            System.out.println("File #1 es null token");
        else
            System.out.println("File #1 no es null token");

        //return ftpClient.retrieveFileStream(remote_file_ruta);
        return is;
    } catch (IOException ex) {
        System.out.println("File #1 has been downloaded successfully. 222");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println("File #1 has been downloaded successfully. 3");
            return null;
            //ex.printStackTrace();
        }
    }
    return null;
}

From source file:ftp_server.FileUpload.java

public void uploading() {
    FTPClient client = new FTPClient();
    FileInputStream fis = null;// w w w. jav  a  2 s. c o m
    try {
        client.connect("shamalmahesh.net78.net");
        client.login("a9959679", "9P3IckDo");
        client.setFileType(FTP.BINARY_FILE_TYPE);
        int reply = client.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Uploading....");
        } else {
            System.out.println("Failed connect to the server!");
        }
        //            String filename = "DownloadedLook1.txt";
        String path = "D:\\jpg\\";
        //            String filename = "1.jpg";
        String filename = "appearance.jpg";
        System.out.println(path + filename);
        fis = new FileInputStream(path + filename);
        System.out.println(fis.toString());
        boolean status = client.storeFile("/public_html/testing/" + filename, fis);
        System.out.println("Status : " + status);
        System.out.println("Done!");
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    // PluginConfig pluginConfig = getPluginConfig();
    // if (pluginConfig != null) {
    Map<String, String> ftpInfo = getFtpInfo("all");
    String urlPrefix = DataConfig.getConfig("IMGFTPROOT");
    FTPClient ftpClient = new FTPClient();
    try {/*  w  w  w.j  av  a 2 s  .co  m*/
        ftpClient.connect(ftpInfo.get("host"), 21);
        ftpClient.login(ftpInfo.get("username"), ftpInfo.get("password"));
        ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode()) && ftpClient.changeWorkingDirectory(path)) {
            for (FTPFile ftpFile : ftpClient.listFiles()) {
                FileInfo fileInfo = new FileInfo();
                fileInfo.setName(ftpFile.getName());
                fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                fileInfo.setIsDirectory(ftpFile.isDirectory());
                fileInfo.setSize(ftpFile.getSize());
                fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                fileInfos.add(fileInfo);
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
            }
        }
    }
    // }
    return fileInfos;
}

From source file:com.dp2345.plugin.ftp.FtpPlugin.java

@Override
public List<FileInfo> browser(String path) {
    List<FileInfo> fileInfos = new ArrayList<FileInfo>();
    PluginConfig pluginConfig = getPluginConfig();
    if (pluginConfig != null) {
        String host = pluginConfig.getAttribute("host");
        Integer port = Integer.valueOf(pluginConfig.getAttribute("port"));
        String username = pluginConfig.getAttribute("username");
        String password = pluginConfig.getAttribute("password");
        String urlPrefix = pluginConfig.getAttribute("urlPrefix");
        FTPClient ftpClient = new FTPClient();
        try {// w ww  . ja va2 s  .  c o m
            ftpClient.connect(host, port);
            ftpClient.login(username, password);
            ftpClient.setFileTransferMode(FTP.STREAM_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())
                    && ftpClient.changeWorkingDirectory(path)) {
                for (FTPFile ftpFile : ftpClient.listFiles()) {
                    FileInfo fileInfo = new FileInfo();
                    fileInfo.setName(ftpFile.getName());
                    fileInfo.setUrl(urlPrefix + path + ftpFile.getName());
                    fileInfo.setIsDirectory(ftpFile.isDirectory());
                    fileInfo.setSize(ftpFile.getSize());
                    fileInfo.setLastModified(ftpFile.getTimestamp().getTime());
                    fileInfos.add(fileInfo);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
    return fileInfos;
}