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:password.pwm.svc.telemetry.FtpTelemetrySender.java

private void disconnectFtpClient(final FTPClient ftpClient) {
    if (ftpClient.isConnected()) {
        try {//w ww .  j  av  a2  s  .  c  o m
            ftpClient.disconnect();
            LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL, "disconnected");
        } catch (IOException e) {
            LOGGER.trace(SessionLabel.TELEMETRY_SESSION_LABEL,
                    "error while disconnecting ftp client: " + e.getMessage());
        }
    }
}

From source file:patcher.FXMLDocumentController.java

@FXML
private void handlePatch(ActionEvent event) throws IOException {
    System.out.println("You clicked me!");
    //split url into server and folderstucture
    String[] uri = serverURL.getText().split("/", 2);
    serverAddress = uri[0];/*w  w  w . ja v a2s  .  c  o  m*/
    folder = "/" + uri[1];

    FTPClient ftp = ftpConnect(serverAddress);
    label.setText("Connecting to " + serverAddress);
    if (ftp == null) {
        label.setText("Connection failed: incorrect url");
        return;
    }

    label.setText("Connection success: " + folder);

    System.out.println("=====Local Files======");
    localdir = locdir.getText();
    File dir = new File(localdir);

    File[] filesList = getLocalFiles(dir);
    ArrayList<String> missing = getMissing(ftp, filesList);
    updateFiles(missing, ftp);

    ftp.disconnect();
}

From source file:Proiect.uploadFTP.java

