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

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

Introduction

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

Prototype

public void setConnectTimeout(int connectTimeout) 

Source Link

Document

Sets the connection timeout in milliseconds, which will be passed to the Socket object's connect() method.

Usage

From source file:com.intellij.diagnostic.SubmitPerformanceReportAction.java

@Nullable
private static String uploadFileToFTP(final File reportPath, @NonNls final String ftpSite,
        @NonNls final String directory, final ProgressIndicator indicator) {
    FTPClient ftp = new FTPClient();
    ftp.setConnectTimeout(30 * 1000);
    try {//from ww w.  j  a v a  2s . c  o m
        indicator.setText("Connecting to server...");
        ftp.connect(ftpSite);
        indicator.setText("Connected to server");

        if (!ftp.login("anonymous", "anonymous@jetbrains.com")) {
            return "Failed to login";
        }
        indicator.setText("Logged in");

        // After connection attempt, you should check the reply code to verify
        // success.
        int reply = ftp.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
            return "FTP server refused connection: " + reply;
        }
        if (!ftp.changeWorkingDirectory(directory)) {
            return "Failed to change directory";
        }

        // else won't work behind FW
        ftp.enterLocalPassiveMode();

        if (!ftp.setFileType(FTPClient.BINARY_FILE_TYPE)) {
            return "Failed to switch to binary mode";
        }

        indicator.setText("Transferring (" + StringUtil.formatFileSize(reportPath.length()) + ")");
        FileInputStream readStream = new FileInputStream(reportPath);
        try {
            if (!ftp.storeFile(reportPath.getName(), readStream)) {
                return "Failed to upload file";
            }
        } catch (IOException e) {
            return "Error during transfer: " + e.getMessage();
        } finally {
            readStream.close();
        }
        ftp.logout();
        return null;
    } catch (IOException e) {
        return "Failed to upload: " + e.getMessage();
    } finally {
        if (ftp.isConnected()) {
            try {
                ftp.disconnect();
            } catch (IOException ioe) {
                // do nothing
            }
        }
    }
}

From source file:com.kcs.core.utilities.FtpUtil.java

