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:org.blue.star.plugins.check_ftp.java

public boolean execute_check() {
    /* Declare variables */
    FTPClient ftp = new FTPClient();
    File filename = null;/*from  w ww .  j  ava 2  s  . com*/
    FileChannel channel;
    InputStream is;
    OutputStream os;
    int reply;

    if (super.verbose > 0)
        verbose = true;

    /* Configure client to meet our requirements */
    ftp.setDefaultPort(port);
    ftp.setDefaultTimeout(timeout);

    if (verbose) {
        System.out.println("Using FTP Server: " + hostname);
        System.out.println("Using FTP Port: " + port);
        System.out.println("Using Timeout of: " + timeout);
    }

    if (passive) {
        ftp.enterLocalPassiveMode();
        if (verbose)
            System.out.println("Using Passive Mode");
    }

    try {
        filename = new File(file);
        channel = new RandomAccessFile(filename, "rw").getChannel();

        if (verbose)
            System.out.println("Attempting FTP Connection to " + hostname);
        ftp.connect(hostname);
        reply = ftp.getReplyCode();

        /* Test to see if we actually managed to connect */
        if (!FTPReply.isPositiveCompletion(reply)) {
            if (verbose)
                System.out.println("FTP Connection to " + hostname + " failed");
            check_state = common_h.STATE_CRITICAL;
            check_message = ftp.getReplyString();
            filename.delete();
            ftp.disconnect();
            return true;
        }

        /* Try and login if we're using username/password */
        if (username != null && password != null) {
            if (verbose)
                System.out.println("Attempting to log in into FTP Server " + hostname);

            if (!ftp.login(username, password)) {
                if (verbose)
                    System.out.println("Unable to log in to FTP Server " + hostname);
                check_state = common_h.STATE_CRITICAL;
                check_message = ftp.getReplyString();
                ftp.disconnect();
                filename.delete();
                return true;
            }
        }

        if (verbose)
            System.out.println("Attempting to change to required directory");
        /* Try and change to the given directory */
        if (!ftp.changeWorkingDirectory(directory)) {
            if (verbose)
                System.out.println("Required directory cannot be found!");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        if (verbose)
            System.out.println("Attempting to retrieve specified file!");
        /* Try to get Stream on Remote File! */
        is = ftp.retrieveFileStream(file);

        if (is == null) {
            if (verbose)
                System.out.println("Unable to locate required file.");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* OutputStream */
        os = Channels.newOutputStream(channel);

        /* Create the buffer */
        byte[] buf = new byte[4096];

        if (verbose)
            System.out.println("Beginning File transfer...");
        for (int len = -1; (len = is.read(buf)) != -1;)
            os.write(buf, 0, len);

        if (verbose) {
            System.out.println("...transfer complete.");
            System.out.println("Attempting to finalise Command");
        }

        /* Finalise the transfer details */
        if (!ftp.completePendingCommand()) {
            if (verbose)
                System.out.println("Unable to finalise command");
            check_state = common_h.STATE_WARNING;
            check_message = ftp.getReplyString();
            ftp.disconnect();
            filename.delete();
            return true;
        }

        /* Clean up */
        if (verbose)
            System.out.println("Check Completed.");
        check_state = common_h.STATE_OK;
        check_message = ftp.getReplyString();

        /* Close out things */
        is.close();
        os.close();
        channel.close();
        filename.delete();

    } catch (IOException e) {
        check_state = common_h.STATE_CRITICAL;
        check_message = e.getMessage();
        if (filename != null)
            filename.delete();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();

            } catch (Exception e) {
            }
        }
    }

    return true;
}

From source file:org.compiere.model.MMediaServer.java

/**
 *    (Re-)Deploy all media//from  www.  j  a v a2  s.com
 *    @param media array of media to deploy
 *    @return true if deployed
 */
