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:hd3gtv.storage.AbstractFileBridgeFtpNexio.java

public AbstractFile[] listFiles() {
    try {//from ww w  .j a v  a  2 s .c  om
        FTPClient ftpclient = connectMe();
        FTPFile[] files = ftpclient.listFiles();

        if (files == null) {
            return new AbstractFile[1];
        }

        AbstractFile[] absfiles = new AbstractFile[files.length];

        for (int pos = 0; pos < files.length; pos++) {
            if (files[pos].isDirectory() == false) {
                absfiles[pos] = new SimpleMediaFile(files[pos].getName(), this, files[pos].getSize());
            }
        }
        ftpclient.disconnect();
        return absfiles;
    } catch (IOException e) {
        Log2.log.error("Can't dirlist", e, this);
    }
    return null;
}

From source file:edu.cmu.cs.in.hoop.hoops.load.HoopFTPReader.java

/**
 * //  ww  w  .j av  a 2s.  com
 */
private String retrieveFTP(String aURL) {
    debug("retrieveFTP (" + aURL + ")");

    URL urlObject = null;

    try {
        urlObject = new URL(aURL);
    } catch (MalformedURLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String downloadPath = this.projectToFullPath("<PROJECTPATH>/tmp/download/");
    HoopLink.fManager.createDirectory(downloadPath);

    File translator = new File(urlObject.getFile());

    String localFileName = "<PROJECTPATH>/tmp/download/" + translator.getName();

    OutputStream fileStream = null;

    if (HoopLink.fManager.openStreamBinary(this.projectToFullPath(localFileName)) == false) {
        this.setErrorString("Error opening temporary output file");
        return (null);
    }

    fileStream = HoopLink.fManager.getOutputStreamBinary();

    if (fileStream == null) {
        this.setErrorString("Error opening temporary output file");
        return (null);
    }

    debug("Starting FTP client ...");

    FTPClient ftp = new FTPClient();

    try {
        int reply;

        debug("Connecting ...");

        ftp.connect(urlObject.getHost());

        debug("Connected to " + urlObject.getHost() + ".");
        debug(ftp.getReplyString());

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            debug("FTP server refused connection.");
            return (null);
        } else {
            ftp.login("anonymous", "hoop-dev@gmail.com");

            reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                debug("Unable to login to FTP server");
                return (null);
            }

            debug("Logged in");

            boolean rep = true;

            String pathFixed = translator.getParent().replace("\\", "/");

            rep = ftp.changeWorkingDirectory(pathFixed);
            if (rep == false) {
                debug("Unable to change working directory to: " + pathFixed);
                return (null);
            } else {
                debug("Current working directory: " + pathFixed);

                debug("Retrieving file " + urlObject.getFile() + " ...");

                try {
                    rep = ftp.retrieveFile(urlObject.getFile(), fileStream);
                } catch (FTPConnectionClosedException connEx) {
                    debug("Caught: FTPConnectionClosedException");
                    connEx.printStackTrace();
                    return (null);
                } catch (CopyStreamException strEx) {
                    debug("Caught: CopyStreamException");
                    strEx.printStackTrace();
                    return (null);
                } catch (IOException ioEx) {
                    debug("Caught: IOException");
                    ioEx.printStackTrace();
                    return (null);
                }

                debug("File retrieved");
            }

            ftp.logout();
        }
    } catch (IOException e) {
        debug("Error retrieving FTP file");
        e.printStackTrace();
        return (null);
    } finally {
        if (ftp.isConnected()) {
            debug("Closing ftp connection ...");

            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                debug("Exception closing ftp connection");
            }
        }
    }

    debug("Closing local file stream ...");

    try {
        fileStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

    String result = HoopLink.fManager.loadContents(this.projectToFullPath(localFileName));

    return (result);
}

From source file:com.cladonia.xngreditor.URLUtilities.java

