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

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

Introduction

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

Prototype

public boolean login(String username, String password) throws IOException 

Source Link

Document

Login to the FTP server using the provided username and password.

Usage

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

/**
 * @return/*w  w w .  jav a 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//ww w  . jav  a 2s .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.limy.common.util.FtpUtils.java

/**
 * FTP????/*from   ww  w  .  ja va 2s  . com*/
 * <p>
 * ?????disconnect?????
 * </p>
 * @param client FTP
 * @param info FTP
 * @throws IOException I/O
 */
public static void connectFtp(FTPClient client, FtpInfo info) throws IOException {

    client.connect(info.getServerAddress());
    if (!client.login(info.getUserName(), info.getPassword())) {
        throw new IOException("?????");
    }
    if (info.getPath() != null) {
        client.cwd(info.getPath());
    }
}

From source file:org.middleheaven.io.repository.ftp.TestFTP.java

private FTPClient connect() {
    try {/*from  ww w .  ja va 2 s.  c  o m*/
        FTPClient ftp = new FTPClient();
        if (!ftp.isConnected()) {
            ftp.connect("184.107.197.226");
            ftp.login("javabuil", "%Q&4pr|!O}=");
        }

        return ftp;
    } catch (IOException e) {
        throw ManagedIOException.manage(e);
    }
}

From source file:org.mule.modules.FtpUtils.java

public static FTPClient createSession(FtpLiteConnectorConfig config, String userName, String hostName,
        String port, String password) {
    FTPClient ftp = new FTPClient();
    ftp.setControlEncoding(config.getEncoding());
    try {// w  w w  .j a v a 2  s.co m
        ftp.connect(hostName, Integer.parseInt(port));
        ftp.login(userName, password);
    } catch (NumberFormatException e) {
        throw new FtpLiteHostException("Port was incorrect and could not be parsed");
    } catch (SocketException e) {
        throw new FtpLiteHostException("Error connecting. " + e.toString());
    } catch (IOException e) {
        throw new FtpLiteHostException("Error connecting. " + e.toString());
    }
    return ftp;
}

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

public Object makeObject() throws Exception {
    FTPClient client = new FTPClient();
    if (uri.getPort() > 0) {
        client.connect(uri.getHost(), uri.getPort());
    } else {//from   w  w w . ja  va  2s . c  om
        client.connect(uri.getHost());
    }
    if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
        throw new IOException("Ftp connect failed: " + client.getReplyCode());
    }
    if (!client.login(uri.getUser(), uri.getPassword())) {
        throw new IOException("Ftp login failed: " + client.getReplyCode());
    }
    if (!client.setFileType(FTP.BINARY_FILE_TYPE)) {
        throw new IOException("Ftp error. Couldn't set BINARY transfer type: " + client.getReplyCode());
    }
    return client;
}

From source file:org.mule.transport.ftp.server.ServerTest.java

/**
 * Sanity test that the embedded ftp server is working. Useful as a first step if
 * the ftp transport tests are failing./*from  w  w  w.j av  a 2s  .com*/
 *
 * @throws Exception
 */
@Test
public void testServerLogin() throws Exception {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect("localhost", dynamicPort.getNumber());
    ftpClient.login("admin", "admin");
}

From source file:org.n52.sos.importer.controller.Step1Controller.java

