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

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

Introduction

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

Prototype

public void connect(InetAddress host, int port) throws SocketException, IOException 

Source Link

Document

Opens a Socket connected to a remote host at the specified port and originating from the current host at a system assigned port.

Usage

From source file:org.codice.alliance.nsili.source.NsiliSource.java

/**
 * Uses FTPClient to obtain the IOR string from the provided URL via FTP.
 *///from w  ww . ja  v  a2s  . c  om
private void getIorStringFromFtpSource() {
    URI uri = null;
    try {
        uri = new URI(iorUrl);
    } catch (URISyntaxException e) {
        LOGGER.error("{} : Invalid URL specified for IOR string: {} {}", id, iorUrl, e.getMessage());
        LOGGER.debug("{} : Invalid URL specified for IOR string: {}", id, iorUrl, e);
    }

    FTPClient ftpClient = new FTPClient();
    try {
        if (uri.getPort() > 0) {
            ftpClient.connect(uri.getHost(), uri.getPort());
        } else {
            ftpClient.connect(uri.getHost());
        }

        if (!ftpClient.login(serverUsername, serverPassword)) {
            LOGGER.error("{} : FTP server log in unsuccessful.", id);
        } else {
            int timeoutMsec = clientTimeout * 1000;
            ftpClient.setConnectTimeout(timeoutMsec);
            ftpClient.setControlKeepAliveReplyTimeout(timeoutMsec);
            ftpClient.setDataTimeout(timeoutMsec);

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

            InputStream inputStream = ftpClient.retrieveFileStream(uri.getPath());

            iorString = IOUtils.toString(inputStream, StandardCharsets.ISO_8859_1.name());
            //Remove leading/trailing whitespace as the CORBA init can't handle that.
            iorString = iorString.trim();
        }
    } catch (Exception e) {
        LOGGER.warn("{} : Error retrieving IOR file for {}. {}", id, iorUrl, e.getMessage());
        LOGGER.debug("{} : Error retrieving IOR file for {}.", id, iorUrl, e);
    }
}

From source file:org.drftpd.tests.ConnectionStressTest.java

public void run() {
    try {/* ww  w.  ja v a2  s. c om*/
        FTPClient c = new FTPClient();
        c.configure(ftpConfig);

        logger.debug("Trying to connect");
        c.connect("127.0.0.1", 21211);
        logger.debug("Connected");

        c.setSoTimeout(5000);

        if (!FTPReply.isPositiveCompletion(c.getReplyCode())) {
            logger.debug("Houston, we have a problem. D/C");
            c.disconnect();
            throw new Exception();
        }

        if (c.login("drftpd", "drftpd")) {
            logger.debug("Logged-in, now waiting 5 secs and kill the thread.");
            _sc.addSuccess();
            Thread.sleep(5000);
            c.disconnect();
        } else {
            logger.debug("Login failed, D/C!");
            throw new Exception();
        }
    } catch (Exception e) {
        logger.debug(e, e);
        _sc.addFailure();
    }

    logger.debug("exiting");
}

From source file:org.fabric3.binding.ftp.runtime.FtpTargetInterceptor.java

public Message invoke(Message msg) {

    FTPClient ftpClient = new FTPClient();
    ftpClient.setSocketFactory(factory);
    try {//from  w  ww.j  av  a  2  s .c om
        if (timeout > 0) {
            ftpClient.setDefaultTimeout(timeout);
            ftpClient.setDataTimeout(timeout);
        }
        monitor.onConnect(hostAddress, port);
        ftpClient.connect(hostAddress, port);
        monitor.onResponse(ftpClient.getReplyString());
        String type = msg.getWorkContext().getHeader(String.class, FtpConstants.HEADER_CONTENT_TYPE);
        if (type != null && type.equalsIgnoreCase(FtpConstants.BINARY_TYPE)) {
            monitor.onCommand("TYPE I");
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        } else if (type != null && type.equalsIgnoreCase(FtpConstants.TEXT_TYPE)) {
            monitor.onCommand("TYPE A");
            ftpClient.setFileType(FTP.ASCII_FILE_TYPE);
            monitor.onResponse(ftpClient.getReplyString());
        }

        /*if (!ftpClient.login(security.getUser(), security.getPassword())) {
        throw new ServiceUnavailableException("Invalid credentials");
        }*/
        // TODO Fix above
        monitor.onAuthenticate();
        ftpClient.login(security.getUser(), security.getPassword());
        monitor.onResponse(ftpClient.getReplyString());

        Object[] args = (Object[]) msg.getBody();
        String fileName = (String) args[0];
        String remoteFileLocation = fileName;
        InputStream data = (InputStream) args[1];

        if (active) {
            monitor.onCommand("ACTV");
            ftpClient.enterLocalActiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        } else {
            monitor.onCommand("PASV");
            ftpClient.enterLocalPassiveMode();
            monitor.onResponse(ftpClient.getReplyString());
        }
        if (commands != null) {
            for (String command : commands) {
                monitor.onCommand(command);
                ftpClient.sendCommand(command);
                monitor.onResponse(ftpClient.getReplyString());
            }
        }

        if (remotePath != null && remotePath.length() > 0) {
            remoteFileLocation = remotePath.endsWith("/") ? remotePath + fileName : remotePath + "/" + fileName;
        }

        String remoteTmpFileLocation = remoteFileLocation;
        if (tmpFileSuffix != null && tmpFileSuffix.length() > 0) {
            remoteTmpFileLocation += tmpFileSuffix;
        }

        monitor.onCommand("STOR " + remoteFileLocation);
        if (!ftpClient.storeFile(remoteTmpFileLocation, data)) {
            throw new ServiceUnavailableException("Unable to upload data. Response sent from server: "
                    + ftpClient.getReplyString() + " ,remoteFileLocation:" + remoteFileLocation);
        }
        monitor.onResponse(ftpClient.getReplyString());

        //Rename file back to original name if temporary file suffix was used while transmission.
        if (!remoteTmpFileLocation.equals(remoteFileLocation)) {
            ftpClient.rename(remoteTmpFileLocation, remoteFileLocation);
        }
    } catch (IOException e) {
        throw new ServiceUnavailableException(e);
    }
    // reset the message to return an empty response
    msg.reset();
    return msg;
}

