Example usage for org.apache.commons.net.ftp FTPReply isPositiveCompletion

List of usage examples for org.apache.commons.net.ftp FTPReply isPositiveCompletion

Introduction

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

Prototype

public static boolean isPositiveCompletion(int reply) 

Source Link

Document

Determine if a reply code is a positive completion response.

Usage

From source file:org.jnode.protocol.ftp.FTPURLConnection.java

/**
 * @see java.net.URLConnection#getInputStream()
 *//*from   www  .j  a  v  a  2 s.  c o  m*/
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.jtheque.films.services.impl.utils.file.FTPManager.java

/**
 * Connect to the server.//from  www  . j  av a  2  s. c o m
 *
 * @return The result of the connection.
 */
public Response connect() {
    Response response;

    try {
        ftp.connect(infos.getHost());

        int reply = ftp.getReplyCode();

        if (FTPReply.isPositiveCompletion(reply)) {
            if (ftp.login(infos.getUser(), infos.getPassword())) {
                response = new Response(true, "");

                ftp.setFileType(FTP.ASCII_FILE_TYPE);

                if (infos.isPassive()) {
                    ftp.enterLocalPassiveMode();
                }
            } else {
                ftp.logout();

                response = new Response(false, "ftp.errors.login.impossible");
            }
        } else {
            ftp.disconnect();

            response = new Response(false, "ftp.errors.connection.refused");
        }
    } catch (IOException e) {
        disconnectSimply();

        Managers.getManager(ILoggingManager.class).getLogger(getClass()).error(e);

        response = new Response(false, "ftp.errors.connection.impossible");
    }

    return response;
}

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

protected FTPClient createClient() {
    FTPClient ftpClient = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    ftpClient.configure(config);//from   w w  w .java2s . c o  m

    if (connectTimeout != null) {
        ftpClient.setConnectTimeout(connectTimeout);
    }

    try {
        if (port != null) {
            ftpClient.connect(hostname, port);
        } else {
            ftpClient.connect(hostname);
        }

        int reply = ftpClient.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            throw new RuntimeException(
                    String.format("Failed to connect to %s.  Recevied a reply code of %d", hostname, reply));
        }

        if (isNotBlank(username)) {
            if (!ftpClient.login(username, password)) {
                throw new AuthenticationException();
            }
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpClient.enterLocalPassiveMode();

        if (isNotBlank(basePath)) {
            ftpClient.changeWorkingDirectory(basePath);
        }
        return ftpClient;
    } catch (Exception e) {
        close();
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        } else {
            throw new IoException(e);
        }
    }

}

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

/**
 * @return/*  w w  w  .j a v  a2  s  .c  om*/
 * @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 connects to the FTP server.
 * @param url//  ww  w  .  j  a  v  a2  s.c o m
 * @return ftp
 */
public FTPClient connect(String url) {
    FTPClient ftp = new FTPClient();
    try {
        ftp.connect(getGovURL());
        // Entering passive mode to prevent firewall issues. The client will establish a  data transfer
        // connection.
        ftp.enterLocalPassiveMode();
        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(Constants.CFDA_GOV_LOGIN_USERNAME, "");
        LOG.info("Logged in as " + Constants.CFDA_GOV_LOGIN_USERNAME);
        if (!loggedIn) {
            LOG.error("Could not login as anonymous.");
            throw new IOException("Could not login as anonymous.");
        }

    } catch (IOException io) {
        LOG.error(io.getMessage());
    }
    return ftp;
}

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

/**
 * @return// w  w  w .j ava 2  s .  c om
 * @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  ww .j av a  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.madeirahs.shared.provider.FTPProvider.java

/**
 * Performs a connection attempt to the specified address without sending login information.
 * @param address/*from  w  w  w  . j av a2s  .c  o  m*/
 * @throws SocketException
 * @throws IOException
 */
protected void connect(String address) throws SocketException, IOException {
    ftp.connect(address);
    int reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        throw (new IOException("connection attempted failed with reply code: " + reply));
    }
    this.address = address;
    this.wkdir = ftp.printWorkingDirectory();
    login = true;
    initConn();
}

From source file:org.madeirahs.shared.provider.FTPProvider.java

/**
 * Attempts to login to the FTP server at the specified address.
 * @param address//from  w ww.j a v  a  2  s  . c om
 * @param username
 * @param password
 * @throws SocketException
 * @throws IOException
 */
protected void connect(String address, String username, String password) throws SocketException, IOException {
    ftp.connect(address);
    int reply = ftp.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        throw (new IOException("connection attempted failed with reply code: " + reply));
    }
    this.address = address;
    boolean success = ftp.login(username, password);
    if (!success) {
        ftp.disconnect();
        throw (new LoginException("invalid login"));
    } else {
        Runtime.getRuntime().addShutdownHook(EXIT_HOOK);
        this.wkdir = ftp.printWorkingDirectory();
        login = true;
        initConn();
    }
}

From source file:org.martin.ftp.net.FTPLinker.java

public boolean isConnected() {
    return FTPReply.isPositiveCompletion(client.getReplyCode());
}