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

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

Introduction

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

Prototype

public boolean isConnected() 

Source Link

Document

Returns true if the client is currently connected to a server.

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 w w . j  a v  a2  s . c o  m*/
    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.covito.kit.file.support.FtpFileServiceImpl.java

/**
 * /*from   ww  w.j a v  a 2  s . c o  m*/
 * <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.eclipse.datatools.connectivity.sample.ftp.internal.FtpContentProvider.java

public Object[] getChildren(Object parent) {
    try {//from  ww  w .j  av a  2s.c o  m
        if (parent instanceof FTPClientObject) {
            FTPClient ftpClient = ((FTPClientObject) parent).getFtpClient();
            if (ftpClient.isConnected()) {
                FTPListParseEngine engine = ftpClient.initiateListParsing();
                FTPFile[] files = engine.getFiles();
                return FTPFileObject.convert(parent, ((FTPClientObject) parent).getProfile(), files);
            }
        } else if (parent instanceof FTPFileObject) {
            FTPFile ftpFile = ((FTPFileObject) parent).getFTPFile();
            FTPClient ftpClient = getFTPClient(parent);
            if (ftpFile.isDirectory() && ftpClient.isConnected()) {
                FTPListParseEngine engine = ftpClient.initiateListParsing(getDirectory((FTPFileObject) parent));
                FTPFile[] files = engine.getFiles();
                return FTPFileObject.convert(parent, ((FTPFileObject) parent).getProfile(), files);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        FTPClient ftpClient = getFTPClient(parent);
        try {
            if (ftpClient != null)
                ftpClient.disconnect();
        } catch (Exception ex) {
        }
    }
    return new Object[0];
}

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

private RinexNavigationParser getFromFTP(String url) throws IOException {
    RinexNavigationParser rnp = null;//from   ww  w.  j  a v  a  2  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 ww.  ja  v  a2 s .  com

    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.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  ww w.jav  a  2 s. c  om
 *
 * @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;
        }
    }
}

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

/**
 * Called by the container when the instance has been created or re-activated
 * (brought out of passivated state).  Will construct the underlying FTP Client
 * and open all appropriate connections.
 *
 * @see org.jboss.ejb3.examples.ch06.filetransfer.FileTransferCommonBusiness#connect()
 *///from w  ww . j a v a 2 s  . co  m
@PostConstruct
@PostActivate
@Override
public void connect() throws IllegalStateException, FileTransferException {
    /*
     * Precondition checks
     */
    final FTPClient clientBefore = this.getClient();
    if (clientBefore != null && clientBefore.isConnected()) {
        throw new IllegalStateException("FTP Client is already initialized");
    }

    // Get the connection properties
    final String connectHost = this.getConnectHost();
    final int connectPort = this.getConnectPort();

    // Create the client
    final FTPClient client = new FTPClient();
    final String canonicalServerName = connectHost + ":" + connectPort;
    log.fine("Connecting to FTP Server at " + canonicalServerName);
    try {
        client.connect(connectHost, connectPort);
    } catch (final IOException ioe) {
        throw new FileTransferException("Error in connecting to " + canonicalServerName, ioe);
    }

    // Set
    log.info("Connected to FTP Server at: " + canonicalServerName);
    this.setClient(client);

    // Check that the last operation succeeded
    this.checkLastOperation();

    try {
        // Login
        client.login("user", "password");

        // Check that the last operation succeeded
        this.checkLastOperation();
    } catch (final Exception e) {
        throw new FileTransferException("Could not log in", e);
    }

    // If there's a pwd defined, cd into it.
    final String pwd = this.getPresentWorkingDirectory();
    if (pwd != null) {
        this.cd(pwd);
    }

}

From source file:org.kuali.kfs.module.cg.service.impl.CfdaServiceImpl.java

/**
 * @return//from ww w  .java2  s .c o  m
 * @throws IOException
 */