From source file:org.fabric3.transport.ftp.server.host.F3FtpHostTest.java

public void testValidLogin() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(InetAddress.getLocalHost(), 1234);
    ftpClient.user("user");
    assertEquals(230, ftpClient.pass("password"));
}

From source file:org.fabric3.transport.ftp.server.host.F3FtpHostTest.java

public void testInvalidLogin() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(InetAddress.getLocalHost(), 1234);
    ftpClient.user("user");
    assertEquals(530, ftpClient.pass("password1"));
}

From source file:org.fabric3.transport.ftp.server.host.F3FtpHostTest.java

public void testStor() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.connect(InetAddress.getLocalHost(), 1234);
    ftpClient.user("user");
    ftpClient.pass("password");
    ftpClient.enterLocalPassiveMode();// w  w  w .j  a  va 2s. com
    ftpClient.storeFile("/resource/test.dat", new ByteArrayInputStream("TEST\r\n".getBytes()));
}

From source file:org.gitools.datasources.obo.OBOStream.java

public OBOStream(URL baseUrl) throws IOException {
    this.baseUrl = baseUrl;

    // Workaround for FTP problem connecting ftp.geneontology.org with URL.openStream()
    if (baseUrl.getProtocol().equalsIgnoreCase("ftp")) {
        FTPClient ftp = new FTPClient();
        if (baseUrl.getPort() != -1) {
            ftp.connect(baseUrl.getHost(), baseUrl.getPort());
        } else {// w  ww. ja  v a 2 s.  co m
            ftp.connect(baseUrl.getHost());
        }
        ftp.login("anonymous", "");
        ftp.enterLocalPassiveMode();
        ftp.setControlKeepAliveTimeout(60);
        InputStream is = ftp.retrieveFileStream(baseUrl.getPath());
        this.reader = new BufferedReader(new InputStreamReader(is));
    } else {
        this.reader = new BufferedReader(new InputStreamReader(baseUrl.openStream()));
    }

    this.linePos = 0;
}

From source file:org.grouter.core.readers.FtpReaderJob.java

/**
 * Use configuration parameters to create a connection to the ftp endpoint.
 * @return a FTPClient instance/*ww  w  . j a  v  a 2 s. c o  m*/
 * @throws Exception if connection problems
 */
private FTPClient initConnection() throws Exception {
    FTPClient client;
    String host = null;
    String strPort;
    try {

        Map map = node.getInBound().getEndPointContext();
        host = node.getInBound().getUri();
        strPort = (String) map.get(FTP_PORT);
        client = new FTPClient();
        int port = FTP_DEFAULT_PORT;
        if (StringUtils.isNotEmpty(strPort)) {
            port = Integer.parseInt(strPort);
            client.connect(host, port);
            int reply = client.getReplyCode();
            logger.debug("reply :" + reply);
            if (FTPReply.isPositiveCompletion(reply)) {
                logger.info("Connected to ftp server :" + client.getRemoteAddress().getHostAddress());
            }
        } else {
            client.connect(host, port);
            int reply = client.getReplyCode();
            logger.debug("reply :" + reply);
            if (FTPReply.isPositiveCompletion(reply)) {
                logger.info("Connected to ftp server :" + client.getRemoteAddress().getHostAddress());
            }

        }

        String user = (String) map.get(FTP_AUTH_USER);
        String pwd = (String) map.get(FTP_AUTH_PASSWORD);
        if (StringUtils.isNotEmpty(user) && StringUtils.isNotEmpty(pwd)) {
            client.login(user, pwd);
            int replyCode = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(replyCode)) {
                logger.info("Logged into ftp server :" + host);
            }
        } else {
            client.login("anonymous", "mymail@mail.com");
            int replyCode = client.getReplyCode();
            if (FTPReply.isPositiveCompletion(replyCode)) {
                logger.info("Logged into ftp server :" + host);
            }
        }
    } catch (Exception e) {
        throw new Exception("Could not establish connection with ftp endpoint using host:" + host, e);
    }
    return client;
}

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  w w  .ja 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.jumpmind.metl.core.runtime.resource.FtpDirectory.java

protected FTPClient createClient() {
    FTPClient ftpClient = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    ftpClient.configure(config);/* w  w  w.  j  a va 2 s  .  c om*/

    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);
        }
    }

}