public boolean deploy(MMedia[] media) {
    // Check whether the host is our example localhost, we will not deploy locally, but this is no error
    if (this.getIP_Address().equals("127.0.0.1") || this.getName().equals("localhost")) {
        log.warning("You have not defined your own server, we will not really deploy to localhost!");
        return true;
    }

    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(getIP_Address());
        if (ftp.login(getUserName(), getPassword()))
            log.info("Connected to " + getIP_Address() + " as " + getUserName());
        else {
            log.warning("Could NOT connect to " + getIP_Address() + " as " + getUserName());
            return false;
        }
    } catch (Exception e) {
        log.log(Level.WARNING, "Could NOT connect to " + getIP_Address() + " as " + getUserName(), e);
        return false;
    }

    boolean success = true;
    String cmd = null;
    //   List the files in the directory
    try {
        cmd = "cwd";
        ftp.changeWorkingDirectory(getFolder());
        //
        cmd = "list";
        String[] fileNames = ftp.listNames();
        log.log(Level.FINE, "Number of files in " + getFolder() + ": " + fileNames.length);

        /*
        FTPFile[] files = ftp.listFiles();
        log.config("Number of files in " + getFolder() + ": " + files.length);
        for (int i = 0; i < files.length; i++)
           log.fine(files[i].getTimestamp() + " \t" + files[i].getName());*/
        //
        cmd = "bin";
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
        //
        for (int i = 0; i < media.length; i++) {
            if (!media[i].isSummary()) {
                log.log(Level.INFO, " Deploying Media Item:" + media[i].get_ID() + media[i].getExtension());
                MImage thisImage = media[i].getImage();

                // Open the file and output streams
                byte[] buffer = thisImage.getData();
                ByteArrayInputStream is = new ByteArrayInputStream(buffer);

                String fileName = media[i].get_ID() + media[i].getExtension();
                cmd = "put " + fileName;
                ftp.storeFile(fileName, is);
                is.close();
            }
        }
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
        success = false;
    }
    //   Logout from the FTP Server and disconnect
    try {
        cmd = "logout";
        ftp.logout();
        cmd = "disconnect";
        ftp.disconnect();
    } catch (Exception e) {
        log.log(Level.WARNING, cmd, e);
    }
    ftp = null;
    return success;
}

From source file:org.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * // w  ww  .j  a v a  2 s  . com
 * <p>
 * ??
 * </p>
 * 
 * @author covito
 * @param ftp
 */