public SortedMap<String, CFDA> getGovCodes() throws IOException {
    Calendar calendar = dateTimeService.getCurrentCalendar();
    SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>();

    // ftp://ftp.cfda.gov/programs09187.csv
    String govURL = parameterService.getParameterValueAsString(CfdaBatchStep.class,
            KFSConstants.SOURCE_URL_PARAMETER);
    String fileName = StringUtils.substringAfterLast(govURL, "/");
    govURL = StringUtils.substringBeforeLast(govURL, "/");
    if (StringUtils.contains(govURL, "ftp://")) {
        govURL = StringUtils.remove(govURL, "ftp://");
    }

    // need to pull off the '20' in 2009
    String year = "" + calendar.get(Calendar.YEAR);
    year = year.substring(2, 4);
    fileName = fileName + year;

    // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday"
    fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1);
    fileName = fileName + ".csv";

    LOG.info("Getting government file: " + fileName + " for update");

    InputStream inputStream = null;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(govURL);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            LOG.error("FTP connection to server not established.");
            throw new IOException("FTP connection to server not established.");
        }

        boolean isLoggedIn = ftp.login("anonymous", "");
        if (!isLoggedIn) {
            LOG.error("Could not login as anonymous.");
            throw new IOException("Could not login as anonymous.");
        }

        LOG.info("Successfully connected and logged in");
        ftp.enterLocalPassiveMode();
        inputStream = ftp.retrieveFileStream(fileName);
        if (inputStream != null) {
            LOG.info("reading input stream");
            InputStreamReader screenReader = new InputStreamReader(inputStream);
            BufferedReader screen = new BufferedReader(screenReader);

            CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1);
            List<String[]> lines = csvReader.readAll();
            for (String[] line : lines) {
                String title = line[0];
                String number = line[1];

                CFDA cfda = new CFDA();
                cfda.setCfdaNumber(number);
                cfda.setCfdaProgramTitleName(title);

                govMap.put(number, cfda);
            }
        }

        ftp.logout();
        ftp.disconnect();
    } finally {
        if (ftp.isConnected()) {
            ftp.disconnect();
        }
    }

    return govMap;
}

From source file:org.kuali.kra.external.Cfda.service.impl.CfdaServiceImpl.java

/**
 * This method disconnects from server.//w ww .  j ava2 s. c  om
 * @param ftp
 * @throws IOException
 */
public void disconnect(FTPClient ftp) throws IOException {
    ftp.logout();
    if (ftp.isConnected()) {
        ftp.disconnect();
    }
}

From source file:org.kuali.ole.coa.service.impl.CfdaServiceImpl.java

/**
 * @return/*from w  w  w. j a  v  a 2s .  com*/
 * @throws IOException
 */
public SortedMap<String, CFDA> getGovCodes() throws IOException {
    Calendar calendar = SpringContext.getBean(DateTimeService.class).getCurrentCalendar();
    SortedMap<String, CFDA> govMap = new TreeMap<String, CFDA>();

    // ftp://ftp.cfda.gov/programs09187.csv
    String govURL = SpringContext.getBean(ParameterService.class).getParameterValueAsString(CfdaBatchStep.class,
            OLEConstants.SOURCE_URL_PARAMETER);
    String fileName = StringUtils.substringAfterLast(govURL, "/");
    govURL = StringUtils.substringBeforeLast(govURL, "/");
    if (StringUtils.contains(govURL, "ftp://")) {
        govURL = StringUtils.remove(govURL, "ftp://");
    }

    // need to pull off the '20' in 2009
    String year = "" + calendar.get(Calendar.YEAR);
    year = year.substring(2, 4);
    fileName = fileName + year;

    // the last 3 numbers in the file name are the day of the year, but the files are from "yesterday"
    fileName = fileName + String.format("%03d", calendar.get(Calendar.DAY_OF_YEAR) - 1);
    fileName = fileName + ".csv";

    LOG.info("Getting government file: " + fileName + " for update");

    InputStream inputStream = null;
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(govURL);
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            LOG.error("FTP connection to server not established.");
            throw new IOException("FTP connection to server not established.");
        }

        boolean loggedIn = ftp.login("anonymous", "");
        if (!loggedIn) {
            LOG.error("Could not login as anonymous.");
            throw new IOException("Could not login as anonymous.");
        }

        LOG.info("Successfully connected and logged in");
        ftp.enterLocalPassiveMode();
        inputStream = ftp.retrieveFileStream(fileName);
        if (inputStream != null) {
            LOG.info("reading input stream");
            InputStreamReader screenReader = new InputStreamReader(inputStream);
            BufferedReader screen = new BufferedReader(screenReader);

            CSVReader csvReader = new CSVReader(screenReader, ',', '"', 1);
            List<String[]> lines = csvReader.readAll();
            for (String[] line : lines) {
                String title = line[0];
                String number = line[1];

                CFDA cfda = new CFDA();
                cfda.setCfdaNumber(number);
                cfda.setCfdaProgramTitleName(title);

                govMap.put(number, cfda);
            }
        }

        ftp.logout();
        ftp.disconnect();
    } finally {
        if (ftp.isConnected()) {
            ftp.disconnect();
        }
    }

    return govMap;
}