public void actionFTP() {
    adressf.addCaretListener(new CaretListener() {
        public void caretUpdate(CaretEvent e) {
            InetAddress thisIp;/*from   ww w  . j a  v  a  2 s. c o  m*/
            try {
                thisIp = InetAddress.getLocalHost();
                titleFTP.setText("Connection: " + thisIp.getHostAddress() + " -> " + adressf.getText());
            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            }
        }
    });

    exit.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent arg0) {
            saveState();
            uploadFTP.dispose();
            tree.dispose();
        }
    });

    connect.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            FTPClient client = new FTPClient();
            FileInputStream fis = null;
            String pass = String.valueOf(passf.getPassword());
            try {
                if (filename == null) {
                    status.setText("File does not exist!");
                } else {
                    // Server address
                    client.connect(adressf.getText());
                    // Login credentials
                    client.login(userf.getText(), pass);
                    if (client.isConnected()) {
                        status.setText("Succesfull transfer!");
                        // File type
                        client.setFileType(FTP.BINARY_FILE_TYPE);
                        // File location
                        File file = new File(filepath);
                        fis = new FileInputStream(file);
                        // Change the folder on the server
                        client.changeWorkingDirectory(folderf.getText());
                        // Save the file on the server
                        client.storeFile(filename, fis);
                    } else {
                        status.setText("Transfer failed!");
                    }
                }
                client.logout();
            } catch (IOException e1) {
                Encrypter.printException(e1);
            } finally {
                try {
                    if (fis != null) {
                        fis.close();
                    }
                    client.disconnect();
                } catch (IOException e1) {
                    Encrypter.printException(e1);
                }
            }
        }
    });

    browsef.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {
            int retval = chooserf.showOpenDialog(chooserf);
            if (retval == JFileChooser.APPROVE_OPTION) {
                status.setText("");
                filename = chooserf.getSelectedFile().getName().toString();
                filepath = chooserf.getSelectedFile().getPath();
                filenf.setText(chooserf.getSelectedFile().getName().toString());
            }
        }
    });

    adv.addActionListener(new ActionListener() {

        public void actionPerformed(ActionEvent e) {

            tree.setSize(220, uploadFTP.getHeight());
            tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY());
            tree.setResizable(false);
            tree.setIconImage(Toolkit.getDefaultToolkit()
                    .getImage(getClass().getClassLoader().getResource("assets/ico.png")));
            tree.setUndecorated(true);
            tree.getRootPane().setBorder(BorderFactory.createLineBorder(Encrypter.color_black, 2));
            tree.setVisible(true);
            tree.setLayout(new BorderLayout());

            JLabel labeltree = new JLabel("Server documents");
            labeltree.setOpaque(true);
            labeltree.setBackground(Encrypter.color_light);
            labeltree.setBorder(BorderFactory.createMatteBorder(8, 10, 10, 0, Encrypter.color_light));
            labeltree.setForeground(Encrypter.color_blue);
            labeltree.setFont(Encrypter.font16);

            JButton refresh = new JButton("");
            ImageIcon refresh_icon = getImageIcon("assets/icons/refresh.png");
            refresh.setIcon(refresh_icon);
            refresh.setBackground(Encrypter.color_light);
            refresh.setBorder(BorderFactory.createEmptyBorder(0, 0, 5, 0));
            refresh.setForeground(Encrypter.color_black);
            refresh.setFont(Encrypter.font16);
            refresh.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

            final FTPClient client = new FTPClient();
            DefaultMutableTreeNode top = new DefaultMutableTreeNode(adressf.getText());
            DefaultMutableTreeNode files = null;
            DefaultMutableTreeNode leaf = null;

            final JTree tree_view = new JTree(top);
            tree_view.setForeground(Encrypter.color_black);
            tree_view.setBorder(BorderFactory.createEmptyBorder(0, 10, 0, 0));
            tree_view.putClientProperty("JTree.lineStyle", "None");
            tree_view.setBackground(Encrypter.color_light);
            JScrollPane scrolltree = new JScrollPane(tree_view);
            scrolltree.setBackground(Encrypter.color_light);
            scrolltree.getVerticalScrollBar().setPreferredSize(new Dimension(0, 0));

            UIManager.put("Tree.textBackground", Encrypter.color_light);
            UIManager.put("Tree.selectionBackground", Encrypter.color_blue);
            UIManager.put("Tree.selectionBorderColor", Encrypter.color_blue);

            tree_view.updateUI();

            final String pass = String.valueOf(passf.getPassword());
            try {
                client.connect(adressf.getText());
                client.login(userf.getText(), pass);
                client.enterLocalPassiveMode();
                if (client.isConnected()) {
                    try {
                        FTPFile[] ftpFiles = client.listFiles();
                        for (FTPFile ftpFile : ftpFiles) {
                            files = new DefaultMutableTreeNode(ftpFile.getName());
                            top.add(files);
                            if (ftpFile.getType() == FTPFile.DIRECTORY_TYPE) {
                                FTPFile[] ftpFiles1 = client.listFiles(ftpFile.getName());
                                for (FTPFile ftpFile1 : ftpFiles1) {
                                    leaf = new DefaultMutableTreeNode(ftpFile1.getName());
                                    files.add(leaf);
                                }
                            }
                        }
                    } catch (IOException e1) {
                        Encrypter.printException(e1);
                    }
                    client.disconnect();
                } else {
                    status.setText("Failed connection!");
                }
            } catch (IOException e1) {
                Encrypter.printException(e1);
            } finally {
                try {
                    client.disconnect();
                } catch (IOException e1) {
                    Encrypter.printException(e1);
                }
            }

            tree.add(labeltree, BorderLayout.NORTH);
            tree.add(scrolltree, BorderLayout.CENTER);
            tree.add(refresh, BorderLayout.SOUTH);

            uploadFTP.addComponentListener(new ComponentListener() {

                public void componentMoved(ComponentEvent e) {
                    tree.setLocation(uploadFTP.getX() + 405, uploadFTP.getY());
                }

                public void componentShown(ComponentEvent e) {
                }

                public void componentResized(ComponentEvent e) {
                }

                public void componentHidden(ComponentEvent e) {
                }
            });

            uploadFTP.addWindowListener(new WindowListener() {
                public void windowActivated(WindowEvent e) {
                    tree.toFront();
                }

                public void windowOpened(WindowEvent e) {
                }

                public void windowIconified(WindowEvent e) {
                }

                public void windowDeiconified(WindowEvent e) {
                }

                public void windowDeactivated(WindowEvent e) {
                }

                public void windowClosing(WindowEvent e) {
                }

                public void windowClosed(WindowEvent e) {
                }
            });

            refresh.addActionListener(new ActionListener() {

                public void actionPerformed(ActionEvent e) {
                    tree.dispose();
                    tree.setVisible(true);
                }
            });
        }
    });

}

From source file:rapture.ftp.common.FTPConnection.java

@Override
public void logoffAndDisconnect() {
    try {// w  w w  . j av a  2  s . c o  m
        FTPService.runWithRetry("Error closing connection", this, false, new FTPAction<Boolean>() {
            @Override
            public Boolean run(int attemptNum) throws IOException {
                log.debug(String.format("Disconnecting from %s. Attempt %s of %s", config.getAddress(),
                        attemptNum + 1, config.getRetryCount()));
                FTPClient ftpClient = getFtpClient();
                try {
                    if (isLoggedIn) {
                        ftpClient.logout();
                    }
                    return true;
                } catch (IOException ignore) {
                    return false;
                } finally {
                    ftpClient.disconnect();
                }
            }
        });
    } catch (RaptureException e) {
        log.warn("Unable to log off and disconnect, but will not die: " + ExceptionToString.format(e));
    }
}

From source file:rems.Global.java