protected void close(FTPClient ftp) {
    try {
        ftp.logout();
        if (ftp.isConnected()) {
            ftp.disconnect();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:org.ecoinformatics.datamanager.download.DownloadHandler.java

/**
 * Gets content from given source and writes it to DataStorageInterface 
 * to store them. This method will be called by run()
 * /* w ww. j ava  2s . co  m*/
 * @param resourceName  the URL to the source data to be retrieved
 */
protected boolean getContentFromSource(String resourceName) {
    boolean successFlag = false;
    QualityCheck onlineURLsQualityCheck = null;
    boolean onlineURLsException = false; // used to determine status of onlineURLs quality check

    if (resourceName != null) {
        resourceName = resourceName.trim();
    }

    if (resourceName != null && (resourceName.startsWith("http://") || resourceName.startsWith("https://")
            || resourceName.startsWith("file://") || resourceName.startsWith("ftp://"))) {
        // get the data from a URL
        int responseCode = 0;
        String responseMessage = null;

        try {
            URL url = new URL(resourceName);
            boolean isFTP = false;

            if (entity != null) {
                String contentType = null;

                // Find the right MIME type and set it as content type
                if (resourceName.startsWith("http")) {
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("HEAD");
                    httpURLConnection.connect();
                    contentType = httpURLConnection.getContentType();
                    responseCode = httpURLConnection.getResponseCode();
                    responseMessage = httpURLConnection.getResponseMessage();
                } else if (resourceName.startsWith("file")) {
                    URLConnection urlConnection = url.openConnection();
                    urlConnection.connect();
                    contentType = urlConnection.getContentType();
                } else { // FTP
                    isFTP = true;
                    contentType = "application/octet-stream";
                }

                entity.setUrlContentType(contentType);
            }

            if (!isFTP) { // HTTP(S) or FILE
                InputStream filestream = url.openStream();

                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    filestream.close();
                }
            } else { // FTP
                String[] urlParts = resourceName.split("/");
                String address = urlParts[2];
                String dir = "/";
                for (int i = 3; i < urlParts.length - 1; i++) {
                    dir += urlParts[i] + "/";
                }
                String fileName = urlParts[urlParts.length - 1];
                FTPClient ftpClient = new FTPClient();
                ftpClient.connect(address);
                ftpClient.login(ANONYMOUS, anonymousFtpPasswd);
                ftpClient.changeWorkingDirectory(dir);
                ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                ftpClient.enterLocalPassiveMode(); // necessary to avoid firewall blocking
                InputStream filestream = ftpClient.retrieveFileStream(fileName);
                try {
                    successFlag = this.writeRemoteInputStreamIntoDataStorage(filestream);
                } catch (IOException e) {
                    exception = e;
                    String errorMessage = e.getMessage();
                    if (errorMessage.startsWith(ONLINE_URLS_EXCEPTION_MESSAGE)) {
                        onlineURLsException = true;
                    }
                } finally {
                    try {
                        filestream.close();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(String
                                .format("Error closing local file '%s': %s", resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }

                // logout and disconnect if FTP session
                if (resourceName.startsWith("ftp") && ftpClient != null) {
                    try {
                        ftpClient.enterLocalActiveMode();
                        ftpClient.logout();
                        ftpClient.disconnect();
                    } catch (IOException e) {
                        exception = new DataSourceNotFoundException(
                                String.format("Error disconnecting from FTP with resource '%s': %s",
                                        resourceName, e.getMessage()));
                        onlineURLsException = true;
                    }
                }
            }
        } catch (MalformedURLException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is a malformed URL: %s", resourceName, eMessage));
        } catch (IOException e) {
            String eClassName = e.getClass().getName();
            String eMessage = String.format("%s: %s", eClassName, e.getMessage());
            if (responseCode > 0) {
                eMessage = String.format("Response Code: %d %s; %s", responseCode, responseMessage, eMessage);
            }
            exception = new DataSourceNotFoundException(
                    String.format("The URL '%s' is not reachable: %s", resourceName, eMessage));
        }

        // Initialize the "Online URLs are live" quality check
        String qualityCheckIdentifier = "onlineURLs";
        QualityCheck qualityCheckTemplate = QualityReport.getQualityCheckTemplate(qualityCheckIdentifier);
        onlineURLsQualityCheck = new QualityCheck(qualityCheckIdentifier, qualityCheckTemplate);

        if (QualityCheck.shouldRunQualityCheck(entity, onlineURLsQualityCheck)) {
            String resourceNameEscaped = embedInCDATA(resourceName);

            if (!onlineURLsException) {
                onlineURLsQualityCheck.setStatus(Status.valid);
                onlineURLsQualityCheck.setFound("true");
                onlineURLsQualityCheck.setExplanation("Succeeded in accessing URL: " + resourceNameEscaped);
            } else {
                onlineURLsQualityCheck.setFailedStatus();
                onlineURLsQualityCheck.setFound("false");
                String explanation = "Failed to access URL: " + resourceNameEscaped;
                explanation = explanation + "; " + embedInCDATA(exception.getMessage());
                onlineURLsQualityCheck.setExplanation(explanation);
            }

            entity.addQualityCheck(onlineURLsQualityCheck);
        }

        return successFlag;
    } else if (resourceName != null && resourceName.startsWith("ecogrid://")) {
        // get the docid from url
        int start = resourceName.indexOf("/", 11) + 1;
        //log.debug("start: " + start);
        int end = resourceName.indexOf("/", start);

        if (end == -1) {
            end = resourceName.length();
        }

        //log.debug("end: " + end);
        String ecogridIdentifier = resourceName.substring(start, end);
        // pass this docid and get data item
        //System.out.println("the endpoint is "+ECOGRIDENDPOINT);
        //System.out.println("The identifier is "+ecogridIdentifier);
        //return false;
        return getContentFromEcoGridSource(ecogridEndPoint, ecogridIdentifier);
    } else if (resourceName != null && resourceName.startsWith("srb://")) {
        // get srb docid from the url
        String srbIdentifier = transformSRBurlToDocid(resourceName);
        // reset endpoint for srb (This is hack we need to figure ou
        // elegent way to do this
        //mEndPoint = Config.getValue("//ecogridService/srb/endPoint");
        // pass this docid and get data item
        //log.debug("before get srb data");
        return getContentFromEcoGridSource(SRBENDPOINT, srbIdentifier);
    } else {
        successFlag = false;
        return successFlag;
    }
}

From source file:org.glassfish.common.util.admin.MapInjectionResolver.java

private void FormatUriToFile() throws IOException {
    List<String> value = parameters.get("DEFAULT");
    String uri = value.get(0);/*from www .ja  v  a 2  s .  com*/
    URL url = new URL(uri);
    File file = null;

    if (uri.startsWith("file:/")) {
        file = new File(url.getFile());
    } else if (uri.startsWith("http://")) {
        InputStream inStream = url.openStream();
        BufferedInputStream bufIn = new BufferedInputStream(inStream);

        file = new File(System.getenv().get("TEMP") + uri.substring(uri.lastIndexOf("/")));
        if (file.exists()) {
            file.delete();
        }
        OutputStream out = new FileOutputStream(file);
        BufferedOutputStream bufOut = new BufferedOutputStream(out);
        byte buffer[] = new byte[204800];
        while (true) {
            int nRead = bufIn.read(buffer, 0, buffer.length);
            if (nRead <= 0)
                break;
            bufOut.write(buffer, 0, nRead);
        }
        bufOut.flush();
        out.close();
        inStream.close();
    } else if (uri.startsWith("ftp://")) {
        String pattern = "^ftp://(.+?)(:.+?)?@(\\S+):(\\d+)(\\S+)$";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(uri);
        if (m.matches()) {
            String username = m.group(1);
            String password = "";
            if (m.group(2) != null) {
                password = m.group(2).replace(":", "");
            }
            String ipAddress = m.group(3);
            String port = m.group(4);
            String path = m.group(5);
            FTPClient ftp = new FTPClient();
            ftp.connect(ipAddress);
            ftp.setDefaultPort(Integer.parseInt(port));
            boolean isLogin = ftp.login(username, password);
            if (isLogin) {
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
                byte[] buf = new byte[204800];
                int bufsize = 0;

                file = new File(System.getenv().get("TEMP") + uri.substring(uri.lastIndexOf("/")));
                if (file.exists()) {
                    file.delete();
                }
                OutputStream ftpOut = new FileOutputStream(file);
                InputStream ftpIn = ftp.retrieveFileStream(path);
                System.out.println(ftpIn);
                while ((bufsize = ftpIn.read(buf, 0, buf.length)) != -1) {
                    ftpOut.write(buf, 0, bufsize);
                }
                ftpOut.flush();
                ftpOut.close();
                ftpIn.close();
            } else {
                ftp.logout();
                ftp.disconnect();
            }
        } else {
            localStrings.getLocalString("IncorrectFtpAddress",
                    "The ftp address is not correct, please change another one.");
        }
    }
    if (file != null)
        parameters.set("DEFAULT", file.getAbsolutePath());
}

From source file:org.gogpsproject.parser.rinex.RinexNavigation.java

private RinexNavigationParser getFromFTP(String url) throws IOException {
    RinexNavigationParser rnp = null;//from www .ja  v  a2  s . c  o m

    String origurl = url;
    if (negativeChache.containsKey(url)) {
        if (System.currentTimeMillis() - negativeChache.get(url).getTime() < 60 * 60 * 1000) {
            throw new FileNotFoundException("cached answer");
        } else {
            negativeChache.remove(url);
        }
    }

    String filename = url.replaceAll("[ ,/:]", "_");
    if (filename.endsWith(".Z"))
        filename = filename.substring(0, filename.length() - 2);
    File rnf = new File(RNP_CACHE, filename);

    if (!rnf.exists()) {
        System.out.println(url + " from the net.");
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            System.out.println("URL: " + url);
            url = url.substring("ftp://".length());
            String server = url.substring(0, url.indexOf('/'));
            String remoteFile = url.substring(url.indexOf('/'));
            String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/'));
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1);

            ftp.connect(server);
            ftp.login("anonymous", "info@eriadne.org");

            System.out.print(ftp.getReplyString());

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

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                return null;
            }

            System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath));
            System.out.println(ftp.getReplyString());
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.println(ftp.getReplyString());

            System.out.println("open " + remoteFile);
            InputStream is = ftp.retrieveFileStream(remoteFile);
            InputStream uis = is;
            System.out.println(ftp.getReplyString());
            if (ftp.getReplyString().startsWith("550")) {
                negativeChache.put(origurl, new Date());
                throw new FileNotFoundException();
            }

            if (remoteFile.endsWith(".Z")) {
                uis = new UncompressInputStream(is);
            }

            rnp = new RinexNavigationParser(uis, rnf);
            rnp.init();
            is.close();

            ftp.completePendingCommand();

            ftp.logout();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    // do nothing
                }
            }
        }
    } else {
        System.out.println(url + " from cache file " + rnf);
        rnp = new RinexNavigationParser(rnf);
        rnp.init();
    }
    return rnp;
}

