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

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

Introduction

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

Prototype

public FTPClient() 

Source Link

Document

Default FTPClient constructor.

Usage

From source file:org.n52.ifgicopter.spf.extension.FTPUploadExtension.java

@Override
public void init() throws Exception {
    this.ftpConfig = new Properties();
    this.ftpConfig.load(getClass().getResourceAsStream("/FTPUploadExtension.properties"));

    // TODO check in spf deploy environment
    this.watchFolder = new File(this.watchFolderPath).getAbsoluteFile();

    this.ftp = new FTPClient();
    connect();//from  w  w  w.j ava2  s  .  com
    disconnect();

    readInitialFolderContents();

    this.watchThread = new WatchfolderThread();
    new Thread(this.watchThread).start();

    logger.debug("Initialized " + this);
}

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;
        }//www.jav 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  ww  w.  ja va  2 s .c  om

    // 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.nabucco.testautomation.engine.proxy.process.ProcessProxyEngineImpl.java

/**
 * {@inheritDoc}// w  w w  . j a va2 s  .  c  o m
 */
@Override
public void configure(ProxyEngineConfiguration config) throws ProxyConfigurationException {
    this.ftpClient = new FTPClient();
    this.ftpClient.setListHiddenFiles(true);

    this.sftpClient = new SFTPClient();

    logger.info("ProcessProxyEngine configured");
}

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

public long getFtpLastModifiedTime(URL url) {
    FTPClient ftpClient = new FTPClient();
    try {/*ww w  .  j  a v  a 2 s  .com*/
        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();
            }
        }
    }
}

From source file:org.okj.commons.net.FtpUtils.java

/**
 * /*from   w  w w  .j  av  a  2  s  .  c  o  m*/
 */
protected FtpUtils() {
    //FTP
    this.ftp = new FTPClient();
    this.ftp.configure(getFTPClientConfig());
}

From source file:org.onebusaway.transit_data_federation.impl.realtime.orbcad.OrbcadRecordFtpSource.java

private void reconnectFtp() throws SocketException, IOException {

    _log.info("attempting to establish ftp connection");

    disconnectFtpClient();/*from ww w .  ja v  a2  s.c o m*/

    _ftpClient = new FTPClient();

    _ftpClient.setConnectTimeout(TIMEOUT_IN_SECONDS * 1000);
    _ftpClient.setDataTimeout(TIMEOUT_IN_SECONDS * 1000);
    _ftpClient.setDefaultTimeout(TIMEOUT_IN_SECONDS * 1000);

    _ftpClient.connect(_dataSource.getServername(), _dataSource.getPort());
    _ftpClient.login(_dataSource.getUsername(), _dataSource.getPassword());

    _ftpClient.enterLocalPassiveMode();
    _log.info("ftp connection established");
}

From source file:org.onehippo.forge.utilities.commons.ftp.SimpleFtpClient.java

/**
 * Constructor if port is different than port 21
 *
 * @param userName login name/*from   w  w  w. ja  v a2s . co  m*/
 * @param password login password
 * @param server   server address (name or ip address))
 * @param port     port number
 */
public SimpleFtpClient(final String userName, final String password, final String server, final int port) {
    this.userName = userName;
    this.password = password;
    this.server = server;
    this.port = port;
    this.client = new FTPClient();
}

From source file:org.openadaptor.thirdparty.apache.ApacheFTPConnection.java

/**
 * Takes the supplied hostname and port of the target machine and attempts to connect to it. If successful the
 * isConnected() flag is set. Sets the file transfer mode.
 * /*from   w ww .j av a  2 s .co  m*/
 * @throws ConnectionException
 *           if we fail to connect to the remote server or we fail to set BINARY mode (if required)
 */
public void connect() throws ConnectionException {
    log.debug("Connecting to " + hostName + " on port " + port);

    try {
        _ftpClient = new FTPClient();

        _ftpClient.connect(hostName, port);

        // check to see that the connection went through ok
        if (!FTPReply.isPositiveCompletion(_ftpClient.getReplyCode())) {
            _ftpClient.disconnect();
            throw new Exception("Failed to connect");
        }

        // set the file transfer mode
        try {
            if (binaryTransfer) {
                _ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
                log.debug("Binary transfer mode set");
            } else {
                _ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
                log.debug("ASCII transfer mode set");
            }
        } catch (IOException e) {
            throw new ConnectionException("Failed to set " + (binaryTransfer ? "binary" : "ascii")
                    + " transfer mode: " + e.getMessage(), this);
        }

        log.debug("ApacheFTPLibrary object initialised and connected to " + hostName);
    } catch (Exception e) {
        close();
        throw new ConnectionException("Failed to initialise the ApacheFTPLibrary object: " + e.getMessage(),
                this);
    }
}

From source file:org.openbel.framework.core.protocol.handler.FTPConnector.java

/**
 * Connects and authenticates with the ftp server specified by the
 * {@code ftpUrl}.//from www  .  jav  a 2s . c om
 * 
 * @param ftpUrl {@link URL}, the ftp server url
 * @throws ResourceDownloadError - Thrown if there was an ftp error
 * connecting or authenticating with the ftp server.
 */
public void connectAndLogin(URL ftpUrl) throws ResourceDownloadError {
    if (!ftpUrl.getProtocol().equals("ftp")) {
        throw new InvalidArgument(
                "The ftp connection does not support protocol '" + ftpUrl.getProtocol() + "', only 'ftp'.");
    }

    //connect to ftp server
    String host = ftpUrl.getHost();
    int port = ftpUrl.getPort() == -1 ? DEFAULT_FTP_PORT : ftpUrl.getPort();
    ftpClient = new FTPClient();

    try {
        ftpClient.connect(host, port);
    } catch (Exception e) {
        final String url = ftpUrl.toString();
        final String msg = e.getMessage();
        throw new ResourceDownloadError(url, msg, e);
    }

    //login to user account
    String userInfo = ftpUrl.getUserInfo();
    String username = DEFAULT_USER_NAME;
    String password = "";
    if (userInfo != null) {
        if (userInfo.contains(":")) {
            //provided username & password so parse
            String[] userInfoTokens = userInfo.split("\\:");
            if (userInfoTokens.length == 2) {
                username = userInfoTokens[0];
                password = userInfoTokens[1];
            }
        } else {
            //provided only username
            username = userInfo;

            //prompt for password
            char[] pwd;
            try {
                pwd = PasswordPrompter.getPassword(pwdInputStream, "Connecting to '" + ftpUrl.toString()
                        + "'.  Enter password for user '" + username + "': ");
            } catch (IOException e) {
                final String name = ftpUrl.toString();
                final String msg = e.getMessage();
                throw new ResourceDownloadError(name, msg, e);
            }
            if (pwd == null) {
                password = "";
            } else {
                password = String.valueOf(pwd);
            }
        }
    }

    try {
        if (!ftpClient.login(username, password)) {
            final String name = ftpUrl.toString();
            final String msg = "Login error for username and password";
            throw new ResourceDownloadError(name, msg);
        }
    } catch (IOException e) {
        final String name = ftpUrl.toString();
        final String msg = "Login error for username and password";
        throw new ResourceDownloadError(name, msg, e);
    }

    try {
        ftpClient.pasv();
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
    } catch (IOException e) {
        final String url = ftpUrl.toString();
        final String msg = "Error setting passive mode or transfer type";
        throw new ResourceDownloadError(url, msg, e);
    }
}