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.discursive.jccook.net.FTPExample.java

private void secondExample() throws SocketException, IOException {
    FTPClient client = new FTPClient();
    client.connect("ftp.ibiblio.org");
    client.login("anonymous", "");

    String remoteDir = "/pub/mirrors/apache/jakarta/ecs/binaries";

    FTPFile[] remoteFiles = client.listFiles(remoteDir);

    System.out.println("Files in " + remoteDir);

    for (int i = 0; i < remoteFiles.length; i++) {
        String name = remoteFiles[i].getName();
        long length = remoteFiles[i].getSize();
        String readableLength = FileUtils.byteCountToDisplaySize(length);

        System.out.println(name + ":\t\t" + readableLength);
    }/*from www .  j  a  v  a2  s.  c  om*/

    client.disconnect();
}

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

/**
 * FTP?.//from   w  w  w.ja v  a  2s. c o m
 * 
 * @param remotePath
 *            FTP?
 * @param fileName
 *            ???
 * @param localPath
 *            ??
 * @return
 */
public boolean ftpDownFile(String remotePath, String fileName, String localPath) {
    // ?
    boolean success = false;
    // FTPClient
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding("GBK");
    try {
        int reply;
        // FTP?
        // ??ftp.connect(url)?FTP?
        ftp.connect(url, port);
        // ftp
        ftp.login(username, password);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return success;
        }
        // 
        ftp.changeWorkingDirectory(remotePath);
        // 
        FTPFile[] fs = ftp.listFiles();
        // ??
        for (FTPFile ff : fs) {
            if (ff.getName().equals(fileName)) {
                // ???
                File localFile = new File(localPath + "/" + ff.getName());
                // ?
                OutputStream is = new FileOutputStream(localFile);
                // 
                ftp.retrieveFile(ff.getName(), is);
                is.close();
                success = true;
            }
        }
        ftp.logout();
        // ?

    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
            }
        }
    }
    return success;
}

From source file:ftp.search.Index.java

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
    try {/*from   www . j a va2 s .  c om*/
        // TODO add your handling code here:
        Class.forName("com.mysql.jdbc.Driver");
        String uid = "root";
        String pwd = "clever";
        String dbURL = "jdbc:mysql://localhost:3306/ftp";
        Connection conn = DriverManager.getConnection(dbURL, uid, pwd);
        Statement statement = conn.createStatement();
        FTPClient ftpClient = new FTPClient();
        String ftp = jTextField1.getText();
        int port = 21;
        try {
            ftpClient.connect(ftp, port);
            int a = ftpClient.getConnectTimeout();
            ftpClient.login("anonymous", "");
            // lists files and directories in the current working directory
            insertFiles(ftp, "/", statement, ftpClient);

            JOptionPane.showMessageDialog(this, "Files Indexed Successfully");
            ftpClient.logout();
            ftpClient.disconnect();
        } catch (IOException ex) {
            Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
        }

    } catch (ClassNotFoundException ex) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
    } catch (SQLException ex) {
        Logger.getLogger(Index.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:hd3gtv.storage.AbstractFileBridgeFtpNexio.java

private FTPClient connectMe() throws IOException {
    FTPClient ftpclient = new FTPClient();
    ftpclient.connect(configurator.host, configurator.port);

    if (ftpclient.login(configurator.username, configurator.password) == false) {
        ftpclient.logout();//from  w  w w.  j a v a  2  s . c o  m
        throw new IOException("Can't login to server");
    }
    int reply = ftpclient.getReplyCode();
    if (FTPReply.isPositiveCompletion(reply) == false) {
        ftpclient.disconnect();
        throw new IOException("Can't login to server");
    }

    ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

    if (configurator.passive) {
        ftpclient.enterLocalPassiveMode();
    } else {
        ftpclient.enterLocalActiveMode();
    }
    ftpclient.changeWorkingDirectory("/" + path);
    if (ftpclient.printWorkingDirectory().equals("/" + path) == false) {
        throw new IOException("Can't change working dir : " + "/" + path);
    }

    return ftpclient;
}

From source file:ddf.test.itests.catalog.TestFtp.java

private void disconnectClient(FTPClient client) {
    if (client != null && client.isConnected()) {
        try {/*  w w w . j a va 2  s .co  m*/
            client.logout();
        } catch (IOException ioe) {
            // ignore
        }
        try {
            client.disconnect();
        } catch (IOException ioe) {
            // ignore
        }
    }
}

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

public void estabishConnection() throws SocketException, IOException, FTPException {

    this.setFtpClient(new FTPClient());
    String errMsg;//  ww w.j a v a2 s  .  co  m

    FTPClient client = this.getFtpClient();
    PrintCommandListener listener = new PrintCommandListener(System.out);
    client.addProtocolCommandListener(listener);

    // Connects to the FTP server
    String host = this.getFtpServerHost();
    int port = this.getFtpServerPort();
    client.connect(host, port);
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        client.disconnect();
        errMsg = "Unable to connect to the server " + this.getFtpServerHost();
        this.verifyReplyCode(errMsg);
    }

    // Login to the FTP server
    String username = this.getFtpUser();
    String pass = this.getFtpPassword();
    if (!client.login(username, pass)) {
        errMsg = "Unable to login to " + this.getFtpServerHost();
        this.verifyReplyCode(errMsg);
    }

    // Change the current directory
    String dirname = this.getFtpServerDir();
    if (!client.changeWorkingDirectory(dirname)) {

        System.out.println("Unable to change to the directory '" + dirname + "'.");
        System.out.println("Going to create the directory !");
        this.mkdirs(dirname);
        System.out.println("Creation of the directory is successful.");
    }

    client.changeWorkingDirectory(dirname);
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        errMsg = "Unable to change to the directory : " + dirname;
        this.verifyReplyCode(errMsg);
    }

    client.pwd();
}

