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.hackengine_er.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {//ww  w  . j a v a2s.  c  o m
        client.connect(Configuration.FTPClient());
        if (client.login(Configuration.FTPUsername(), Configuration.getPASSWORD())) {
            client.setDefaultTimeout(10000);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (client.storeFile(Tags.SITE + username + "-" + fileName, inputStream)) {
                return true;
            }
        }
    } catch (IOException e) {
        Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return false;
}

From source file:com.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {/*  www . jav a2s  .  co  m*/
        client.connect(Initialize.FTPClient());
        if (client.login(Initialize.FTPUsername(), Initialize.getPASSWORD())) {
            client.setDefaultTimeout(10000);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (client.storeFile(Tags.SITE + username + "/" + fileName, inputStream)) {
                return true;
            }
        }
    } catch (IOException e) {
        Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return false;
}

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

@Override
public void upload(String path, File file, String contentType) {
    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");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {/*from ww  w  . j  ava  2s .  c om*/
            inputStream = new FileInputStream(file);
            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())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.claim.controller.FileTransferController.java

public boolean uploadMutiFilesWithFTP(ObjFileTransfer ftpObj) throws Exception {
    FTPClient ftpClient = new FTPClient();
    int replyCode;
    boolean completed = false;
    try {//from  ww  w  . j a v  a  2  s  .  co  m

        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        try {
            ftpClient.connect(properties.getFtp_server(), properties.getFtp_port());
            FtpUtil.showServerReply(ftpClient);
        } catch (ConnectException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("ConnectException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (SocketException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("SocketException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (UnknownHostException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("UnknownHostException: " + ex.getMessage());
            ex.printStackTrace();
        }

        replyCode = ftpClient.getReplyCode();
        FtpUtil.showServerReply(ftpClient);

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            FtpUtil.showServerReply(ftpClient);
            ftpClient.disconnect();
            Console.LOG("Exception in connecting to FTP Serve ", 0);
            throw new Exception("Exception in connecting to FTP Server");
        } else {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG("Success in connecting to FTP Serve ", 1);
        }

        try {
            boolean success = ftpClient.login(properties.getFtp_username(), properties.getFtp_password());
            FtpUtil.showServerReply(ftpClient);
            if (!success) {
                throw new Exception("Could not login to the FTP server.");
            } else {
                Console.LOG("login to the FTP server. Successfully ", 1);
            }
            //ftpClient.enterLocalPassiveMode();
        } catch (FTPConnectionClosedException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();

        // APPROACH #2: uploads second file using an OutputStream
        File files = new File(ftpObj.getFtp_directory_path());

        String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator
                + ftpObj.getFtp_report_type();
        FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryReportType);
        FtpUtil.showServerReply(ftpClient);

        String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp();
        FtpUtil.ftpCreateDirectoryTree(ftpClient, workingDirectoryStmp);
        FtpUtil.showServerReply(ftpClient);

        for (File file : files.listFiles()) {
            if (file.isFile()) {
                System.out.println("file ::" + file.getName());
                InputStream in = new FileInputStream(file);
                ftpClient.changeWorkingDirectory(workingDirectoryStmp);
                completed = ftpClient.storeFile(file.getName(), in);
                in.close();
                Console.LOG(
                        "  " + file.getName() + " ",
                        1);
                FtpUtil.showServerReply(ftpClient);
            }
        }
        Console.LOG(" ?... ", 1);

        //completed = ftpClient.completePendingCommand();
        FtpUtil.showServerReply(ftpClient);
        completed = true;
        ftpClient.disconnect();

    } catch (IOException ex) {
        Console.LOG(ex.getMessage(), 0);
        FtpUtil.showServerReply(ftpClient);
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpClient.isConnected()) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            FtpUtil.showServerReply(ftpClient);
            Console.LOG(ex.getMessage(), 0);
            ex.printStackTrace();
        }
    }
    return completed;
}

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