From source file:org.gogpsproject.parser.sp3.SP3Navigation.java

private SP3Parser getFromFTP(String url) throws IOException {
    SP3Parser sp3p = null;/*from w  w  w .j a  v a 2  s  . c o  m*/

    String filename = url.replaceAll("[ ,/:]", "_");
    if (filename.endsWith(".Z"))
        filename = filename.substring(0, filename.length() - 2);
    File sp3f = new File(SP3_CACHE, filename);

    if (!sp3f.exists()) {
        System.out.println(url + " from the net.");
        FTPClient ftp = new FTPClient();

        try {
            int reply;
            System.out.println("URL: " + url);
            url = url.substring("ftp://".length());
            String server = url.substring(0, url.indexOf('/'));
            String remoteFile = url.substring(url.indexOf('/'));
            String remotePath = remoteFile.substring(0, remoteFile.lastIndexOf('/'));
            remoteFile = remoteFile.substring(remoteFile.lastIndexOf('/') + 1);

            ftp.connect(server);
            ftp.login("anonymous", "info@eriadne.org");

            System.out.print(ftp.getReplyString());

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

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                System.err.println("FTP server refused connection.");
                return null;
            }

            System.out.println("cwd to " + remotePath + " " + ftp.changeWorkingDirectory(remotePath));
            System.out.println(ftp.getReplyString());
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            System.out.println(ftp.getReplyString());

            System.out.println("open " + remoteFile);
            InputStream is = ftp.retrieveFileStream(remoteFile);
            InputStream uis = is;
            System.out.println(ftp.getReplyString());
            if (ftp.getReplyString().startsWith("550")) {
                throw new FileNotFoundException();
            }

            if (remoteFile.endsWith(".Z")) {
                uis = new UncompressInputStream(is);
            }

            sp3p = new SP3Parser(uis, sp3f);
            sp3p.init();
            is.close();

            ftp.completePendingCommand();

            ftp.logout();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                    // do nothing
                }
            }
        }
    } else {
        System.out.println(url + " from cache file " + sp3f);
        sp3p = new SP3Parser(sp3f);
        sp3p.init();
    }
    return sp3p;
}