From source file:de.ipk_gatersleben.ag_nw.graffiti.services.GUIhelper.java

public static ArrayList<String> performDirectoryListing(String downloadURL,
        BackgroundTaskStatusProviderSupportingExternalCall status) {
    if (status == null)
        status = new BackgroundTaskConsoleLogger("downloading: " + downloadURL, "please wait", false);
    String server, remote;/*from   w  ww  .j a va 2  s  .c  om*/

    runIdx++;
    final int thisRun = runIdx;

    server = downloadURL.substring("ftp://".length());
    remote = server.substring(server.indexOf("/") + "/".length());
    server = server.substring(0, server.indexOf("/"));

    ArrayList<String> result = null;

    final FTPClient ftp;
    ThreadSafeOptions tso;
    synchronized (host2ftp) {
        if (!host2ftp.containsKey(server)) {
            ThreadSafeOptions ttt = new ThreadSafeOptions();
            ttt.setParam(0, new FTPClient());
            host2ftp.put(server, ttt);
        }
        tso = host2ftp.get(server);
        ftp = (FTPClient) tso.getParam(0, null);
    }
    status.setCurrentStatusValue(0);

    try {
        result = listFiles(status, downloadURL, server, remote, ftp);
        status.setCurrentStatusText2("Finished: " + downloadURL);

        BackgroundTaskHelper.executeLaterOnSwingTask(10000, new Runnable() {
            public void run() {
                try {
                    synchronized (GUIhelper.class) {
                        if (runIdx == thisRun) {
                            System.out.println("Disconnect FTP connection");
                            ftp.disconnect();
                        }
                    }
                } catch (Exception err) {
                    ErrorMsg.addErrorMessage(err);
                }
            }
        });
    } catch (Exception e) {
        ErrorMsg.addErrorMessage(e);
    }
    return result;
}

From source file:com.cisco.dvbu.ps.utils.net.FtpFile.java

public void ftpFile(String fileName) throws CustomProcedureException, SQLException {

    // new ftp client
    FTPClient ftp = new FTPClient();
    OutputStream output = null;/*  w w w  .  j  a v  a2s . c om*/

    success = false;
    try {
        //try to connect
        ftp.connect(hostIp);

        //login to server
        if (!ftp.login(userId, userPass)) {
            ftp.logout();
            qenv.log(LOG_ERROR, "Ftp server refused connection user/password incorrect.");
        }
        int reply = ftp.getReplyCode();

        //FTPReply stores a set of constants for FTP Reply codes
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            qenv.log(LOG_ERROR, "Ftp server refused connection.");
        }

        //enter passive mode
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE, FTPClient.BINARY_FILE_TYPE);
        ftp.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();

        //get system name
        //System.out.println("Remote system is " + ftp.getSystemType());

        //change current directory
        ftp.changeWorkingDirectory(ftpDirName);
        System.out.println("Current directory is " + ftp.printWorkingDirectory());
        System.out.println("File is " + fileName);

        output = new FileOutputStream(dirName + "/" + fileName);

        //get the file from the remote system
        success = ftp.retrieveFile(fileName, output);

        //close output stream
        output.close();

    } catch (IOException ex) {
        throw new CustomProcedureException("Error in CJP " + getName() + ": " + ex.toString());
    }
}

