Example usage for org.apache.commons.net.ftp FTPClient logout

List of usage examples for org.apache.commons.net.ftp FTPClient logout

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient logout.

Prototype

public boolean logout() throws IOException 

Source Link

Document

Logout of the FTP server by sending the QUIT command.

Usage

From source file:com.hackengine_er.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {//from  w  w  w . j  ava  2 s.  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 {/*ww w  .  j  a v  a  2s . 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:convcao.com.agent.ConvcaoNeptusInteraction.java

private void upload(String ftpServer, String pathDirectory, String sourcePathDirectory, String userName,
        String password, String filename) {

    FTPClient client = new FTPClient();
    FileInputStream fis = null;/*w w  w  .  j  av a2 s  . co  m*/

    try {
        client.connect(ftpServer);
        client.login(userName, password);
        client.enterLocalPassiveMode();
        client.setFileType(FTP.BINARY_FILE_TYPE);
        fis = new FileInputStream(sourcePathDirectory + filename);
        client.changeWorkingDirectory("/" + pathDirectory);

        client.storeFile(filename, fis);

        System.out.println(
                "The file " + sourcePathDirectory + " was stored to " + "/" + pathDirectory + "/" + filename);
        client.logout();

        //Report = "File: " + filename + " Uploaded Successfully ";
    } catch (Exception exp) {
        exp.printStackTrace();
        report = "Server Error";
        jLabel6.setText(report);
    } finally {
        try {
            if (fis != null) {
                fis.close();
            }
            client.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:main.TestManager.java

/**
 * Deletes all local tests, downloads tests from the server
 * and saves all downloaded test in the local directory.
 *///from  ww w. j av a 2s .c o m
public static void syncTestsWithServer() {
    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 test to be replaced with 
        // actulized version
        File[] locals = new File("src/tests/").listFiles();
        for (File f : locals) {
            if (f.getName() == "." || f.getName() == "..") {
                continue;
            }
            f.delete();
        }
        // Copy the files from server to local folder
        int failed = 0;
        for (FTPFile f : files) {
            if (f.isFile()) {
                Debugger.println(f.getName());
                if (f.getName() == "." || f.getName() == "..") {
                    continue;
                }
                File file = new File("src/tests/" + f.getName());
                file.createNewFile();
                OutputStream output = new FileOutputStream(file);
                if (!ftp.retrieveFile(f.getName(), output))
                    failed++;
                output.close();
            }
        }
        // If we failed to download 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();

    }
    Alert alert = new Alert(AlertType.INFORMATION);
    alert.setTitle("Download hotov");
    alert.setHeaderText(null);
    alert.setContentText("Vetky testy boli zo servru spene stiahnut.");

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

From source file:com.maxl.java.amikodesk.Emailer.java

private void uploadToFTPServer(Author author, String name, String path) {
    FTPClient ftp_client = new FTPClient();
    try {//www  . ja  v a  2  s  .c o  m
        ftp_client.connect(author.getS(), 21);
        ftp_client.login(author.getL(), author.getP());
        ftp_client.enterLocalPassiveMode();
        ftp_client.changeWorkingDirectory(author.getO());
        ftp_client.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftp_client.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp_client.disconnect();
            System.err.println("FTP server refused connection.");
            return;
        }

        File local_file = new File(path);
        String remote_file = name + ".csv";
        InputStream is = new FileInputStream(local_file);
        System.out.print("Uploading file " + name + " to server " + author.getS() + "... ");

        boolean done = ftp_client.storeFile(remote_file, is);
        if (done)
            System.out.println("file uploaded successfully.");
        else
            System.out.println("error.");
        is.close();
    } catch (IOException ex) {
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftp_client.isConnected()) {
                ftp_client.logout();
                ftp_client.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:egovframework.com.ext.jfile.sample.SampleFileUploadCluster.java

public void uploadCompleted(String fileId, String sourceRepositoryPath, String maskingFileName,
        String originalFileName) {
    if (logger.isDebugEnabled()) {
        logger.debug("SampleUploadCluster.process called");
    }/*from   w ww  .j a  va  2 s  .co  m*/
    FTPClient ftp = new FTPClient();
    OutputStream out = null;
    File file = new File(sourceRepositoryPath + "/" + maskingFileName);
    FileInputStream fin = null;
    BufferedInputStream bin = null;
    String storeFileName = null;
    String server = "?IP";//??  ? . ex) 210.25.3.21
    try {
        ftp.connect(server);
        if (FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
            ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
            storeFileName = maskingFileName
                    + originalFileName.substring(originalFileName.lastIndexOf("."), originalFileName.length());
            fin = new FileInputStream(file);
            bin = new BufferedInputStream(fin);
            ftp.login("testId",
                    "testPassword" + server.substring(server.lastIndexOf(".") + 1, server.length()));
            if (logger.isDebugEnabled()) {
                logger.debug(server + " connect success !!! ");
            }
            ftp.changeWorkingDirectory("/testdir1/testsubdir2/testupload/");
            out = ftp.storeFileStream(storeFileName);
            FileCopyUtils.copy(fin, out);
            if (logger.isDebugEnabled()) {
                logger.debug(" cluster success !!! ");
            }
        } else {
            ftp.disconnect();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null)
                out.close();
            if (bin != null)
                bin.close();
            ftp.logout();
            out = null;
            bin = null;
        } catch (Exception e2) {
            e2.printStackTrace();
        }
    }
}

From source file:main.TestManager.java

/**
 * Deletes all files on the server and uploads all the
 * tests from the local directory.//from ww w .ja  v  a2s.c o m
 */
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:com.jmeter.alfresco.utils.FtpUtils.java

/**
 * Upload directory or file.//from w w w  .  j  a v  a2 s.  c o m
 *
 * @param host the host
 * @param port the port
 * @param userName the user name
 * @param password the password
 * @param fromLocalDirOrFile the local dir
 * @param toRemoteDirOrFile the remote dir
 * @return the string
 * @throws IOException Signals that an I/O exception has occurred.
 */
public String uploadDirectoryOrFile(final String host, final int port, final String userName,
        final String password, final String fromLocalDirOrFile, final String toRemoteDirOrFile)
        throws IOException {

    final FTPClient ftpClient = new FTPClient();
    String responseMessage = Constants.EMPTY;
    try {
        // Connect and login to get the session
        ftpClient.connect(host, port);
        final int replyCode = ftpClient.getReplyCode();

        if (FTPReply.isPositiveCompletion(replyCode)) {
            final boolean loginSuccess = ftpClient.login(userName, password);
            if (loginSuccess) {
                LOG.debug("Connected to remote host!");
                //Use local passive mode to pass fire-wall
                //In this mode a data connection is made by opening a port on the server for the client to connect 
                //and this is not blocked by fire-wall.
                ftpClient.enterLocalPassiveMode();
                final File localDirOrFileObj = new File(fromLocalDirOrFile);
                if (localDirOrFileObj.isFile()) {
                    LOG.debug("Uploading file: " + fromLocalDirOrFile);
                    uploadFile(ftpClient, fromLocalDirOrFile,
                            toRemoteDirOrFile + FILE_SEPERATOR_LINUX + localDirOrFileObj.getName());
                } else {
                    uploadDirectory(ftpClient, toRemoteDirOrFile, fromLocalDirOrFile, EMPTY);
                }
                responseMessage = "Upload completed successfully!";
            } else {
                responseMessage = "Could not login to the remote host!";
            }
            //Log out and disconnect from the server once FTP operation is completed.
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.logout();
                } catch (IOException ignored) {
                    LOG.error("Ignoring the exception while logging out from remote host: ", ignored);
                }
                try {
                    ftpClient.disconnect();
                    LOG.debug("Disconnected from remote host!");
                } catch (IOException ignored) {
                    LOG.error("Ignoring the exception while disconnecting from remote host: ", ignored);
                }
            }
        } else {
            responseMessage = "Host connection failed!";
        }
        LOG.debug("ResponseMessage:=> " + responseMessage);
    } catch (IOException ioexcp) {
        LOG.error("IOException occured in uploadDirectoryOrFile(..): ", ioexcp);
        throw ioexcp;
    }
    return responseMessage;
}

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

public void readFilesFromServer(String targetDirectory) {
    FTPClient ftpClient = new FTPClient();
    try {// w  w w.  j a  va  2  s. c o  m

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

From source file:madkitgroupextension.export.Export.java

private static void sendToWebSite() throws IOException {
    System.out.println("Enter your password :");
    byte b[] = new byte[100];
    int l = System.in.read(b);
    String pwd = new String(b, 0, l);

    boolean reconnect = true;
    long time = System.currentTimeMillis();
    File current_file_transfert = null;
    File current_directory_transfert = null;

    while (reconnect) {
        FTPClient ftpClient = new FTPClient();
        ftpClient.connect(FTPURL, 21);//from  w ww  . ja v a2  s  .c  o m
        try {
            if (ftpClient.isConnected()) {
                System.out.println("Connected to server " + FTPURL + " (Port: " + FTPPORT + ") !");
                if (ftpClient.login(FTPLOGIN, pwd)) {
                    ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
                    System.out.println("Logged as " + FTPLOGIN + " !");
                    System.out.print("Updating...");

                    FTPFile files[] = ftpClient.listFiles("");
                    FTPFile downloadroot = null;
                    FTPFile docroot = null;

                    for (FTPFile f : files) {
                        if (f.getName().equals("downloads")) {
                            downloadroot = f;
                            if (docroot != null)
                                break;
                        }
                        if (f.getName().equals("doc")) {
                            docroot = f;
                            if (downloadroot != null)
                                break;
                        }
                    }
                    if (downloadroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("downloads")) {
                            System.err.println("Impossible to create directory: downloads");
                        }
                    }
                    if (docroot == null) {
                        //ftpClient.changeWorkingDirectory("/");
                        if (!ftpClient.makeDirectory("doc")) {
                            System.err.println("Impossible to create directory: doc");
                        }
                    }

                    updateFTP(ftpClient, "downloads/", new File(ExportPathFinal), current_file_transfert,
                            current_directory_transfert);
                    updateFTP(ftpClient, "doc/", new File("./doc"), current_file_transfert,
                            current_directory_transfert);
                    reconnect = false;

                    System.out.println("[OK]");
                    if (ftpClient.logout()) {
                        System.out.println("Logged out from " + FTPLOGIN + " succesfull !");
                    } else
                        System.err.println("Logged out from " + FTPLOGIN + " FAILED !");
                } else
                    System.err.println("Impossible to log as " + FTPLOGIN + " !");

                ftpClient.disconnect();
                System.out.println("Disconnected from " + FTPURL + " !");
            } else {
                System.err.println("Impossible to get a connection to the server " + FTPURL + " !");
            }
            reconnect = false;
        } catch (TransfertException e) {
            if (System.currentTimeMillis() - time > 30000) {
                System.err.println("A problem occured during the transfert...");
                System.out.println("Reconnection in progress...");
                try {
                    ftpClient.disconnect();
                } catch (Exception e2) {
                }
                current_file_transfert = e.current_file_transfert;
                current_directory_transfert = e.current_directory_transfert;
                time = System.currentTimeMillis();
            } else {
                System.err.println("A problem occured during the transfert. Transfert aborded.");
                throw e.original_exception;
            }
        }
    }
}