public static void save(URL url, InputStream input, String encoding) throws IOException {
    //        System.out.println( "URLUtilities.save( "+url+", "+encoding+")");

    String password = URLUtilities.getPassword(url);
    String username = URLUtilities.getUsername(url);

    String protocol = url.getProtocol();

    if (protocol.equals("ftp")) {
        FTPClient client = null;
        String host = url.getHost();

        client = new FTPClient();
        //               System.out.println( "Connecting ...");
        client.connect(host);//from www . j a v a  2s.c  om
        //               System.out.println( "Connected.");

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

        if (!FTPReply.isPositiveCompletion(reply)) {
            //                  System.out.println( "Disconnecting...");

            client.disconnect();
            throw new IOException("FTP Server \"" + host + "\" refused connection.");
        }

        //               System.out.println( "Logging in ...");

        if (!client.login(username, password)) {
            //                  System.out.println( "Could not log in.");
            // TODO bring up login dialog?
            client.disconnect();

            throw new IOException("Could not login to FTP Server \"" + host + "\".");
        }

        //               System.out.println( "Logged in.");

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

        //               System.out.println( "Writing output ...");

        OutputStream output = client.storeFileStream(url.getFile());

        //             if( !FTPReply.isPositiveIntermediate( client.getReplyCode())) {
        //                 output.close();
        //                 client.disconnect();
        //                 throw new IOException( "Could not transfer file \""+url.getFile()+"\".");
        //             }

        InputStreamReader reader = new InputStreamReader(input, encoding);
        OutputStreamWriter writer = new OutputStreamWriter(output, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);
            ch = reader.read();
        }

        writer.flush();
        writer.close();
        output.close();

        // Must call completePendingCommand() to finish command.
        if (!client.completePendingCommand()) {
            client.disconnect();
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        } else {
            client.disconnect();
        }

    } else if (protocol.equals("http") || protocol.equals("https")) {
        WebdavResource webdav = createWebdavResource(toString(url), username, password);
        if (webdav != null) {
            webdav.putMethod(url.getPath(), input);
            webdav.close();
        } else {
            throw new IOException("Could not transfer file \"" + url.getFile() + "\".");
        }
    } else if (protocol.equals("file")) {
        FileOutputStream stream = new FileOutputStream(toFile(url));
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stream, encoding));

        InputStreamReader reader = new InputStreamReader(input, encoding);

        int ch = reader.read();

        while (ch != -1) {
            writer.write(ch);

            ch = reader.read();
        }

        writer.flush();
        writer.close();
    } else {
        throw new IOException("The \"" + protocol + "\" protocol is not supported.");
    }
}

From source file:com.buzz.buzzdata.MongoBuzz.java

private InputStream getFTPInputStream(String ftp_location) {
    InputStream retval = null;// w  w  w  . j  a va2s .c om

    String server = "162.219.245.61";
    int port = 21;
    String user = "jelastic-ftp";
    String pass = "HeZCHxeefB";
    FTPClient ftpClient = new FTPClient();

    try {
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);
        ftpClient.enterLocalPassiveMode();
        ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
        retval = ftpClient.retrieveFileStream(ftp_location);
    } catch (IOException ex) {
        Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            Logger.getLogger(MongoBuzz.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return retval;
}

From source file:com.webarch.common.net.ftp.FtpService.java

/**
 * /*from w w  w .ja  va  2s.c  om*/
 *
 * @param fileName   ??
 * @param path       ftp?
 * @param fileStream ?
 * @return true/false ?
 */
public boolean uploadFile(String fileName, String path, InputStream fileStream) {
    boolean success = false;
    FTPClient ftpClient = new FTPClient();
    try {
        int replyCode;
        ftpClient.connect(url, port);
        ftpClient.login(userName, password);
        replyCode = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(replyCode)) {
            return false;
        }
        ftpClient.changeWorkingDirectory(path);
        ftpClient.storeFile(fileName, fileStream);
        fileStream.close();
        ftpClient.logout();
        success = true;
    } catch (IOException e) {
        logger.error("ftp?", e);
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException e) {
                logger.error("ftp?", e);
            }
        }
    }
    return success;
}