public static String UploadFile(InetAddress ftpserverurl, String serverAppDirectory, String PureFileName,
        String fullLocFileUrl, String userName, String password) {
    // get an ftpClient object  
    FTPClient ftpClient = new FTPClient();
    FileInputStream inputStream = null;
    String responsTxt = "";
    try {//from w w  w  .  ja v  a2 s.c om
        // pass directory path on server to connect
        // pass username and password, returned true if authentication is  
        // successful  
        ftpClient.connect(ftpserverurl, 21);
        boolean login = ftpClient.login(userName, password);
        ftpClient.setKeepAlive(false);
        ftpClient.setPassiveNatWorkaround(true);
        if (login) {
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            File firstLocalFile = new File(fullLocFileUrl);
            inputStream = new FileInputStream(firstLocalFile);
            //inputStream.reset();
            boolean uploaded = ftpClient.storeFile(serverAppDirectory + PureFileName, inputStream);
            inputStream.close();
            responsTxt = ftpClient.getReplyString();
            if (uploaded) {
                responsTxt += "File uploaded successfully !";
            } else {
                responsTxt += "Error in uploading file !::" + serverAppDirectory + PureFileName;
            }

            Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nUpload Response ==>\r\n" + responsTxt,
                    Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID);
            // logout the user, returned true if logout successfully  
            boolean logout = ftpClient.logout();
            if (logout) {
                //System.out.println("Connection close...");
            }
        } else {
            Global.errorLog += "Connection Failed..." + responsTxt;
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        }
        return responsTxt;
    } catch (SocketException e) {
        Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } catch (IOException e) {
        Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            Global.errorLog += e.getMessage() + "\r\n" + Arrays.toString(e.getStackTrace());
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        } finally {

        }
    }
    return "";
}

From source file:rems.Global.java