public static FTPClient openFtpConnect(String hostname, int port, String username, String password)
        throws Exception {
    FTPClient ftp = null;
    try {//from  w w  w  .  j  a va  2  s.c o m
        ftp = new FTPClient();
        ftp.setConnectTimeout(1000);
        ftp.connect(hostname, port);
        ftp.login(username, password);
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
    return ftp;
}

From source file:com.zxy.commons.net.ftp.FtpUtils.java

/**
 * FTP handle//from   w  w  w  .j  av a  2  s  .  co m
 * 
 * @param <T> return object type
 * @param ftpConfig ftp config
 * @param callback ftp callback
 * @return value
*/
public static <T> T ftpHandle(FtpConfig ftpConfig, FtpCallback<T> callback) {
    FTPClient client = null;
    if (ftpConfig.isFtps() && ftpConfig.getSslContext() != null) {
        client = new FTPSClient(ftpConfig.getSslContext());
    } else if (ftpConfig.isFtps()) {
        client = new FTPSClient();
    } else {
        client = new FTPClient();
    }

    client.configure(ftpConfig.getFtpClientConfig());
    try {
        //            client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        client.connect(ftpConfig.getHost(), ftpConfig.getPort());
        client.setConnectTimeout(ftpConfig.getConnectTimeoutMs());
        client.setControlKeepAliveTimeout(ftpConfig.getKeepAliveTimeoutSeconds());
        if (!Strings.isNullOrEmpty(ftpConfig.getUsername())) {
            client.login(ftpConfig.getUsername(), ftpConfig.getPassword());
        }
        LOGGER.trace("Connected to {}, reply: {}", ftpConfig.getHost(), client.getReplyString());

        // After connection attempt, you should check the reply code to verify success.
        int reply = client.getReplyCode();

        if (!FTPReply.isPositiveCompletion(reply)) {
            client.disconnect();
            throw new NetException("FTP server refused connection.");
        }
        return callback.process(client);
    } catch (Exception e) {
        throw new NetException(e);
    } finally {
        if (client.isConnected()) {
            try {
                client.logout();
            } catch (IOException ioe) {
                LOGGER.warn(ioe.getMessage());
            }
            try {
                client.disconnect();
            } catch (IOException ioe) {
                LOGGER.warn(ioe.getMessage());
            }
        }
    }
}

From source file:net.seedboxer.camel.component.file.remote.ftp2.Ftp2Endpoint.java

@Override
public RemoteFileOperations<FTPFile> createRemoteFileOperations() throws Exception {
    // configure ftp client
    FTPClient client = ftpClient;

    if (client == null) {
        // must use a new client if not explicit configured to use a custom client
        client = createFtpClient();//from  w ww  .j  a  v a  2s .  com
    }

    // set any endpoint configured timeouts
    if (getConfiguration().getConnectTimeout() > -1) {
        client.setConnectTimeout(getConfiguration().getConnectTimeout());
    }
    if (getConfiguration().getSoTimeout() > -1) {
        soTimeout = getConfiguration().getSoTimeout();
    }
    dataTimeout = getConfiguration().getTimeout();

    // then lookup ftp client parameters and set those
    if (ftpClientParameters != null) {
        // setting soTimeout has to be done later on FTPClient (after it has connected)
        Object timeout = ftpClientParameters.remove("soTimeout");
        if (timeout != null) {
            soTimeout = getCamelContext().getTypeConverter().convertTo(int.class, timeout);
        }
        // and we want to keep data timeout so we can log it later
        timeout = ftpClientParameters.remove("dataTimeout");
        if (timeout != null) {
            dataTimeout = getCamelContext().getTypeConverter().convertTo(int.class, dataTimeout);
        }
        IntrospectionSupport.setProperties(client, ftpClientParameters);
    }

    if (ftpClientConfigParameters != null) {
        // client config is optional so create a new one if we have parameter for it
        if (ftpClientConfig == null) {
            ftpClientConfig = new FTPClientConfig();
        }
        IntrospectionSupport.setProperties(ftpClientConfig, ftpClientConfigParameters);
    }

    if (dataTimeout > 0) {
        client.setDataTimeout(dataTimeout);
    }

    if (log.isDebugEnabled()) {
        log.debug("Created FTPClient [connectTimeout: {}, soTimeout: {}, dataTimeout: {}]: {}",
                new Object[] { client.getConnectTimeout(), getSoTimeout(), dataTimeout, client });
    }

    Ftp2Operations operations = new Ftp2Operations(client, getFtpClientConfig());
    operations.setEndpoint(this);
    return operations;
}

From source file:com.jaeksoft.searchlib.crawler.file.process.fileInstances.FtpFileInstance.java

protected FTPClient ftpConnect() throws SocketException, IOException, NoSuchAlgorithmException {
    FilePathItem fpi = getFilePathItem();
    FTPClient ftp = null;
    try {//ww w  .j av a2  s. c o  m
        ftp = new FTPClient();
        // For debug
        // f.addProtocolCommandListener(new PrintCommandListener(
        // new PrintWriter(System.out)));
        ftp.setConnectTimeout(120000);
        ftp.setControlKeepAliveTimeout(180);
        ftp.setDataTimeout(120000);
        ftp.connect(fpi.getHost());
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException("FTP Error Code: " + reply);
        ftp.login(fpi.getUsername(), fpi.getPassword());
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException("FTP Error Code: " + reply);
        if (fpi.isFtpUsePassiveMode())
            ftp.enterLocalPassiveMode();
        if (!FTPReply.isPositiveCompletion(reply))
            throw new IOException("FTP Error Code: " + reply);
        FTPClient ftpReturn = ftp;
        ftp = null;
        return ftpReturn;
    } finally {
        if (ftp != null)
            ftpQuietDisconnect(ftp);
    }
}

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

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

    try {/*  w ww . j  ava  2  s . c  om*/
        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:com.jaeksoft.searchlib.scheduler.task.TaskFtpXmlFeed.java

private void checkConnect(FTPClient ftp, String server, String login, String password) throws IOException {
    try {//  w  ww .  j  av a2s.co m
        if (ftp.isConnected())
            if (ftp.sendNoOp())
                return;
    } catch (FTPConnectionClosedException e) {
        Logging.warn(e);
    }
    ftp.setConnectTimeout(120000);
    ftp.setControlKeepAliveTimeout(180);
    ftp.setDataTimeout(120000);
    ftp.connect(server);
    ftp.login(login, password);
}

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);
    client.setDefaultTimeout(timeout);/* ww  w  .j  a  v  a 2  s . c om*/
    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.mirth.connect.connectors.file.filesystems.FtpConnection.java

public FtpConnection(String host, int port, FileSystemConnectionOptions fileSystemOptions, boolean passive,
        int timeout, FTPClient client) throws Exception {
    this.client = client;
    // This sets the timeout for read operations on data sockets. It does not affect write operations.
    client.setDataTimeout(timeout);/* w w w . j a va 2  s  . c o m*/

    // This sets the timeout for the initial connection.
    client.setConnectTimeout(timeout);

    try {
        if (port > 0) {
            client.connect(host, port);
        } else {
            client.connect(host);
        }

        // This sets the timeout for read operations on the command socket. As per JavaDoc comments, you should only call this after the connection has been opened by connect()
        client.setSoTimeout(timeout);

        if (!FTPReply.isPositiveCompletion(client.getReplyCode())) {
            throw new IOException("Ftp error: " + client.getReplyCode());
        }
        if (!client.login(fileSystemOptions.getUsername(), fileSystemOptions.getPassword())) {
            throw new IOException("Ftp error: " + client.getReplyCode());
        }
        if (!client.setFileType(FTP.BINARY_FILE_TYPE)) {
            throw new IOException("Ftp error");
        }

        initialize();

        if (passive) {
            client.enterLocalPassiveMode();
        }
    } catch (Exception e) {
        if (client.isConnected()) {
            client.disconnect();
        }
        throw e;
    }
}

From source file:hydrograph.engine.spark.datasource.utils.FTPUtil.java

public void download(RunFileTransferEntity runFileTransferEntity) {
    log.debug("Start FTPUtil download");

    File filecheck = new File(runFileTransferEntity.getOutFilePath());
    if (!(filecheck.exists() && filecheck.isDirectory())
            && !(runFileTransferEntity.getOutFilePath().contains("hdfs://"))) {
        log.error("Invalid output file path. Please provide valid output file path.");
        throw new RuntimeException("Invalid output path");
    }/*from ww w  .  ja v a2s . co m*/
    boolean fail_if_exist = false;
    FTPClient ftpClient = new FTPClient();
    int retryAttempt = runFileTransferEntity.getRetryAttempt();
    int attemptCount = 1;
    int i = 0;
    boolean login = false;
    boolean done = false;
    for (i = 0; i < retryAttempt; i++) {
        try {
            log.info("Connection attempt: " + (i + 1));
            if (runFileTransferEntity.getTimeOut() != 0)
                ftpClient.setConnectTimeout(runFileTransferEntity.getTimeOut());
            log.debug("connection details: " + "/n" + "Username: " + runFileTransferEntity.getUserName() + "/n"
                    + "HostName " + runFileTransferEntity.getHostName() + "/n" + "Portno"
                    + runFileTransferEntity.getPortNo());
            ftpClient.connect(runFileTransferEntity.getHostName(), runFileTransferEntity.getPortNo());

            login = ftpClient.login(runFileTransferEntity.getUserName(), runFileTransferEntity.getPassword());

            if (!login) {
                log.error("Invalid FTP details provided. Please provide correct FTP details.");
                throw new FTPUtilException("Invalid FTP details");
            }
            ftpClient.enterLocalPassiveMode();
            if (runFileTransferEntity.getEncoding() != null)
                ftpClient.setControlEncoding(runFileTransferEntity.getEncoding());
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (runFileTransferEntity.getOutFilePath().contains("hdfs://")) {
                log.debug("Processing for HDFS output path");
                String outputPath = runFileTransferEntity.getOutFilePath();
                String s1 = outputPath.substring(7, outputPath.length());
                String s2 = s1.substring(0, s1.indexOf("/"));
                File f = new File("/tmp");
                if (!f.exists()) {
                    f.mkdir();
                }

                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);

                File isfile = new File(runFileTransferEntity.getOutFilePath() + "\\" + file_name);
                if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) {

                    OutputStream outputStream = new FileOutputStream("/tmp/" + file_name);
                    done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                    outputStream.close();
                } else {
                    if (!(isfile.exists() && !isfile.isDirectory())) {
                        OutputStream outputStream = new FileOutputStream("/tmp/" + file_name);

                        done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                        outputStream.close();
                    } else {
                        fail_if_exist = true;
                        throw new RuntimeException("File already exists");
                    }
                }

                Configuration conf = new Configuration();
                conf.set("fs.defaultFS", "hdfs://" + s2);
                FileSystem hdfsFileSystem = FileSystem.get(conf);

                String s = outputPath.substring(7, outputPath.length());
                String hdfspath = s.substring(s.indexOf("/"), s.length());

                Path local = new Path("/tmp/" + file_name);
                Path hdfs = new Path(hdfspath);
                hdfsFileSystem.copyFromLocalFile(local, hdfs);

            } else {
                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);

                File isfile = new File(runFileTransferEntity.getOutFilePath() + File.separatorChar + file_name);
                if (runFileTransferEntity.getOverwrite().equalsIgnoreCase("Overwrite If Exists")) {

                    OutputStream outputStream = new FileOutputStream(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/") + "/" + file_name);
                    done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), (outputStream));
                    outputStream.close();
                } else {

                    if (!(isfile.exists() && !isfile.isDirectory())) {

                        OutputStream outputStream = new FileOutputStream(
                                runFileTransferEntity.getOutFilePath().replaceAll(
                                        Matcher.quoteReplacement("\\"), "/") + File.separatorChar + file_name);

                        done = ftpClient.retrieveFile(runFileTransferEntity.getInputFilePath(), outputStream);
                        outputStream.close();
                    } else {
                        fail_if_exist = true;
                        Log.error("File already exits");
                        throw new FTPUtilException("File already exists");

                    }

                }
            }
        } catch (Exception e) {
            log.error("error while transferring the file", e);
            if (!login) {
                log.error("Login ");

                throw new FTPUtilException("Invalid FTP details");
            }
            if (fail_if_exist) {
                log.error("File already exists ");
                throw new FTPUtilException("File already exists");
            }
            try {
                Thread.sleep(runFileTransferEntity.getRetryAfterDuration());
            } catch (Exception e1) {
                Log.error("Exception occured during sleep");
            } catch (Error err) {
                log.error("fatal error", e);
                throw new FTPUtilException(err);
            }
            continue;
        }

        break;

    }

    if (i == runFileTransferEntity.getRetryAttempt()) {

        try {
            if (ftpClient != null) {
                ftpClient.logout();
                ftpClient.disconnect();

            }
        } catch (Exception e) {

            Log.error("Exception while closing the ftp client", e);
        }
        if (runFileTransferEntity.getFailOnError())
            throw new FTPUtilException("File transfer failed ");

    }

    log.debug("Finished FTPUtil download");

}