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

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

Introduction

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

Prototype

public void setDefaultTimeout(int timeout) 

Source Link

Document

Set the default timeout in milliseconds to use when opening a socket.

Usage

From source file:jenkins.plugins.publish_over_ftp.BapFtpHostConfiguration.java

private void configureFTPClient(final FTPClient ftpClient) {
    ftpClient.setDefaultTimeout(timeout);
    ftpClient.setDataTimeout(timeout);//  ww w  . j a v  a 2 s .  c  o m
    if (controlEncoding != null)
        ftpClient.setControlEncoding(controlEncoding);
}

From source file:com.clustercontrol.port.protocol.ReachAddressFTP.java

/**
 * FTP????????//from   w  w  w  .  ja va2 s  . c  o m
 * 
 * @param addressText
 * @return FTP
 */
@Override
protected boolean isRunning(String addressText) {

    m_message = "";
    m_messageOrg = "";
    m_response = -1;

    boolean isReachable = false;

    try {
        long start = 0; // 
        long end = 0; // 
        boolean retry = true; // ????(true:??false:???)

        StringBuffer bufferOrg = new StringBuffer(); // 
        String result = "";

        InetAddress address = InetAddress.getByName(addressText);

        bufferOrg.append("Monitoring the FTP Service of " + address.getHostName() + "["
                + address.getHostAddress() + "]:" + m_portNo + ".\n\n");

        FTPClient client = new FTPClient();

        for (int i = 0; i < m_sentCount && retry; i++) {
            try {
                bufferOrg.append(HinemosTime.getDateString() + " Tried to Connect: ");
                client.setDefaultTimeout(m_timeout);

                start = HinemosTime.currentTimeMillis();
                client.connect(address, m_portNo);
                end = HinemosTime.currentTimeMillis();

                m_response = end - start;

                result = client.getReplyString();

                int reply = client.getReplyCode();

                if (FTPReply.isPositiveCompletion(reply)) {
                    if (m_response > 0) {
                        if (m_response < m_timeout) {
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        } else {
                            m_response = m_timeout;
                            result = result + ("\n" + "Response Time = " + m_response + "ms");
                        }
                    } else {
                        result = result + ("\n" + "Response Time < 1ms");
                    }

                    retry = false;
                    isReachable = true;
                } else {
                    retry = false;
                    isReachable = false;
                }

            } catch (SocketException e) {
                result = (e.getMessage() + "[SocketException]");
                retry = true;
                isReachable = false;
            } catch (IOException e) {
                result = (e.getMessage() + "[IOException]");
                retry = true;
                isReachable = false;
            } finally {
                bufferOrg.append(result + "\n");
                if (client.isConnected()) {
                    try {
                        client.disconnect();
                    } catch (IOException e) {
                        m_log.warn("isRunning(): " + "socket disconnect failed: " + e.getMessage(), e);
                    }
                }
            }

            if (i < m_sentCount - 1 && retry) {
                try {
                    Thread.sleep(m_sentInterval);
                } catch (InterruptedException e) {
                    break;
                }
            }
        }

        m_message = result + "(FTP/" + m_portNo + ")";
        m_messageOrg = bufferOrg.toString();
        return isReachable;
    } catch (UnknownHostException e) {
        m_log.debug("isRunning(): " + MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage()
                + e.getMessage());

        m_message = MessageConstant.MESSAGE_FAIL_TO_EXECUTE_TO_CONNECT.getMessage() + " (" + e.getMessage()
                + ")";

        return false;
    }
}

From source file:com.wheelermarine.android.publicAccesses.Updater.java