From source file:facturacion.ftp.FtpServer.java

public static InputStream getFileInputStream(String remote_file_ruta) {
    FTPClient ftpClient = new FTPClient();
    try {// w w w  .j  ava 2s  .c om
        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);
        //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 ruta=" + "1/" + remote_file_ruta);
        InputStream is = ftpClient.retrieveFileStream(remote_file_ruta);

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

        //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.tobias.vocabulary_trainer.UpdateVocabularies.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.update_vocabularies_layout);
    prefs = getSharedPreferences(USER_PREFERENCE, Activity.MODE_PRIVATE);
    serverAdresseEditText = (EditText) findViewById(R.id.server_adresse_edit_text);
    serverUsernameEditText = (EditText) findViewById(R.id.server_username_edit_text);
    serverPasswordEditText = (EditText) findViewById(R.id.server_password_edit_text);
    serverPortEditText = (EditText) findViewById(R.id.server_port_edit_text);
    serverFileEditText = (EditText) findViewById(R.id.server_file_edit_text);
    localFileEditText = (EditText) findViewById(R.id.local_file_edit_text);

    vocabularies = new VocabularyData(this);
    System.out.println("before updateUIFromPreferences();");
    updateUIFromPreferences();//from   w w  w .j  a  va2s .c o m
    System.out.println("after updateUIFromPreferences();");

    final Button ServerOkButton = (Button) findViewById(R.id.server_ok);
    ServerOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            System.out.println("ServerOKButton pressed");
            savePreferences();
            InputStream in;
            String serverAdresse = serverAdresseEditText.getText().toString();
            String serverUsername = serverUsernameEditText.getText().toString();
            String serverPassword = serverPasswordEditText.getText().toString();
            int serverPort = Integer.parseInt(serverPortEditText.getText().toString());
            String serverFile = serverFileEditText.getText().toString();

            FTPClient ftp;
            ftp = new FTPClient();
            try {
                int reply;
                System.out.println("try to connect to ftp server");
                ftp.connect(serverAdresse, serverPort);
                System.out.print(ftp.getReplyString());
                // After connection attempt, you should check the reply code to verify
                // success.
                reply = ftp.getReplyCode();
                if (FTPReply.isPositiveCompletion(reply)) {
                    System.out.println("connected to ftp server");
                } else {
                    ftp.disconnect();
                    System.out.println("FTP server refused connection.");
                }

                // transfer files
                System.out.println("try to login");
                ftp.login(serverUsername, serverPassword);
                System.out.println("current working directory: " + ftp.printWorkingDirectory());
                System.out.println("try to start downloading");
                in = ftp.retrieveFileStream(serverFile);
                // files transferred
                //write to database and textfile on sdcard
                vocabularies.readVocabularies(in, false);
                ftp.logout();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ftp.isConnected()) {
                    try {
                        ftp.disconnect();
                    } catch (IOException ioe) {
                        // do nothing
                    }
                }
            }
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button LocalFileOkButton = (Button) findViewById(R.id.local_file_ok);
    LocalFileOkButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            File f = new File(Environment.getExternalStorageDirectory(),
                    localFileEditText.getText().toString());
            savePreferences();
            vocabularies.readVocabularies(f, false);
            //               settings.populateSpinners();
            finish();
        }
    });
    final Button CancelButton = (Button) findViewById(R.id.Cancel);
    CancelButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            finish();
        }
    });
    vocabularies.close();
}

From source file:com.ephesoft.dcma.ftp.service.FTPServiceImpl.java

/**
 * API to download a particular directory from FTP Server.
 * //from www.  ja  va2s .  c  o  m
 * @param sourceDirName {@link String} - Name of the source directory to be copied.
 * @param destDirectoryPath {@link String} - Full path where directory need to be copied.
 * @param retryCounter - Start with zero.
 * @param isDeletedFTPServerSourceContent - set true for deleted the ftp server content.
 * @throws FTPDataDownloadException if any error occurs while downloading the file.
 */
