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:main.TestManager.java

/**
 * Deletes all files on the server and uploads all the
 * tests from the local directory.//from ww  w. j a  v a 2  s  . c  om
 */
public static void syncServerWithTest() {
    FTPClient ftp = new FTPClient();
    boolean error = false;
    try {
        int reply;
        String server = "zajicek.endora.cz";
        ftp.connect(server, 21);

        // After connection attempt, we check the reply code to verify
        // success.
        reply = ftp.getReplyCode();

        //Not connected successfully - inform the user
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            Debugger.println("FTP server refused connection.");
            ErrorInformer.failedSyncing();
            return;
        }
        // LOGIN
        boolean success = ftp.login("plakato", "L13nK4");
        Debugger.println("Login successful: " + success);
        if (success == false) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        ftp.enterLocalPassiveMode();
        // Get all files from the server
        FTPFile[] files = ftp.listFiles();
        System.out.println("Got files! Count: " + files.length);
        // Delete all current tests on the server to be replaced with 
        // actualized version from local directory
        for (FTPFile f : files) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            if (f.isFile()) {
                ftp.deleteFile(f.getName());
            }
        }
        // Copy the files from local folder to server
        File localFolder = new File("src/tests/");
        File[] localFiles = localFolder.listFiles();
        int failed = 0;
        for (File f : localFiles) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            if (f.isFile()) {
                Debugger.println(f.getName());
                File file = new File("src/tests/" + f.getName());
                InputStream input = new FileInputStream(file);
                if (!ftp.storeFile(f.getName(), input))
                    failed++;
                input.close();
            }
        }
        // If we failed to upload some file, inform the user
        if (failed != 0) {
            ftp.disconnect();
            ErrorInformer.failedSyncing();
            return;
        }
        // Disconnect ftp client or resolve the potential error
        ftp.logout();
    } catch (IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
        if (error) {
            ErrorInformer.failedSyncing();
            return;
        }
    }
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle("Upload hotov");
    alert.setHeaderText(null);
    alert.setContentText("spene sa podarilo skoprova vetky testy na server!");

    alert.showAndWait();
    alert.close();
}

From source file:ftp.FTPtask.java

/**
 * Download File from FTP//from www . j  a va  2s. c o m
  * @param FTPADDR, ?  ?
  * @param user,   
  * @param password,   
 * @param FullPathToPutFile -       ,    ??
 * @param FilenameOnFTP - ?    (?     /upload/)
 */