From source file:org.grouter.core.readers.FtpReaderJob.java

@Override
protected List<CommandMessage> readFromSource() {
    logger.info("Reading files from :" + node.getInBound().getUri());

    // a list of full paths on ftp server we will download from
    Map endPointContext = node.getInBound().getEndPointContext();

    List<String> remoteFtpUriToFile = getPathIncludingFile((String) endPointContext.get(FILE_LIST));
    List<CommandMessage> commandMessages = new ArrayList<CommandMessage>();
    FTPClient client = null;
    try {/*from www.  j  a  v a 2 s. c o  m*/
        client = initConnection();
        for (String fullPathToFile : remoteFtpUriToFile) {
            // should only return one file - since we are using a complete file uri and not a uri to a folder
            FTPFile[] ftpFilesAtPath = client.listFiles(fullPathToFile);
            if (ftpFilesAtPath.length > 0) {
                //String localFileName = fullPathToFile;
                File internalInFile = new File(node.getRouter().getHomePath() + File.separator + "nodes"
                        + File.separator + node.getId() + File.separator + "internal" + File.separator + "in"
                        + File.separator + fullPathToFile.replace("/", "_"));
                FileOutputStream fos = new FileOutputStream(internalInFile);
                logger.info("Downloading file from ftp server:" + fullPathToFile);
                // we have a valid fullPathToFile and there is a file at that fullPathToFile
                boolean status = client.retrieveFile(fullPathToFile, fos);
                if (status) {
                    logger.info("Downloading complete :" + internalInFile);
                    internalInFile.setLastModified(ftpFilesAtPath[0].getTimestamp().getTimeInMillis());

                    // Get part of the message to store for querying purposes
                    String message = getMessage(internalInFile);
                    CommandMessage cmdMessage = new CommandMessage(message, internalInFile);
                    commandMessages.add(cmdMessage);
                } else {
                    logger.error("Failed to download remote file :" + fullPathToFile + " Status code received :"
                            + status);
                }
                fos.close();
            }
        }
    } catch (Exception e) {
        // TODO We need to reset state if we start working again
        node.setNodeStatus(NodeStatus.ERROR);
        node.setStatusMessage(
                "Failed reading files from :" + node.getInBound().getUri() + " Error:" + e.getMessage());
        logStrategy.log(node);
        logger.warn("Connection problem with FTP server.", e);
    } finally {
        if (client != null) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException e) {
                //ignore
            }
        }
    }
    return commandMessages;
}

