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

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

Introduction

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

Prototype

public void setDataTimeout(int timeout) 

Source Link

Document

Sets the timeout in milliseconds to use when reading from the data connection.

Usage

From source file:org.apache.ftpserver.clienttests.BindExceptionSerialTest.java

@Override
protected FTPClient createFTPClient() throws Exception {
    FTPClient c = super.createFTPClient();
    c.setDataTimeout(1000);
    return c;/*from  ww w.  j a va  2  s.c o m*/
}

From source file:org.apache.nifi.processors.standard.util.FTPTransfer.java

private FTPClient getClient(final FlowFile flowFile) throws IOException {
    if (client != null) {
        String desthost = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
        if (remoteHostName.equals(desthost)) {
            // destination matches so we can keep our current session
            resetWorkingDirectory();//from w w w.  j  a v  a 2 s.c  o m
            return client;
        } else {
            // this flowFile is going to a different destination, reset session
            close();
        }
    }

    final Proxy.Type proxyType = Proxy.Type.valueOf(ctx.getProperty(PROXY_TYPE).getValue());
    final String proxyHost = ctx.getProperty(PROXY_HOST).getValue();
    final Integer proxyPort = ctx.getProperty(PROXY_PORT).asInteger();
    FTPClient client;
    if (proxyType == Proxy.Type.HTTP) {
        client = new FTPHTTPClient(proxyHost, proxyPort, ctx.getProperty(HTTP_PROXY_USERNAME).getValue(),
                ctx.getProperty(HTTP_PROXY_PASSWORD).getValue());
    } else {
        client = new FTPClient();
        if (proxyType == Proxy.Type.SOCKS) {
            client.setSocketFactory(new SocksProxySocketFactory(
                    new Proxy(proxyType, new InetSocketAddress(proxyHost, proxyPort))));
        }
    }
    this.client = client;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setDefaultTimeout(
            ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setRemoteVerificationEnabled(false);

    final String remoteHostname = ctx.getProperty(HOSTNAME).evaluateAttributeExpressions(flowFile).getValue();
    this.remoteHostName = remoteHostname;
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }

    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(remoteHostname);
    }

    client.connect(inetAddress, ctx.getProperty(PORT).evaluateAttributeExpressions(flowFile).asInteger());
    this.closed = false;
    client.setDataTimeout(ctx.getProperty(DATA_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());
    client.setSoTimeout(ctx.getProperty(CONNECTION_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue());

    final String username = ctx.getProperty(USERNAME).evaluateAttributeExpressions(flowFile).getValue();
    final String password = ctx.getProperty(PASSWORD).evaluateAttributeExpressions(flowFile).getValue();
    final boolean loggedIn = client.login(username, password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + username + "'");
    }

    final String connectionMode = ctx.getProperty(CONNECTION_MODE).getValue();
    if (connectionMode.equalsIgnoreCase(CONNECTION_MODE_ACTIVE)) {
        client.enterLocalActiveMode();
    } else {
        client.enterLocalPassiveMode();
    }

    final String transferMode = ctx.getProperty(TRANSFER_MODE).getValue();
    final int fileType = (transferMode.equalsIgnoreCase(TRANSFER_MODE_ASCII)) ? FTPClient.ASCII_FILE_TYPE
            : FTPClient.BINARY_FILE_TYPE;
    if (!client.setFileType(fileType)) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    this.homeDirectory = client.printWorkingDirectory();
    return client;
}

From source file:org.apache.nifi.processors.standard.util.FTPUtils.java

/**
 * Creates a new FTPClient connected to an FTP server. The following properties must exist:
 * <ul>Required Properties://  w ww. j a  v  a  2s  .c o m
 * <li>remote.host - The hostname or IP address of the FTP server to connect to</li>
 * <li>remote.user - The username of the account to authenticate with</li>
 * <li>remote.password = The password for the username to authenticate with</li>
 * </ul>
 * <ul>Optional Properties:
 * <li>remote.port - The port on the FTP server to connect to. Defaults to FTP default.</li>
 * <li>transfer.mode - The type of transfer for this connection ('ascii', 'binary'). Defaults to 'binary'</li>
 * <li>connection.mode - The type of FTP connection to make ('active_local', 'passive_local'). Defaults to 'active_local'. In active_local the server initiates 'data connections' to the client
 * where in passive_local the client initiates 'data connections' to the server.</li>
 * <li>network.data.timeout - Default is 0. Sets the timeout in milliseconds for waiting to establish a new 'data connection' (not a control connection) when in ACTIVE_LOCAL mode. Also, this
 * establishes the amount of time to wait on read calls on the data connection in either mode. A value of zero means do not timeout. Users should probably set a value here unless using very
 * reliable communications links or else risk indefinite hangs that require a restart.</li>
 * <li>network.socket.timeout - Default is 0. Sets the timeout in milliseconds to use when creating a new control channel socket and also a timeout to set when reading from a control socket. A
 * value of zero means do not timeout. Users should probably set a value here unless using very reliable communications links or else risk indefinite hangs that require a restart.</li>
 * </ul>
 *
 * @param conf conf
 * @param monitor if provided will be used to monitor FTP commands processed but may be null
 * @return FTPClient connected to FTP server as configured
 * @throws NullPointerException if either argument is null
 * @throws IllegalArgumentException if a required property is missing
 * @throws NumberFormatException if any argument that must be an int cannot be converted to int
 * @throws IOException if some problem occurs connecting to FTP server
 */