@Override
protected Integer doInBackground(URL... urls) {

    try {/*from   w w  w  .j  a  va 2s .  c  o m*/
        final DatabaseHelper db = new DatabaseHelper(context);

        SQLiteDatabase database = db.getWritableDatabase();
        if (database == null)
            throw new IllegalStateException("Unable to open database!");

        database.beginTransaction();
        try {
            // Clear out the old data.
            database.delete(DatabaseHelper.PublicAccessEntry.TABLE_NAME, null, null);

            // Connect to the web server and locate the FTP download link.
            Log.v(TAG, "Finding update: " + urls[0]);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Locating update...");
                    progress.setIndeterminate(true);
                }
            });
            Document doc = Jsoup.connect(urls[0].toString()).timeout(timeout * 1000).userAgent(userAgent).get();
            URL dataURL = null;
            for (Element element : doc.select("a")) {
                if (element.hasAttr("href") && element.attr("href").startsWith("ftp://ftp.dnr.state.mn.us")) {
                    dataURL = new URL(element.attr("href"));
                }
            }

            // Make sure the download URL was fund.
            if (dataURL == null)
                throw new FileNotFoundException("Unable to locate data URL.");

            // Connect to the FTP server and download the update.
            Log.v(TAG, "Downloading update: " + dataURL);
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    progress.setMessage("Downloading update...");
                    progress.setIndeterminate(true);
                }
            });
            FTPClient ftp = new FTPClient();
            try {
                ftp.setConnectTimeout(timeout * 1000);
                ftp.setDefaultTimeout(timeout * 1000);
                ftp.connect(dataURL.getHost());
                ftp.enterLocalPassiveMode();

                // After connection attempt, you should check the reply code
                // to verify success.
                if (!FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                    ftp.disconnect();
                    throw new IOException("FTP server refused connection: " + ftp.getReplyString());
                }

                // Login using the standard anonymous credentials.
                if (!ftp.login("anonymous", "anonymous")) {
                    ftp.disconnect();
                    throw new IOException("FTP Error: " + ftp.getReplyString());
                }

                Map<Integer, Location> locations = null;

                // Download the ZIP archive.
                Log.v(TAG, "Downloading: " + dataURL.getFile());
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                InputStream in = ftp.retrieveFileStream(dataURL.getFile());
                if (in == null)
                    throw new FileNotFoundException(dataURL.getFile() + " was not found!");
                try {
                    ZipInputStream zin = new ZipInputStream(in);
                    try {
                        // Locate the .dbf entry in the ZIP archive.
                        ZipEntry entry;
                        while ((entry = zin.getNextEntry()) != null) {
                            if (entry.getName().endsWith(entryName)) {
                                readDBaseFile(zin, database);
                            } else if (entry.getName().endsWith(shapeEntryName)) {
                                locations = readShapeFile(zin);
                            }
                        }
                    } finally {
                        try {
                            zin.close();
                        } catch (Exception e) {
                            // Ignore this error.
                        }
                    }
                } finally {
                    in.close();
                }

                if (locations != null) {
                    final int recordCount = locations.size();
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            progress.setIndeterminate(false);
                            progress.setMessage("Updating locations...");
                            progress.setMax(recordCount);
                        }
                    });

                    int progress = 0;
                    for (int recordNumber : locations.keySet()) {
                        PublicAccess access = db.getPublicAccessByRecordNumber(recordNumber);
                        Location loc = locations.get(recordNumber);
                        access.setLatitude(loc.getLatitude());
                        access.setLongitude(loc.getLongitude());
                        db.updatePublicAccess(access);
                        publishProgress(++progress);
                    }
                }
            } finally {
                if (ftp.isConnected())
                    ftp.disconnect();
            }
            database.setTransactionSuccessful();
            return db.getPublicAccessesCount();
        } finally {
            database.endTransaction();
        }
    } catch (Exception e) {
        error = e;
        Log.e(TAG, "Error loading data: " + e.getLocalizedMessage(), e);
        return -1;
    }
}

From source file:net.audumla.climate.bom.BOMDataLoader.java

private synchronized FTPClient getFTPClient(String host) {
    FTPClient ftp = ftpClients.get(host);
    if (ftp == null || !ftp.isAvailable() || !ftp.isConnected()) {
        ftp = new FTPClient();
        FTPClientConfig config = new FTPClientConfig();
        ftp.configure(config);//from   w w  w  . java  2  s. c o m
        try {
            ftp.setControlKeepAliveTimeout(30);
            ftp.setControlKeepAliveReplyTimeout(5);
            ftp.setDataTimeout(3000);
            ftp.setDefaultTimeout(1000);
            int reply;
            ftp.connect(host);
            LOG.debug("Connected to " + host);
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                LOG.error("FTP server '" + host + "' refused connection.");
            } else {
                if (!ftp.login("anonymous", "guest")) {
                    LOG.error("Unable to login to server " + host);
                }
                ftp.setSoTimeout(60000);
                ftp.enterLocalPassiveMode();
                ftp.setFileType(FTPClient.BINARY_FILE_TYPE);

            }
        } catch (IOException e) {
            LOG.error("Unable to connect to " + host, e);
        }
        ftpClients.put(host, ftp);
    }
    if (!ftp.isConnected() || !ftp.isAvailable()) {
        throw new UnsupportedOperationException("Cannot connect to " + host);
    }
    return ftp;
}

From source file:ch.cyberduck.core.ftp.FTPSession.java

protected void configure(final FTPClient client) throws IOException {
    client.setProtocol(host.getProtocol());
    client.setSocketFactory(socketFactory);
    client.setControlEncoding(host.getEncoding());
    final int timeout = preferences.getInteger("connection.timeout.seconds") * 1000;
    client.setConnectTimeout(timeout);//  w  w  w  .  j av a  2s  .  c o  m
    client.setDefaultTimeout(timeout);
    client.setDataTimeout(timeout);
    client.setDefaultPort(host.getProtocol().getDefaultPort());
    client.setParserFactory(new FTPParserFactory());
    client.setRemoteVerificationEnabled(preferences.getBoolean("ftp.datachannel.verify"));
    final int buffer = preferences.getInteger("ftp.socket.buffer");
    client.setBufferSize(buffer);

    if (preferences.getInteger("connection.buffer.receive") > 0) {
        client.setReceiveBufferSize(preferences.getInteger("connection.buffer.receive"));
    }
    if (preferences.getInteger("connection.buffer.send") > 0) {
        client.setSendBufferSize(preferences.getInteger("connection.buffer.send"));
    }
    if (preferences.getInteger("connection.buffer.receive") > 0) {
        client.setReceieveDataSocketBufferSize(preferences.getInteger("connection.buffer.receive"));
    }
    if (preferences.getInteger("connection.buffer.send") > 0) {
        client.setSendDataSocketBufferSize(preferences.getInteger("connection.buffer.send"));
    }
    client.setStrictMultilineParsing(preferences.getBoolean("ftp.parser.multiline.strict"));
    client.setStrictReplyParsing(preferences.getBoolean("ftp.parser.reply.strict"));
}