From source file:eu.ggnet.dwoss.misc.op.listings.FtpTransfer.java

/**
 * Uploads a some files to a remove ftp host.
 * <p/>// www . j a v  a2s. c om
 * @param config  the config for he connection.
 * @param uploads the upload commands
 * @param monitor an optional monitor.
 * @throws java.net.SocketException
 * @throws java.io.IOException
 */
public static void upload(ConnectionConfig config, IMonitor monitor, UploadCommand... uploads)
        throws SocketException, IOException {
    if (uploads == null || uploads.length == 0)
        return;
    SubMonitor m = SubMonitor.convert(monitor, "FTP Transfer", toWorkSize(uploads) + 4);
    m.message("verbinde");
    m.start();
    FTPClient ftp = new FTPClient();
    ftp.addProtocolCommandListener(PROTOCOL_TO_LOGGER);

    try {
        ftp.connect(config.getHost(), config.getPort());
        if (!FTPReply.isPositiveCompletion(ftp.getReplyCode()))
            throw new IOException("FTPReply.isPositiveCompletion(ftp.getReplyCode()) = false");
        if (!ftp.login(config.getUser(), config.getPass()))
            throw new IOException("Login with " + config.getUser() + " not successful");
        L.info("Connected to {} idenfied by {}", config.getHost(), ftp.getSystemType());

        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        for (UploadCommand upload : uploads) {
            m.worked(1, "uploading to " + upload.getPath());
            ftp.changeWorkingDirectory(upload.getPath());
            deleteFilesByType(ftp, upload.getDeleteFileTypes());
            for (File file : upload.getFiles()) {
                m.worked(1, "uploading to " + upload.getPath() + " file " + file.getName());
                try (InputStream input = new FileInputStream(file)) {
                    if (!ftp.storeFile(file.getName(), input))
                        throw new IOException("Cannot store file " + file + " on server!");
                }
            }
        }
        m.finish();
    } finally {
        // just cleaning up
        try {
            ftp.logout();
        } catch (IOException e) {
        }
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException f) {
            }
        }
    }
}

From source file:com.starr.smartbuilds.service.FileService.java

public String getFile(Build build, ServletContext sc)
        throws FileNotFoundException, IOException, ParseException {

    /*if (fileName == null || fileName.equals("") || fileText == null || fileText.equals("")) {
     resultMsg = "<font color='red'>Fail: File is not created!</font>";
     } else {/*from   ww w.j  a v  a2s . c o m*/
     try {*/
    String path = sc.getRealPath("/");
    System.out.println(path);
    File dir = new File(path + "/builds");
    if (!dir.exists() || !dir.isDirectory()) {
        dir.mkdir();
    }

    String fileName = path + "/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json";
    File fileBuild = new File(fileName);
    if (!fileBuild.exists() || fileBuild.isDirectory()) {
        String file_data = buildService.buildData(build, buildService.parseBlocks(build.getBlocks()));
        fileBuild.createNewFile();
        FileOutputStream fos = new FileOutputStream(fileBuild, false);
        fos.write(file_data.getBytes());
        fos.close();
    }

    FTPClient client = new FTPClient();
    FileInputStream fis = null;

    try {
        client.connect("itelit.ftp.ukraine.com.ua");
        client.login("itelit_dor", "154896");

        // Create an InputStream of the file to be uploaded
        fis = new FileInputStream(fileBuild.getAbsolutePath());

        // Store file to server
        client.storeFile("builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json", fis);
        client.logout();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /*} catch (IOException ex) {
     resultMsg = "<font color='red'>Fail: File is not created!</font>";
     }
     }*/
    return "http://dor.it-elit.org/builds/" + build.getChampion().getKeyChamp() + build.getId() + ".json";
}