public static FTPClient connect(final FTPConfiguration conf, final ProtocolCommandListener monitor)
        throws IOException {
    if (null == conf) {
        throw new NullPointerException();
    }

    final String portVal = conf.port;
    final int portNum = (null == portVal) ? -1 : Integer.parseInt(portVal);
    final String connectionModeVal = conf.connectionMode;
    final String connectionMode = (null == connectionModeVal) ? ACTIVE_LOCAL_CONNECTION_MODE
            : connectionModeVal;
    final String transferModeVal = conf.transferMode;
    final String transferMode = (null == transferModeVal) ? BINARY_TRANSFER_MODE : transferModeVal;
    final String networkDataTimeoutVal = conf.dataTimeout;
    final int networkDataTimeout = (null == networkDataTimeoutVal) ? 0
            : Integer.parseInt(networkDataTimeoutVal);
    final String networkSocketTimeoutVal = conf.connectionTimeout;
    final int networkSocketTimeout = (null == networkSocketTimeoutVal) ? 0
            : Integer.parseInt(networkSocketTimeoutVal);

    final FTPClient client = new FTPClient();
    if (networkDataTimeout > 0) {
        client.setDataTimeout(networkDataTimeout);
    }
    if (networkSocketTimeout > 0) {
        client.setDefaultTimeout(networkSocketTimeout);
    }
    client.setRemoteVerificationEnabled(false);
    if (null != monitor) {
        client.addProtocolCommandListener(monitor);
    }
    InetAddress inetAddress = null;
    try {
        inetAddress = InetAddress.getByAddress(conf.remoteHostname, null);
    } catch (final UnknownHostException uhe) {
    }
    if (inetAddress == null) {
        inetAddress = InetAddress.getByName(conf.remoteHostname);
    }

    if (portNum < 0) {
        client.connect(inetAddress);
    } else {
        client.connect(inetAddress, portNum);
    }
    if (networkDataTimeout > 0) {
        client.setDataTimeout(networkDataTimeout);
    }
    if (networkSocketTimeout > 0) {
        client.setSoTimeout(networkSocketTimeout);
    }
    final boolean loggedIn = client.login(conf.username, conf.password);
    if (!loggedIn) {
        throw new IOException("Could not login for user '" + conf.username + "'");
    }
    if (connectionMode.equals(ACTIVE_LOCAL_CONNECTION_MODE)) {
        client.enterLocalActiveMode();
    } else if (connectionMode.equals(PASSIVE_LOCAL_CONNECTION_MODE)) {
        client.enterLocalPassiveMode();
    }
    boolean transferModeSet = false;
    if (transferMode.equals(ASCII_TRANSFER_MODE)) {
        transferModeSet = client.setFileType(FTPClient.ASCII_FILE_TYPE);
    } else {
        transferModeSet = client.setFileType(FTPClient.BINARY_FILE_TYPE);
    }
    if (!transferModeSet) {
        throw new IOException("Unable to set transfer mode to type " + transferMode);
    }

    return client;
}

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

/**
 * Uses FTPClient to obtain the IOR string from the provided URL via FTP.
 */// w  ww. ja  va  2s  . c  o  m
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.fabric3.binding.ftp.runtime.FtpTargetInterceptor.java

public Message invoke(Message msg) {

    FTPClient ftpClient = new FTPClient();
    ftpClient.setSocketFactory(factory);
    try {/* www  .j ava2 s . c  o m*/
        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.syncany.tests.connection.plugins.ftp.EmbeddedTestFtpServer.java

public static void mkdir(String path, String user) throws SocketException, IOException {
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(3000);// w ww  . j a  v a2 s  . com
    ftp.setDataTimeout(3000);
    ftp.setDefaultTimeout(3000);

    ftp.connect(HOST, PORT);
    ftp.login(user, PASSWORD1);
    ftp.enterLocalPassiveMode();
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // Important !!!
    ftp.makeDirectory(path);

    ftp.disconnect();
    ftp = null;
}

From source file:org.syncany.tests.plugins.ftp.EmbeddedTestFtpServer.java

public static void createTestFile(String path, String user) throws SocketException, IOException {
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(3000);//from   w  ww  .ja v  a  2  s  . c o  m
    ftp.setDataTimeout(3000);
    ftp.setDefaultTimeout(3000);

    ftp.connect(HOST, PORT);
    ftp.login(user, PASSWORD1);
    ftp.enterLocalPassiveMode();
    ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // Important !!!
    ftp.storeFile(path, new ByteArrayInputStream(new byte[] { 0x01, 0x02 }));

    ftp.disconnect();
    ftp = null;
}

From source file:org.teiid.resource.adapter.ftp.FtpManagedConnectionFactory.java

private void beforeConnectProcessing(FTPClient client) throws IOException {

    client.configure(this.config);
    if (this.connectTimeout != null) {
        client.setConnectTimeout(this.connectTimeout);
    }//  w  w  w .j  a v a 2 s  .co  m
    if (this.defaultTimeout != null) {
        client.setDefaultTimeout(this.defaultTimeout);
    }
    if (this.dataTimeout != null) {
        client.setDataTimeout(this.dataTimeout);
    }
    client.setControlEncoding(this.controlEncoding);

    if (this.isFtps) {
        FTPSClient ftpsClient = (FTPSClient) client;
        ftpsClient.execPBSZ(0);
        ftpsClient.execPROT(this.execProt);
    }
}