public static String DownloadFile(InetAddress ftpserverurl, String serverAppDirectory, String PureFileName,
        String fullLocFileUrl, String userName, String password) {

    File f = new File(fullLocFileUrl);
    // get an ftpClient object  
    FTPClient ftpClient = new FTPClient();
    String responsTxt = "";
    try {/* w w  w  .j ava 2 s. c  o m*/
        // pass directory path on server to connect  
        ftpClient.connect(ftpserverurl, 21);
        // pass username and password, returned true if authentication is  
        // successful  
        boolean login = ftpClient.login(userName, password);
        if (login) {
            ftpClient.enterLocalPassiveMode();
            //ftpClient.setFileTransferMode(FTP.BLOCK_TRANSFER_MODE);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            OutputStream outputStream1 = new BufferedOutputStream(new FileOutputStream(f));
            boolean download = ftpClient.retrieveFile(serverAppDirectory + PureFileName, outputStream1);
            outputStream1.close();

            //fos = new FileOutputStream(fullLocFileUrl);
            //boolean download = ftpClient.retrieveFile(serverAppDirectory + PureFileName, fos);
            responsTxt = ftpClient.getReplyString();
            if (download) {
                responsTxt += "File downloaded successfully !";
            } else {
                responsTxt += "Error in downloading file !::" + serverAppDirectory + PureFileName;
            }
            Global.updateLogMsg(Global.logMsgID, "\r\n\r\nDownload Response ==>\r\n" + responsTxt,
                    Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
            // logout the user, returned true if logout successfully  
            boolean logout = ftpClient.logout();
            if (logout) {
                //System.out.println("Connection close...");
            }
        } else {
            Global.errorLog += "Connection Failed..." + responsTxt;
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        }
        return responsTxt;
    } catch (SocketException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } catch (IOException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.updateLogMsg(Global.logMsgID,
                "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                Global.gnrlDateStr, Global.rnUser_ID);
        Global.writeToLog();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            Global.errorLog += Arrays.toString(e.getStackTrace());
            Global.updateLogMsg(Global.logMsgID,
                    "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + Global.errorLog, Global.logTbl,
                    Global.gnrlDateStr, Global.rnUser_ID);
            Global.writeToLog();
        } finally {

        }
    }
    Global.updateLogMsg(Global.logMsgID, "\r\n\r\n\r\nThe Program has Errored Out ==>\r\n\r\n" + responsTxt,
            Global.logTbl, Global.gnrlDateStr, Global.rnUser_ID);
    return responsTxt;
}

From source file:rems.Global.java

public static String[] GetFileList(InetAddress ftpServerAddrs, String serverAppDirectory, String dirName,
        String userName, String password) {
    String[] downloadFiles = new String[1];
    StringBuilder result = new StringBuilder();
    FTPClient ftpClient = new FTPClient();
    try {/*w w w .j av a 2 s  .c o  m*/
        // pass directory path on server to connect  
        ftpClient.connect(ftpServerAddrs);
        // pass username and password, returned true if authentication is  
        // successful  
        boolean login = ftpClient.login(userName, password);
        if (login) {
            //System.out.println("Connection established...");
            // get all files from server and store them in an array of  
            // FTPFiles  
            FTPFile[] files = ftpClient.listFiles();
            for (FTPFile file : files) {
                if (file.getType() == FTPFile.FILE_TYPE) {
                    result.append(file.getName());
                    result.append("\n");
                }
            }
            result.replace(result.toString().lastIndexOf("\n"), result.toString().length(), "");
            // logout the user, returned true if logout successfully  
            boolean logout = ftpClient.logout();
            if (logout) {
                System.out.println("Connection close...");
            }
        } else {
            System.out.println("Connection fail...");
        }
        return result.toString().split("\\\n");
    } catch (SocketException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.writeToLog();
    } catch (IOException e) {
        Global.errorLog += Arrays.toString(e.getStackTrace());
        Global.writeToLog();
    } finally {
        try {
            ftpClient.disconnect();
        } catch (IOException e) {
            Global.errorLog += Arrays.toString(e.getStackTrace());
            Global.writeToLog();
        }
    }
    return downloadFiles;
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public <X> X connect(URI remoteHostUri, String username, String password, String remoteHost, int remotePort,
        String options) throws Exception {
    long startTime = new Date().getTime();
    X abstractConnection = null;/*from   ww w  . j  a  v  a  2  s  . c om*/
    FTPClient ftpConnection = new FTPClient();
    try {
        remotePort = (remotePort == -1) ? (int) 21 : remotePort;
        ftpConnection.setDefaultTimeout(60 * 1000);
        ftpConnection.setRemoteVerificationEnabled(false);
        // FTPconnection.setSoTimeout( 60 * 1000 );
        // FTPconnection.setDataTimeout( 60 * 1000 );
        ftpConnection.connect(remoteHost, remotePort);
        ftpConnection.login(username, password);
        ftpConnection.enterLocalPassiveMode();
        ftpConnection.setFileType(FTPClient.BINARY_FILE_TYPE);
        // FTPconnection.setControlKeepAliveTimeout(300);
        // Check reply code for success
        int reply = ftpConnection.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftpConnection.disconnect();
            throw new Exception(ErrorMessages.err_FTC005);
        } else {
            abstractConnection = (X) ftpConnection;
        }
    } catch (IOException se) {
        if (ftpConnection.isConnected()) {
            try {
                ftpConnection.disconnect();
            } catch (IOException ioe) {
                throw new Exception(ErrorMessages.err_FTC005);
            }
        }
    }
    log.info("The FTP sub-module connected to '" + remoteHostUri + "' in " + (new Date().getTime() - startTime)
            + " ms.");
    return abstractConnection;
}

From source file:ro.kuberam.libs.java.ftclient.FTP.FTP.java

public static Boolean disconnect(Object abstractConnection) throws Exception {
    long startTime = new Date().getTime();
    FTPClient FTPconnection = (FTPClient) abstractConnection;
    if (!FTPconnection.isConnected()) {
        throw new Exception(ErrorMessages.err_FTC002);
    }/*  w  w  w .  j  a  va  2s .c  o  m*/

    Boolean result = true;

    // try {
    // // close the Connection
    // long startTime = new Date().getTime();
    // //FTPconnection.logout();
    // log.info("Logout was done in " + (new Date().getTime() - startTime) +
    // " ms.");
    // } catch (IOException ioe) {
    // // log.error(ioe.getMessage(), ioe);
    // result = false;
    // } finally {
    // long startTime = new Date().getTime();
    // try {
    // FTPconnection.disconnect();
    // } catch (IOException ioe) {
    // log.error(ioe.getMessage(), ioe);
    // result = false;
    // }
    // log.info("Disconnection was done in " + (new Date().getTime() -
    // startTime) + " ms.");
    // }

    try {
        // FTPconnection.logout();
        FTPconnection.disconnect();
        log.info("The FTP sub-module disconnected in " + (new Date().getTime() - startTime) + " ms.");
    } catch (IOException ioe) {
        log.error(ioe.getMessage(), ioe);
        result = false;
    }

    return result;
}

From source file:ru.in360.FTPUploader.java

public boolean uploadFolder(File src, URI dest) {
    FTPClient ftpClient = new FTPClient();

    try {/*from  ww w .  j  ava  2s.  c o  m*/
        // connect and login to the server
        ftpClient.connect(server, port);
        ftpClient.login(user, pass);

        // use local passive mode to pass firewall
        ftpClient.enterLocalPassiveMode();

        System.out.println("Connected");

        String remoteDirPath = "/Upload";
        String localDirPath = "E:/winhex";

        FTPUtil.saveFilesToServer(ftpClient, remoteProject, src);

        // log out and disconnect from the server
        ftpClient.logout();
        ftpClient.disconnect();

        System.out.println("Disconnected");
        return true;
    } catch (IOException ex) {
        ex.printStackTrace();
        return false;
    }
}