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.jnode.protocol.ftp.FTPURLConnection.java

/**
 * @see java.net.URLConnection#getInputStream()
 *///from   ww  w  .j  a v a 2 s . com
public InputStream getInputStream() throws IOException {
    FTPClient client = new FTPClient();
    client.connect(host);
    String replyString = client.getReplyString();
    int replyCode = client.getReplyCode();
    if (!FTPReply.isPositiveCompletion(replyCode)) {
        client.disconnect();
        throw new IOException(replyString);
    }
    if (!client.login(username, password)) {
        replyString = client.getReplyString();
        client.logout();
        throw new IOException(replyString);
    }
    client.setFileType(FTP.BINARY_FILE_TYPE);
    client.enterLocalPassiveMode();

    final ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        client.retrieveFile(path, os);
        client.logout();
    } finally {
        client.disconnect();
    }
    return new ByteArrayInputStream(os.toByteArray());
}

From source file:org.jumpmind.metl.core.runtime.resource.FtpDirectory.java

protected void close(FTPClient ftpClient) {
    if (ftpClient != null) {
        try {//from   www .  j  a  va2s .  c  o m
            ftpClient.logout();
        } catch (IOException e) {
        }

        try {
            ftpClient.disconnect();
        } catch (IOException e) {
        }
    }
}

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

/**
 * @return//from   ww w. jav  a2  s.  co  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./*from   www.  ja  v  a  2  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/*  www. ja  va  2 s.  c o m*/
 * @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;
}

From source file:org.kuali.ole.module.purap.transmission.service.impl.TransmissionServiceImpl.java

/**
 * This method is to perform file upload
 *
 * @param ftpHostname//from  w  w  w.j a va 2  s . c o  m
 * @param ftpUsername
 * @param ftpPassword
 * @param file
 * @param fileName
 */
@Override
public void doFTPUpload(String ftpHostname, String ftpUsername, String ftpPassword, String file,
        String fileName) {
    LOG.trace("************************************doFTPUpload() started************************************");
    FTPClient ftpClient = new FTPClient();
    FileInputStream inputStream = null;
    FileOutputStream outputStream = null;
    try {
        ftpClient.connect(ftpHostname);
        ftpClient.login(ftpUsername, ftpPassword);
        ftpClient.enterLocalPassiveMode();
        int reply = ftpClient.getReplyCode();
        if (FTPReply.isPositiveCompletion(reply)) {
            LOG.debug("Connected to FTP server.");
        } else {
            LOG.debug("FTP server refused connection.");
        }

        // upload
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        String fileLocation = getFileLocation();
        if (LOG.isDebugEnabled()) {
            LOG.debug("File Location in FTP Server================>" + fileLocation);
            LOG.debug("File source=================================>" + file);
            LOG.debug("FileName====================================>" + fileName);
        }
        ftpClient.mkd(fileLocation);
        ftpClient.cwd(fileLocation);
        inputStream = new FileInputStream(file);
        ftpClient.storeFile(fileName, inputStream);

        ftpClient.logout();
        inputStream.close();
    } catch (Exception e) {
        LOG.error("Exception performing SFTP upload of " + file + " to " + ftpHostname, e);
        throw new RuntimeException(e);
    }
    LOG.trace(
            "************************************doFTPUpload() completed************************************");
}

From source file:org.mousephenotype.dcc.crawler.Downloader.java

private void closeOpenConnections() {
    // close all ftp connections
    Iterator<Entry<String, FTPClient>> ci = ftpConnections.entrySet().iterator();
    while (ci.hasNext()) {
        Entry<String, FTPClient> item = ci.next();
        FTPClient c = item.getValue();
        if (c.isConnected()) {
            try {
                c.logout();
                c.disconnect();/*from  ww w.  j  a v a 2  s . c  om*/
                logger.debug("Downloader has disconnected from '{}'", item.getKey());
            } catch (IOException e) {
                logger.error(e.getMessage());
            }
        }
        ci.remove();
    }

    // close all sftp channels (before closing sessions)
    Iterator<Entry<String, ChannelSftp>> ch = sftpChannels.entrySet().iterator();
    while (ch.hasNext()) {
        Entry<String, ChannelSftp> item = ch.next();
        ChannelSftp c = item.getValue();
        if (c.isConnected()) {
            c.disconnect();
            logger.debug("Downloader has closed sftp channel with '{}'", item.getKey());
        }
        ch.remove();
    }

    // close all sftp sessions
    Iterator<Entry<String, Session>> se = sftpSessions.entrySet().iterator();
    while (se.hasNext()) {
        Entry<String, Session> item = se.next();
        Session c = item.getValue();
        if (c.isConnected()) {
            c.disconnect();
            logger.debug("Downloader has closed sftp session with '{}'", item.getKey());
        }
        se.remove();
    }
}

From source file:org.mule.transport.ftp.FtpConnectionFactory.java

public void destroyObject(Object obj) throws Exception {
    FTPClient client = (FTPClient) obj;
    client.logout();
    client.disconnect();/* www . j  av a  2 s. co m*/
}

From source file:org.mule.transport.ftp.FtpConnector.java

/**
 * Well get the output stream (if any) for this type of transport. Typically this
 * will be called only when Streaming is being used on an outbound endpoint
 *
 * @param endpoint the endpoint that releates to this Dispatcher
 * @param event the current event being processed
 * @return the output stream to use for this request or null if the transport
 *         does not support streaming// w w  w .j av  a2s  . c o m
 */
@Override
public OutputStream getOutputStream(OutboundEndpoint endpoint, MuleEvent event) throws MuleException {
    try {
        final EndpointURI uri = endpoint.getEndpointURI();
        String filename = getFilename(endpoint, event.getMessage());

        final FTPClient client;
        try {
            client = this.createFtpClient(endpoint);
        } catch (Exception e) {
            throw new ConnectException(e, this);
        }

        try {
            OutputStream out = client.storeFileStream(filename);
            if (out == null) {
                throw new IOException("FTP operation failed: " + client.getReplyString());
            }

            return new CallbackOutputStream(out, new CallbackOutputStream.Callback() {
                public void onClose() throws Exception {
                    try {
                        if (!client.completePendingCommand()) {
                            client.logout();
                            client.disconnect();
                            throw new IOException("FTP Stream failed to complete pending request");
                        }
                    } finally {
                        releaseFtp(uri, client);
                    }
                }
            });
        } catch (Exception e) {
            logger.debug("Error getting output stream: ", e);
            releaseFtp(uri, client);
            throw e;
        }
    } catch (ConnectException ce) {
        // Don't wrap a ConnectException, otherwise the retry policy will not go into effect.
        throw ce;
    } catch (Exception e) {
        throw new DispatchException(CoreMessages.streamingFailedNoStream(), event, endpoint, e);
    }
}

From source file:org.mule.transport.ftp.FtpMessageDispatcher.java

@Override
public RetryContext validateConnection(RetryContext retryContext) {
    FTPClient client = null;
    try {// w w  w . j a v  a  2  s  .  c o  m
        client = connector.createFtpClient(endpoint);
        client.sendNoOp();
        client.logout();
        client.disconnect();

        retryContext.setOk();
    } catch (Exception ex) {
        retryContext.setFailed(ex);
    } finally {
        try {
            if (client != null) {
                connector.releaseFtp(endpoint.getEndpointURI(), client);
            }
        } catch (Exception e) {
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to release ftp client " + client, e);
            }

        }
    }

    return retryContext;
}