From source file:com.tumblr.maximopro.iface.router.FTPHandler.java

@Override
public byte[] invoke(Map<String, ?> metaData, byte[] data) throws MXException {
    byte[] encodedData = super.invoke(metaData, data);
    this.metaData = metaData;

    FTPClient ftp;
    if (enableSSL()) {
        FTPSClient ftps = new FTPSClient(isImplicit());
        ftps.setTrustManager(TrustManagerUtils.getAcceptAllTrustManager());
        ftp = ftps;/*from  ww  w . j  a  v  a  2s  .c om*/
    } else {
        ftp = new FTPClient();
    }

    InputStream is = null;
    try {

        if (getTimeout() > 0) {
            ftp.setDefaultTimeout(getTimeout());
        }

        if (getBufferSize() > 0) {
            ftp.setBufferSize(getBufferSize());
        }

        if (getNoDelay()) {
            ftp.setTcpNoDelay(getNoDelay());
        }

        ftp.connect(getHostname(), getPort());

        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }

        if (!ftp.login(getUsername(), getPassword())) {
            ftp.logout();
            ftp.disconnect();
        }

        ftp.setFileType(FTP.BINARY_FILE_TYPE);

        if (enableActive()) {
            ftp.enterLocalActiveMode();
        } else {
            ftp.enterLocalPassiveMode();
        }

        is = new ByteArrayInputStream(encodedData);

        String remoteFileName = getFileName(metaData);

        ftp.changeWorkingDirectory("/");
        if (createDirectoryStructure(ftp, getDirName().split("/"))) {
            ftp.storeFile(remoteFileName, is);
        } else {
            throw new MXApplicationException("iface", "cannotcreatedir");
        }

        ftp.logout();
    } catch (MXException e) {
        throw e;
    } catch (SocketException e) {
        throw new MXApplicationException("iface", "ftpsocketerror", e);
    } catch (IOException e) {
        throw new MXApplicationException("iface", "ftpioerror", e);
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }

        if (ftp != null && ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException e) {
                throw new MXApplicationException("iface", "ftpioerror", e);
            }
        }
    }

    return null;
}

From source file:fr.ibp.nifi.processors.IBPFTPTransfer.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();//www. j  a  v a2  s .c om
            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).evaluateAttributeExpressions(flowFile)
            .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:com.hackengine_er.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {/*from ww  w. j a  v a  2s. c  o m*/
        client.connect(Configuration.FTPClient());
        if (client.login(Configuration.FTPUsername(), Configuration.getPASSWORD())) {
            client.setDefaultTimeout(10000);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (client.storeFile(Tags.SITE + username + "-" + fileName, inputStream)) {
                return true;
            }
        }
    } catch (IOException e) {
        Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return false;
}

From source file:com.muslumyusuf.DBOperations.java

private boolean uploadToFTP(String username, String fileName, InputStream inputStream) {
    FTPClient client = new FTPClient();
    try {//from  w ww. ja v a 2s .co  m
        client.connect(Initialize.FTPClient());
        if (client.login(Initialize.FTPUsername(), Initialize.getPASSWORD())) {
            client.setDefaultTimeout(10000);
            client.setFileType(FTPClient.BINARY_FILE_TYPE);
            if (client.storeFile(Tags.SITE + username + "/" + fileName, inputStream)) {
                return true;
            }
        }
    } catch (IOException e) {
        Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
                client.disconnect();
            } catch (IOException ex) {
                Logger.getLogger(DBOperations.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    return false;
}

From source file:com.clickha.nifi.processors.util.FTPTransferV2.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();/*w w  w.  j  a va  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();
    }

    // additional  
    FTPClientConfig ftpConfig = new FTPClientConfig(FTPClientConfig.SYST_UNIX);
    final String ftpClientConfig = ctx.getProperty(FTP_CLIENT_CONFIG_SYST).getValue();
    if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_UNIX)) {
        this.ftpConfig = ftpConfig;
        client.configure(ftpConfig);
    } else if (ftpClientConfig.equalsIgnoreCase(FTP_CLIENT_CONFIG_SYST_NT)) {
        this.ftpConfig = ftpConfig;
        client.configure(ftpConfig);
    }

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