private static ArrayList<String> listFiles(final BackgroundTaskStatusProviderSupportingExternalCall status,
        String downloadURL, String server, String remotePath, final FTPClient ftp) {
    String username;//from   w ww  .  ja v  a  2 s.c o  m
    String password;
    username = "anonymous@" + server;
    password = "anonymous";

    final ObjectRef myoutputstream = new ObjectRef();

    ftp.addProtocolCommandListener(new ProtocolCommandListener() {
        public void protocolCommandSent(ProtocolCommandEvent arg0) {
            status.setCurrentStatusText1("Command: " + arg0.getMessage());
        }

        public void protocolReplyReceived(ProtocolCommandEvent arg0) {
            status.setCurrentStatusText2("Message: " + arg0.getMessage());
            if (myoutputstream.getObject() != null) {
                String msg = arg0.getMessage();
                if (msg.indexOf("Opening BINARY mode") >= 0) {
                    if (msg.indexOf("(") > 0) {
                        msg = msg.substring(msg.indexOf("(") + "(".length());
                        if (msg.indexOf(" ") > 0) {
                            msg = msg.substring(0, msg.indexOf(" "));
                            try {
                                long max = Long.parseLong(msg);
                                MyOutputStream os = (MyOutputStream) myoutputstream.getObject();
                                os.setMaxBytes(max);
                            } catch (Exception e) {
                                System.out.println(
                                        "Could not determine file length for detailed progress information");
                            }
                        }
                    }
                }
            }
        }
    });

    System.out.println("FTP LIST DIRECTORY: " + downloadURL);

    try {
        if (ftp.isConnected()) {
            status.setCurrentStatusText2("Using open FTP connection");
            System.out.println("Reusing open FTP connection");
        } else {
            ftp.connect(server);
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                status.setCurrentStatusText1("Can't connect to FTP server");
                status.setCurrentStatusText2("ERROR");
                return new ArrayList<String>();
            }
            if (!ftp.login("anonymous", "anonymous")) {
                if (!ftp.login(username, password)) {
                    ftp.disconnect();
                    status.setCurrentStatusText1("Can't login to FTP server");
                    status.setCurrentStatusText2("ERROR");
                    return new ArrayList<String>();
                }
            }
            status.setCurrentStatusText1("Set Binary Transfer Mode");
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            status.setCurrentStatusText2("Activate Passive Transfer Mode");
            ftp.enterLocalPassiveMode();
        }
        status.setCurrentStatusText1("Start download...");
        status.setCurrentStatusText2("Please Wait.");

        ftp.setRemoteVerificationEnabled(false);

        FTPFile[] res = ftp.listFiles(remotePath);

        ArrayList<String> result = new ArrayList<String>();

        for (FTPFile r : res) {
            result.add(r.getName());
        }

        return result;
    } catch (Exception err) {
        ErrorMsg.addErrorMessage(err);
        if (ftp != null && ftp.isConnected()) {
            try {
                System.out.println("Disconnect FTP connection (following error condition)");
                ftp.disconnect();
            } catch (Exception err2) {
                ErrorMsg.addErrorMessage(err2);
            }
        }
        return new ArrayList<String>();
    }
}

From source file:com.shigeodayo.ardrone.utils.ARDroneInfo.java