public static void DownloadFileFromFTP(String FTPADDR, String user, String password, String FullPathToPutFile,
        String FilenameOnFTP) {

    FTPClient client = new FTPClient();
    FileOutputStream fos = null;

    try {
        client.connect(FTPADDR);
        client.login(user, password);

        //       The remote filename to be downloaded.

        String filename = FullPathToPutFile;
        fos = new FileOutputStream(filename);

        //       Download file from FTP server

        client.retrieveFile("/upload/" + FilenameOnFTP, fos);
        //

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fos != null) {
                fos.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

From source file:com.intellij.diagnostic.SubmitPerformanceReportAction.java

@Nullable
private static String uploadFileToFTP(final File reportPath, @NonNls final String ftpSite,
        @NonNls final String directory, final ProgressIndicator indicator) {
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(30 * 1000);/*from   w  ww  .j a v a  2s. c o m*/
    try {
        indicator.setText("Connecting to server...");
        ftp.connect(ftpSite);
        indicator.setText("Connected to server");

        if (!ftp.login("anonymous", "anonymous@jetbrains.com")) {
            return "Failed to login";
        }
        indicator.setText("Logged in");

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return "FTP server refused connection: " + reply;
        }
        if (!ftp.changeWorkingDirectory(directory)) {
            return "Failed to change directory";
        }

        // else won't work behind FW
        ftp.enterLocalPassiveMode();

        if (!ftp.setFileType(FTPClient.BINARY_FILE_TYPE)) {
            return "Failed to switch to binary mode";
        }

        indicator.setText("Transferring (" + StringUtil.formatFileSize(reportPath.length()) + ")");
        FileInputStream readStream = new FileInputStream(reportPath);
        try {
            if (!ftp.storeFile(reportPath.getName(), readStream)) {
                return "Failed to upload file";
            }
        } catch (IOException e) {
            return "Error during transfer: " + e.getMessage();
        } finally {
            readStream.close();
        }
        ftp.logout();
        return null;
    } catch (IOException e) {
        return "Failed to upload: " + e.getMessage();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:deincraftlauncher.IO.download.FTPSync.java

public static String[] listFiles(String dir) {

    FTPClient client = new FTPClient();

    try {/*ww  w.  ja v  a 2  s .c om*/
        client.connect(ftpServer);
        client.login(ftpUsername, ftpPassword);
        client.changeWorkingDirectory(dir);

        // Obtain a list of filenames in the current working
        // directory. When no file found an empty array will 
        // be returned.
        String[] names = client.listNames();

        client.logout();

        return names;

    } catch (IOException e) {
        System.err.println("Error connecting to ftp (listfiles): " + e);
    } finally {

        try {
            client.disconnect();
        } catch (IOException e) {
            System.err.println("Error disconnecting to ftp (listfiles): " + e);
        }
    }

    return null;

}

From source file:com.clothcat.hpoolauto.HtmlUploader.java

/**
 * Upload the html via FTP/* w ww . j a v a  2 s. c  o m*/
 */
public static void uploadHtml() {
    FTPClient ftpc = new FTPClient();
    FTPClientConfig conf = new FTPClientConfig();
    ftpc.configure(conf);
    try {
        ftpc.connect(Constants.FTP_HOSTNAME);
        ftpc.login(Constants.FTP_USERNAME, Constants.FTP_PASSWORD);
        File dir = new File(Constants.HTML_FILEPATH);
        File[] files = dir.listFiles();
        ftpc.changeWorkingDirectory("/htdocs");
        for (File f : files) {
            HLogger.log(Level.FINEST, "Uploading file: " + f.getName());
            FileInputStream fis = new FileInputStream(f);
            ftpc.storeFile(f.getName(), fis);
        }
        ftpc.logout();
    } catch (IOException ioe) {
        ioe.printStackTrace();
    } finally {
        if (ftpc.isConnected()) {
            try {
                ftpc.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:com.igormaznitsa.zxpoly.utils.ROMLoader.java

static byte[] loadFTPArchive(final String host, final String path, final String name, final String password)
        throws IOException {
    final FTPClient client = new FTPClient();
    client.connect(host);//from   www  . ja va2  s.  co  m
    int replyCode = client.getReplyCode();

    if (FTPReply.isPositiveCompletion(replyCode)) {
        try {
            client.login(name == null ? "" : name, password == null ? "" : password);
            client.setFileType(FTP.BINARY_FILE_TYPE);
            client.enterLocalPassiveMode();

            final ByteArrayOutputStream out = new ByteArrayOutputStream(300000);
            if (client.retrieveFile(path, out)) {
                return out.toByteArray();
            } else {
                throw new IOException(
                        "Can't load file 'ftp://" + host + path + "\' status=" + client.getReplyCode());
            }
        } finally {
            client.disconnect();
        }
    } else {
        client.disconnect();
        throw new IOException("Can't connect to ftp '" + host + "'");
    }
}

From source file:com.axelor.apps.tool.net.MyFtp.java

public static void getDataFiles(String server, String username, String password, String folder,
        String destinationFolder, Calendar start, Calendar end) {

    try {//from  w  w w .  j  a  va2  s  .  co m

        // Connect and logon to FTP Server
        FTPClient ftp = new FTPClient();
        ftp.connect(server);
        ftp.login(username, password);

        // List the files in the directory
        ftp.changeWorkingDirectory(folder);
        FTPFile[] files = ftp.listFiles();

        for (int i = 0; i < files.length; i++) {

            Date fileDate = files[i].getTimestamp().getTime();
            if (fileDate.compareTo(start.getTime()) >= 0 && fileDate.compareTo(end.getTime()) <= 0) {

                // Download a file from the FTP Server
                File file = new File(destinationFolder + File.separator + files[i].getName());
                FileOutputStream fos = new FileOutputStream(file);
                ftp.retrieveFile(files[i].getName(), fos);
                fos.close();
                file.setLastModified(fileDate.getTime());
            }
        }

        // Logout from the FTP Server and disconnect
        ftp.logout();
        ftp.disconnect();

    } catch (Exception e) {

        LOG.error(e.getMessage());

    }
}

From source file:com.qasp.diego.arsp.Atualiza.java

public static boolean DownloadFTP() throws IOException {

    final String FTPURL = "37.187.45.24";
    final String USUARIO = "diego";
    final String SENHA = "Jogador5";
    final String ARQUIVO = "data.dat";
    FTPClient ftp = new FTPClient();

    try {//from   w ww .  j  a  v  a 2s. c  o  m
        ftp.connect(FTPURL);
        ftp.login(USUARIO, SENHA);
        ftp.changeWorkingDirectory("/httpdocs/tcc/TCCpython");
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        OutputStream outputStream = null;
        boolean downloadcomsucesso = false;
        try {
            File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
                    ARQUIVO);
            f.createNewFile();
            outputStream = new BufferedOutputStream(new FileOutputStream(f));
            downloadcomsucesso = ftp.retrieveFile(ARQUIVO, outputStream);
        } finally {
            if (outputStream != null)
                outputStream.close();
        }
        return downloadcomsucesso;
    } finally {
        if (ftp != null) {
            ftp.logout();
            ftp.disconnect();
        }
    }
}

From source file:gui.TesteHackathon.java

public static void enviaImagem() {
    String server = "www.ejec.co";
    int port = 21;
    String user = "ejec";
    String pass = "cPanel2015";

    FTPClient ftpClient = new FTPClient();
    try {/*from  w ww .  ja  v  a2  s.c  o m*/

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

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        // APPROACH #1: uploads first file using an InputStream
        File firstLocalFile = new File("image.jpg");
        String firstRemoteFile = "public_html/virtualfit/image.jpg";
        InputStream inputStream = new FileInputStream(firstLocalFile);

        System.out.println("Start uploading first file");
        boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
        inputStream.close();
        if (done) {
            System.out.println("The first file is uploaded successfully.");
        }

    } 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();
        }
    }
}

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

public static FTPClient getFtpConnection(PublishingProfile pp) throws IOException {

    FTPClient ftp = new FTPClient();

    System.out.println("\t\t" + pp.ftpUrl());
    System.out.println("\t\t" + pp.ftpUsername());
    System.out.println("\t\t" + pp.ftpPassword());

    URI uri = URI.create("ftp://" + pp.ftpUrl());
    ftp.connect(uri.getHost(), 21);/*w  w  w.j av  a  2  s.com*/
    final int replyCode = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(replyCode)) {
        ftp.disconnect();
        throw new ConnectException("Unable to connect to FTP server");
    }

    if (!ftp.login(pp.ftpUsername(), pp.ftpPassword())) {
        throw new ConnectException("Unable to login to FTP server");
    }

    ftp.setControlKeepAliveTimeout(Constants.connection_read_timeout_ms);
    ftp.setFileType(FTP.BINARY_FILE_TYPE);
    ftp.enterLocalPassiveMode();//Switch to passive mode

    return ftp;
}