@Override
public void downloadDirectory(final String sourceDirName, final String destDirectoryPath,
        final int numberOfRetryCounter, boolean isDeletedFTPServerSourceContent)
        throws FTPDataDownloadException {
    boolean isValid = true;
    if (sourceDirName == null) {
        isValid = false;
        LOGGER.error(var_source_dir);
        throw new FTPDataDownloadException(var_source_dir);
    }
    if (destDirectoryPath == null) {
        isValid = false;
        LOGGER.error(var_source_des);
        throw new FTPDataDownloadException(var_source_des);
    }
    if (isValid) {
        FTPClient client = new FTPClient();
        String outputFileName = null;
        File file = new File(destDirectoryPath);
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            createConnection(client);
            int reply = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(reply)) {
                LOGGER.info("Starting File Download...");
            } else {
                LOGGER.error("Invalid Connection to FTP server. Disconnecting from FTP server....");
                client.disconnect();
                isValid = false;
                throw new FTPDataDownloadException(
                        "Invalid Connection to FTP server. Disconnecting from FTP server....");
            }
            if (isValid) {
                client.setFileType(FTP.BINARY_FILE_TYPE);
                String ftpDirectory = EphesoftStringUtil.concatenate(uploadBaseDir, File.separator,
                        sourceDirName);
                LOGGER.info("Downloading files from FTP server");
                try {
                    FTPUtil.retrieveFiles(client, ftpDirectory, destDirectoryPath);
                } catch (IOException e) {
                    int retryCounter = numberOfRetryCounter;
                    LOGGER.info("Retrying download Attempt#-" + (retryCounter + 1));
                    if (retryCounter < numberOfRetries) {
                        retryCounter = retryCounter + 1;
                        downloadDirectory(sourceDirName, destDirectoryPath, retryCounter,
                                isDeletedFTPServerSourceContent);
                    } else {
                        LOGGER.error("Error in getting file from FTP server :" + outputFileName);
                    }
                }
                if (isDeletedFTPServerSourceContent) {
                    FTPUtil.deleteExistingFTPData(client, ftpDirectory, true);
                }
            }
        } catch (FileNotFoundException e) {
            LOGGER.error("Error in generating output Stream for file :" + outputFileName);
        } catch (SocketException e) {
            LOGGER.error("Could not connect to FTP Server-" + ftpServerURL + e);
        } catch (IOException e) {
            LOGGER.error("Could not connect to FTP Server-" + ftpServerURL + e);
        } finally {
            try {
                client.disconnect();
            } catch (IOException e) {
                LOGGER.error("Error in disconnecting from FTP server." + e);
            }
        }
    }
}

From source file:ca.efendi.datafeeds.messaging.FtpSubscriptionMessageListener.java

public void fetch(final FtpSubscription ftpSubscription) {
    if (_log.isDebugEnabled()) {
        _log.debug("fetching " + ftpSubscription);
    }// w  w w  . ja  va2s  .  co  m
    final FTPClient ftp = new FTPClient();
    ftp.setControlKeepAliveTimeout(30);
    ftp.setControlKeepAliveReplyTimeout(30);
    ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out), true));
    try {
        int reply;
        ftp.connect(ftpSubscription.getFtpHost());
        _log.debug("Connected to " + ftpSubscription.getFtpHost() + " on " + ftp.getDefaultPort());
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.err.println("FTP server refused connection.");
            System.exit(1);
        }
    } catch (final IOException e) {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException f) {
                // do nothing
            }
        }
        System.err.println("Could not connect to server.");
        e.printStackTrace();
        System.exit(1);
    }
    boolean error = false;
    __main: try {
        if (!ftp.login(ftpSubscription.getFtpUser(), ftpSubscription.getFtpPassword())) {
            ftp.logout();
            error = true;
            break __main;
        }
        _log.info("Remote system is " + ftp.getSystemType());
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        //ftp.enterLocalActiveMode();
        ftp.enterLocalPassiveMode();
        //final FTPClientConfig config = new FTPClientConfig();
        ////config.setLenientFutureDates(true);
        //ftp.configure(config);
        if (!StringUtils.isBlank(ftpSubscription.getFtpFolder())) {
            ftp.changeWorkingDirectory(ftpSubscription.getFtpFolder());
        }
        final InputStream is = ftp.retrieveFileStream(ftpSubscription.getFtpFile());
        if (is == null) {
            _log.error("FIle not found: " + ftp.getSystemType());
        } else {
            unzip(ftpSubscription, is);
            is.close();
        }
        ftp.completePendingCommand();
    } catch (final FTPConnectionClosedException e) {
        error = true;
        System.err.println("Server closed connection.");
        e.printStackTrace();
    } catch (final IOException e) {
        error = true;
        e.printStackTrace();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (final IOException e) {
                _log.error(e);
            }
        }
    }
}