private boolean connectToDroneThroughFtp() {
    FTPClient client = new FTPClient();
    BufferedOutputStream bos = null;

    try {//from  ww w .  ja v  a2 s .c  o  m
        client.connect(ARDroneConstants.IP_ADDRESS, ARDroneConstants.FTP_PORT);

        if (!client.login("anonymous", "")) {
            ARDrone.error("Login failed", this);
            return false;
        }

        client.setFileType(FTP.BINARY_FILE_TYPE);

        bos = new BufferedOutputStream(new OutputStream() {

            @Override
            public void write(int arg0) throws IOException {
                //System.out.println("aa:" + (char)arg0);
                switch (count) {
                case 0:
                    major = arg0 - '0';
                    break;
                case 2:
                    minor = arg0 - '0';
                    break;
                case 4:
                    revision = arg0 - '0';
                    break;
                default:
                    break;
                }
                count++;
            }
        });

        if (!client.retrieveFile("/" + VERSION_FILE_NAME, bos)) {
            ARDrone.error("Cannot find \"" + VERSION_FILE_NAME + "\"", this);
            return false;
        }

        bos.flush();

        //System.out.print("major:" + major);
        //System.out.print(" minor:" + minor);
        //System.out.println(" revision:" + revision);

        //System.out.println("done");
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (bos != null) {
                bos.flush();
                bos.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }
    return true;
}

From source file:net.shopxx.plugin.ftpStorage.FtpStoragePlugin.java

@Override
public void upload(String path, File file, String contentType) {
    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");
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {/* w w w. j a v a  2 s. com*/
            inputStream = new BufferedInputStream(new FileInputStream(file));
            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())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (SocketException e) {
            throw new RuntimeException(e.getMessage(), e);
        } catch (IOException e) {
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            IOUtils.closeQuietly(inputStream);
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.savy3.util.MainframeFTPClientUtils.java

public static FTPClient getFTPConnection(Configuration conf) throws IOException {
    FTPClient ftp = null;
    try {// www .  j  a v a2s.  c o  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:com.hibo.bas.fileplugin.file.FtpPlugin.java

@Override
public void upload(String path, File file, String contentType) {
    Map<String, String> ftpInfo = getFtpInfo(contentType);
    if (!"".equals(ftpInfo.get("host")) && !"".equals(ftpInfo.get("username"))
            && !"".equals(ftpInfo.get("password"))) {
        FTPClient ftpClient = new FTPClient();
        InputStream inputStream = null;
        try {//w w w .j  a  va  2 s  .  c o m
            inputStream = new FileInputStream(file);
            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();
            path = ftpInfo.get("path") + path;
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
                String directory = StringUtils.substringBeforeLast(path, "/");
                String filename = StringUtils.substringAfterLast(path, "/");
                if (!ftpClient.changeWorkingDirectory(directory)) {
                    String[] paths = StringUtils.split(directory, "/");
                    String p = "/";
                    ftpClient.changeWorkingDirectory(p);
                    for (String s : paths) {
                        p += s + "/";
                        if (!ftpClient.changeWorkingDirectory(p)) {
                            ftpClient.makeDirectory(s);
                            ftpClient.changeWorkingDirectory(p);
                        }
                    }
                }
                ftpClient.storeFile(filename, inputStream);
                ftpClient.logout();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(inputStream);
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                }
            }
        }
    }
}

From source file:com.claim.controller.FileTransferController.java

public void readFilesFromServer(String targetDirectory) {
    FTPClient ftpClient = new FTPClient();
    try {//w  ww . j av a  2 s .com

        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        ftpClient.connect(properties.getFtp_server(), properties.getFtp_port());
        ftpClient.login(properties.getFtp_username(), properties.getFtp_password());
        ftpClient.enterLocalPassiveMode();

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();
        FTPFile[] ftpFiles = ftpClient.listFiles();

        if (ftpFiles != null && ftpFiles.length > 0) {
            //loop thru files
            for (FTPFile file : ftpFiles) {
                if (!file.isFile()) {
                    continue;
                }
                System.out.println("File is " + file.getName());

                //get output stream
                OutputStream output;
                //output = new FileOutputStream(FTP_REMOTE_HOME + "/" + file.getName());
                output = new FileOutputStream(file.getName());
                //get the file from the remote system
                ftpClient.retrieveFile(file.getName(), output);
                //close output stream
                output.close();

                //delete the file
                //ftpClient.deleteFile(file.getName());
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            Logger.getLogger(FileTransferController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}