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

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

Introduction

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

Prototype

public boolean logout() throws IOException 

Source Link

Document

Logout of the FTP server by sending the QUIT command.

Usage

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 ww  .  j  a  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:it.zero11.acme.example.FTPChallengeListener.java

private void deleteChallengeFiles() {
    FTPClient ftp = new FTPClient();
    try {//w  w  w  .j  a va 2  s . c om
        ftp.connect(host);
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.disconnect();
            return;
        }

        ftp.login(username, password);
        ftp.changeWorkingDirectory(webroot);
        ftp.changeWorkingDirectory(".well-known");
        ftp.changeWorkingDirectory("acme-challenge");

        FTPFile[] subFiles = ftp.listFiles();

        if (subFiles != null && subFiles.length > 0) {
            for (FTPFile aFile : subFiles) {
                String currentFileName = aFile.getName();
                if (currentFileName.equals(".") || currentFileName.equals("..")) {
                    continue;
                } else {
                    ftp.deleteFile(currentFileName);
                }
            }
        }
        ftp.changeToParentDirectory();
        ftp.removeDirectory("acme-challenge");
        ftp.changeToParentDirectory();
        ftp.removeDirectory(".well-known");
        ftp.logout();
    } catch (IOException e) {
        throw new AcmeException(e);
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
}

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

/**
 * logout & disconnect FTP client.//from w  ww  . j  a v  a 2 s . c  o m
 *
 * @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 {/*w w  w.  java  2s  . 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:facturacion.ftp.FtpServer.java

public static InputStream getTokenInputStream(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    try {//from w w w.j  a v  a2 s .c o  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:com.savy3.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;
    try {/*from w ww.j  av  a 2s.  co  m*/
        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()));
        System.out.println("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 Binary transfer mode
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.featureValue("LITERAL SITE RDW");
        ftp.doCommand("SITE", "RDW");
        System.out.println("reply for LITERAL" + ftp.getReplyString());
        // 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: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  a va2s  . 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:ca.rmen.android.networkmonitor.app.speedtest.SpeedTestUpload.java

public static SpeedTestResult upload(SpeedTestUploadConfig uploadConfig) {
    Log.v(TAG, "upload " + uploadConfig);
    // Make sure we have a file to upload
    if (!uploadConfig.file.exists())
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);

    FTPClient ftp = new FTPClient();
    // For debugging, we'll log all the ftp commands
    if (BuildConfig.DEBUG) {
        PrintCommandListener printCommandListener = new PrintCommandListener(System.out);
        ftp.addProtocolCommandListener(printCommandListener);
    }// w  ww . ja va2 s. c  o m
    InputStream is = null;
    try {
        // Set buffer size of FTP client
        ftp.setBufferSize(1048576);
        // Open a connection to the FTP server
        ftp.connect(uploadConfig.server, uploadConfig.port);
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }
        // Login to the FTP server
        if (!ftp.login(uploadConfig.user, uploadConfig.password)) {
            ftp.disconnect();
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.AUTH_FAILURE);
        }
        // Try to change directories
        if (!TextUtils.isEmpty(uploadConfig.path) && !ftp.changeWorkingDirectory(uploadConfig.path)) {
            Log.v(TAG, "Upload: could not change path to " + uploadConfig.path);
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.INVALID_FILE);
        }

        // set the file type to be read as a binary file
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        // Upload the file
        is = new FileInputStream(uploadConfig.file);
        long before = System.currentTimeMillis();
        long txBytesBefore = TrafficStats.getTotalTxBytes();
        if (!ftp.storeFile(uploadConfig.file.getName(), is)) {
            ftp.disconnect();
            Log.v(TAG, "Upload: could not store file to " + uploadConfig.path + ". Error code: "
                    + ftp.getReplyCode() + ", error string: " + ftp.getReplyString());
            return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
        }

        // Calculate stats
        long after = System.currentTimeMillis();
        long txBytesAfter = TrafficStats.getTotalTxBytes();
        ftp.logout();
        ftp.disconnect();
        Log.v(TAG, "Upload complete");
        return new SpeedTestResult(txBytesAfter - txBytesBefore, uploadConfig.file.length(), after - before,
                SpeedTestStatus.SUCCESS);
    } catch (SocketException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } catch (IOException e) {
        Log.e(TAG, "upload " + e.getMessage(), e);
        return new SpeedTestResult(0, 0, 0, SpeedTestStatus.FAILURE);
    } finally {
        IoUtil.closeSilently(is);
    }
}

From source file:FTP.Uploader.java

public void uploadFile(String filename) throws IOException {
    FTPClient ftpclient = new FTPClient();
    FileInputStream fis = null;//from   w w  w  .  ja v  a  2 s  .c o m
    boolean result;
    String ftpServerAddress = "shamalmahesh.net78.net";
    String userName = "a9959679";
    String password = "9P3IckDo";

    try {
        ftpclient.connect(ftpServerAddress);
        result = ftpclient.login(userName, password);

        if (result == true) {
            System.out.println("Logged in Successfully !");
        } else {
            System.out.println("Login Fail!");
            return;
        }
        ftpclient.enterLocalPassiveMode();
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

        ftpclient.changeWorkingDirectory("/public_html/testing");

        //            File file = new File("D:/jpg/wq.jpg");
        File file = new File(filename);
        String testName = file.getName();
        fis = new FileInputStream(file);
        System.out.println(ftpclient.getBufferSize());
        // Upload file to the ftp server
        result = ftpclient.storeFile(testName, fis);
        if (result == true) {
            System.out.println("File is uploaded successfully");
        } else {
            System.out.println("File uploading failed");
        }
        ftpclient.logout();
    } catch (FTPConnectionClosedException e) {
        e.printStackTrace();
    } finally {
        try {
            ftpclient.disconnect();
        } catch (FTPConnectionClosedException e) {
            System.out.println(e);
        }
    }
}

From source file:boosta.artem.services.FTPResultReader.java

public void readResult() {
    String server = "62.210.82.210";
    int port = 55021;
    String user = "misha_p";
    String pass = "GfhjkM1983";

    FTPClient ftpClient = new FTPClient();
    try {/*from  w  w w . j  a va2  s  . c  om*/

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

        // APPROACH #1: using retrieveFile(String, OutputStream)
        String remoteFile = Main.remote_out_path;
        System.out.println(remoteFile);
        //String remoteFile = "/results/ttgenerate.txt";
        String downlFile = Main.file_name;
        System.out.println(downlFile);
        File downloadFile = new File(downlFile);
        OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(downloadFile));

        boolean success = ftpClient.retrieveFile(remoteFile, outputStream);

        outputStream.close();

        if (success) {
            System.out.println(" ?   FTP!!!");
        } else {
            System.out.println("  ?   TFP!!!");
        }

    } catch (IOException ex) {
        System.out.println("   ? FTP  !!!");
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            System.out.println(" ? ?? ? FTP!!!");
        }
    }
}