From source file:com.cladonia.xngreditor.URLUtilities.java

public static InputStream open(URL url) throws IOException {
    //        System.out.println( "URLUtilities.open( "+url+")");
    InputStream stream = null;/*from  www. j  a  v  a2  s  .  com*/

    String password = URLUtilities.getPassword(url);
    String username = URLUtilities.getUsername(url);

    String protocol = url.getProtocol();

    if (protocol.equals("http") || protocol.equals("https")) {
        try {
            DefaultAuthenticator authenticator = Main.getDefaultAuthenticator();

            URL newURL = new URL(URLUtilities.toString(url));

            if (authenticator != null && password != null && username != null) {
                authenticator.setPasswordAuthentication(
                        new PasswordAuthentication(username, password.toCharArray()));
            }

            stream = newURL.openStream();

            if (authenticator != null && password != null && username != null) {
                authenticator.setPasswordAuthentication(null);
            }
        } catch (Exception e) {
            //            System.out.println( "Could not use normal http connection, because of:\n"+e.getMessage());
            // try it with webdav
            WebdavResource webdav = createWebdavResource(toString(url), username, password);

            stream = webdav.getMethodData(toString(url));

            webdav.close();
        }
    } else if (protocol.equals("ftp")) {
        FTPClient client = null;
        String host = url.getHost();

        try {
            //               System.out.println( "Connecting to: "+host+" ...");

            client = new FTPClient();
            client.connect(host);

            //               System.out.println( "Connected.");

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

            if (!FTPReply.isPositiveCompletion(reply)) {
                //                  System.out.println( "Could not connect.");
                client.disconnect();
                throw new IOException("FTP Server \"" + host + "\" refused connection.");
            }

            //               System.out.println( "Logging in using: "+username+", "+password+" ...");

            if (!client.login(username, password)) {
                //                  System.out.println( "Could not log in.");
                // TODO bring up login dialog?
                client.disconnect();

                throw new IOException("Could not login to FTP Server \"" + host + "\".");
            }

            //               System.out.println( "Logged in.");

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

            //               System.out.println( "Opening file \""+url.getFile()+"\" ...");

            stream = client.retrieveFileStream(url.getFile());
            //               System.out.println( "File opened.");

            //               System.out.println( "Disconnecting ...");
            client.disconnect();
            //               System.out.println( "Disconnected.");

        } catch (IOException e) {
            if (client.isConnected()) {
                try {
                    client.disconnect();
                } catch (IOException f) {
                    // do nothing
                    e.printStackTrace();
                }
            }

            throw new IOException("Could not connect to FTP Server \"" + host + "\".");
        }

    } else if (protocol.equals("file")) {
        stream = url.openStream();
    } else {

        //unknown protocol but try anyways
        try {
            stream = url.openStream();
        } catch (IOException ioe) {

            throw new IOException("The \"" + protocol + "\" protocol is not supported.");
        }
    }

    return stream;
}