From source file:org.jason.mapmaker.server.service.ShapefileMetadataServiceImpl.java

private List<String> getRemoteFilenames(String url, String directory) {

    FTPClient ftp = new FTPClient();
    List<String> filenameList = new ArrayList<String>();

    try {//from  ww  w. ja v a 2  s  . c om
        int reply;
        ftp.connect(url);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            System.out.println("FTP connection failed for " + url);
        }
        ftp.enterLocalPassiveMode();
        ftp.login("anonymous", "");
        FTPFile[] files = ftp.listFiles(directory);
        for (FTPFile f : files) {
            filenameList.add(f.getName());
        }

        ftp.logout();

    } catch (IOException ex) {

        ex.printStackTrace();
    }

    return filenameList;
}

From source file:org.jboss.ejb3.examples.ch06.filetransfer.FileTransferBean.java

/**
 * Called by the container when the instance is about to be passivated or brought
 * out of service entirely./*from w  ww  .  j av a  2s  .  c o m*/
 *
 * @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferCommonBusiness#disconnect()
 */
@PrePassivate
@PreDestroy
@Override
public void disconnect() {
    // Obtain FTP Client
    final FTPClient client = this.getClient();

    // If exists
    if (client != null) {
        // If connected
        if (client.isConnected()) {
            // Logout
            try {
                client.logout();
                log.info("Logged out of: " + client);
            } catch (final IOException ioe) {
                log.warning("Exception encountered in logging out of the FTP client: " + ioe.getMessage());
            }

            // Disconnect
            try {
                log.fine("Disconnecting: " + client);
                client.disconnect();
                log.info("Disconnected: " + client);
            } catch (final IOException ioe) {
                log.warning("Exception encountered in disconnecting the FTP client: " + ioe.getMessage());
            }

            // Null out the client so it's not serialized
            this.client = null;
        }
    }
}