@Override
public boolean isFinished() {

    if (step1Panel != null && step1Panel.getFeedingType() == Step1Panel.CSV_FILE) {
        final String filePath = step1Panel.getCSVFilePath();
        if (filePath == null) {
            JOptionPane.showMessageDialog(null, "Please choose a CSV file.", "File missing",
                    JOptionPane.WARNING_MESSAGE);
            return false;
        }//  ww w . j a  v a2s .  c o m
        // checks one-time feed input data for validity
        if (filePath.equals("")) {
            JOptionPane.showMessageDialog(null, "Please choose a CSV file.", "File missing",
                    JOptionPane.WARNING_MESSAGE);
            return false;
        }

        final File dataFile = new File(filePath);
        if (!dataFile.exists()) {
            JOptionPane.showMessageDialog(null, "The specified file does not exist.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (!dataFile.isFile()) {
            JOptionPane.showMessageDialog(null, "Please specify a file, not a directory.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (!dataFile.canRead()) {
            JOptionPane.showMessageDialog(null, "No reading access on the specified file.", "Error",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }
        readFile(dataFile, step1Panel.getFileEncoding());
    } else if (step1Panel != null && (step1Panel.getFeedingType() == Step1Panel.FTP_FILE)) {
        // checks repetitive feed input data for validity
        if (step1Panel.getUrl() == null || step1Panel.getUrl().equals("")) {
            JOptionPane.showMessageDialog(null, "No ftp server was specified.", "Server missing",
                    JOptionPane.ERROR_MESSAGE);
            return false;
        }

        if (step1Panel.getFilenameSchema() == null || step1Panel.getFilenameSchema().equals("")) {
            JOptionPane.showMessageDialog(null, "No file/file schema was specified.",
                    "File/file schema missing", JOptionPane.ERROR_MESSAGE);
            return false;
        }

        // ftp client
        FTPClient client;

        // proxy
        final String pHost = System.getProperty("proxyHost", "proxy");
        int pPort = -1;
        if (System.getProperty("proxyPort") != null) {
            pPort = Integer.parseInt(System.getProperty("proxyPort"));
        }
        final String pUser = System.getProperty("http.proxyUser");
        final String pPassword = System.getProperty("http.proxyPassword");
        if (pHost != null && pPort != -1) {
            if (pUser != null && pPassword != null) {
                client = new FTPHTTPClient(pHost, pPort, pUser, pPassword);
            }
            client = new FTPHTTPClient(pHost, pPort);
        } else {
            client = new FTPClient();
        }

        // get first file
        if (step1Panel.getFeedingType() == Step1Panel.FTP_FILE) {
            final String csvFilePath = System.getProperty("user.home") + File.separator + ".SOSImporter"
                    + File.separator + "tmp_" + step1Panel.getFilenameSchema();

            // if back button was used: delete old file
            if (new File(csvFilePath).exists()) {
                new File(csvFilePath).delete();
            }

            try {
                client.connect(step1Panel.getUrl());
                final boolean login = client.login(step1Panel.getUser(), step1Panel.getPassword());
                if (login) {
                    // download file
                    final int result = client.cwd(step1Panel.getDirectory());
                    if (result == 250) { // successfully connected
                        final File outputFile = new File(csvFilePath);
                        final FileOutputStream fos = new FileOutputStream(outputFile);
                        client.retrieveFile(step1Panel.getFilenameSchema(), fos);
                        fos.flush();
                        fos.close();
                    }
                    final boolean logout = client.logout();
                    if (logout) {
                        logger.info("Step1Controller: cannot logout!");
                    }
                } else {
                    logger.info("Step1Controller: cannot login!");
                }

                final File csv = new File(csvFilePath);
                if (csv.length() != 0) {
                    step1Panel.setCSVFilePath(csvFilePath);
                    readFile(new File(csvFilePath), step1Panel.getFileEncoding());
                } else {
                    csv.delete();
                    throw new IOException();
                }

            } catch (final SocketException e) {
                System.err.println(e);
                JOptionPane.showMessageDialog(null, "The file you specified cannot be obtained.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return false;
            } catch (final IOException e) {
                System.err.println(e);
                JOptionPane.showMessageDialog(null, "The file you specified cannot be obtained.", "Error",
                        JOptionPane.ERROR_MESSAGE);
                return false;
            }
        }
    }

    return true;
}

From source file:org.n52.sos.importer.feeder.task.OneTimeFeeder.java

private DataFile getRemoteFile(final Configuration config) {
    File dataFile = null;/*from www  . ja va  2s  .c o m*/

    // ftp client
    FTPClient client;

    // proxy
    final String pHost = System.getProperty("proxyHost", "proxy");
    int pPort = -1;
    if (System.getProperty("proxyPort") != null) {
        pPort = Integer.parseInt(System.getProperty("proxyPort"));
    }
    final String pUser = System.getProperty("http.proxyUser");
    final String pPassword = System.getProperty("http.proxyPassword");
    if (pHost != null && pPort != -1) {
        LOG.info("Using proxy for FTP connection!");
        if (pUser != null && pPassword != null) {
            client = new FTPHTTPClient(pHost, pPort, pUser, pPassword);
        }
        client = new FTPHTTPClient(pHost, pPort);
    } else {
        LOG.info("Using no proxy for FTP connection!");
        client = new FTPClient();
    }

    // get first file
    final String directory = config.getConfigFile().getAbsolutePath();
    dataFile = FileHelper.createFileInImporterHomeWithUniqueFileName(directory + ".csv");

    // if back button was used: delete old file
    if (dataFile.exists()) {
        dataFile.delete();
    }

    try {
        client.connect(config.getFtpHost());
        final boolean login = client.login(config.getUser(), config.getPassword());
        if (login) {
            LOG.info("FTP: connected...");
            // download file
            final int result = client.cwd(config.getFtpSubdirectory());
            LOG.info("FTP: go into directory...");
            if (result == 250) { // successfully connected
                final FileOutputStream fos = new FileOutputStream(dataFile);
                LOG.info("FTP: download file...");
                client.retrieveFile(config.getFtpFile(), fos);
                fos.flush();
                fos.close();
            } else {
                LOG.info("FTP: cannot go to subdirectory!");
            }
            final boolean logout = client.logout();
            if (!logout) {
                LOG.info("FTP: cannot logout!");
            }
        } else {
            LOG.info("FTP:  cannot login!");
        }

    } catch (final SocketException e) {
        LOG.error("The file you specified cannot be obtained.");
        return null;
    } catch (final IOException e) {
        LOG.error("The file you specified cannot be obtained.");
        return null;
    }

    return new DataFile(config, dataFile);
}

From source file:org.nmdp.service.epitope.task.URLProcessor.java

public long getFtpLastModifiedTime(URL url) {
    FTPClient ftpClient = new FTPClient();
    try {/*ww  w.  ja va  2  s . c o m*/
        ftpClient.connect(url.getHost(), url.getPort() == -1 ? url.getDefaultPort() : url.getPort());
        ftpClient.login("anonymous", "anonymous");
        ftpClient.enterLocalPassiveMode();
        String filePath = url.getPath();
        String time = ftpClient.getModificationTime(filePath);
        //logger.debug("server replied: " + time);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        String timePart = time.split(" ")[1];
        Date modificationTime = dateFormat.parse(timePart);
        //logger.debug("parsed time: " + modificationTime);
        return modificationTime.getTime();
    } catch (Exception e) {
        logger.error("failed to parse time for url: " + url, e);
        return 0;
    } finally {
        if (ftpClient.isConnected()) {
            try {
                ftpClient.disconnect();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}