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:lucee.runtime.net.ftp.FTPWrap.java

static void setConnectionSettings(FTPClient client, FTPConnection conn) {
    if (client == null)
        return;/*w  w  w .  j a  va  2  s . c  o m*/

    // timeout
    client.setDataTimeout(conn.getTimeout() * 1000);
    try {
        client.setSoTimeout(conn.getTimeout() * 1000);
    } catch (Throwable t) {
    }

    // passive/active Mode
    int mode = client.getDataConnectionMode();
    if (conn.isPassive()) {
        if (FTPClient.PASSIVE_LOCAL_DATA_CONNECTION_MODE != mode)
            client.enterLocalPassiveMode();
    } else {
        if (FTPClient.ACTIVE_LOCAL_DATA_CONNECTION_MODE != mode)
            client.enterLocalActiveMode();
    }
}

From source file:com.ephesoft.dcma.util.FTPUtil.java

/**
 * API for creating connection to ftp server.
 * //from   w  ww  .ja  v  a2  s .com
 * @param client {@link FTPClient} the ftp client instance
 * @throws SocketException generate if any error occurs while making the connection.
 * @throws IOException generate if any error occur while making the connection.
 */
public static void createConnection(final FTPClient client, final String ftpServerURL, final String ftpUsername,
        final String ftpPassword, final String ftpDataTimeOut) throws SocketException, IOException {
    client.connect(ftpServerURL);
    client.login(ftpUsername, ftpPassword);
    try {
        int ftpDataTimeOutLocal = Integer.parseInt(ftpDataTimeOut);
        client.setDataTimeout(ftpDataTimeOutLocal);
    } catch (NumberFormatException e) {
        LOGGER.error(EphesoftStringUtil.concatenate("Error occuring in converting ftpDataTimeOut :",
                e.getMessage(), e));
    }
}

From source file:net.siegmar.japtproxy.fetcher.FetcherFtp.java

/**
 * {@inheritDoc}//w w w.  j  a v  a  2  s  .c om
 */
@Override
public FetchedResourceFtp fetch(final URL targetResource, final long lastModified,
        final String originalUserAgent) throws IOException, ResourceUnavailableException {

    final FTPClient ftpClient = new FTPClient();
    ftpClient.setSoTimeout(socketTimeout);
    ftpClient.setDataTimeout(dataTimeout);

    try {
        final String host = targetResource.getHost();
        final String resourceName = targetResource.getPath();

        LOG.debug("Configured FetcherFtp: Host '{}', Resource '{}'", host, resourceName);

        ftpClient.connect(host);
        ftpClient.enterLocalPassiveMode();

        if (!ftpClient.login("anonymous", "japt-proxy")) {
            throw new IOException("Can't login to FTP server");
        }

        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        final FTPFile[] files = ftpClient.listFiles(resourceName);

        if (files.length == 0) {
            throw new ResourceUnavailableException("Resource '" + resourceName + "' not found");
        }

        if (files.length > 1) {
            throw new IOException("Multiple files found");
        }

        final FTPFile file = files[0];

        final FetchedResourceFtp fetchedResourceFtp = new FetchedResourceFtp(ftpClient, file);
        fetchedResourceFtp
                .setModified(lastModified == 0 || lastModified < file.getTimestamp().getTimeInMillis());

        return fetchedResourceFtp;
    } catch (final IOException e) {
        // Closing only in case of an exception - otherwise closed by FetchedResourceFtp
        if (ftpClient.isConnected()) {
            ftpClient.disconnect();
        }

        throw e;
    }
}

From source file:dk.dma.dmiweather.service.FTPLoader.java

/**
 * Check for files every 10 minutes. New files are given to the gridWeatherService
 *///from   w  w w  .  ja v  a2s. co m
@Scheduled(initialDelay = 1000, fixedDelay = 10 * 60 * 1000)
public void checkFiles() {
    log.info("Checking FTP files at DMI.");
    FTPClient client = new FTPClient();
    try {
        client.setDataTimeout(20 * 1000);
        client.setBufferSize(1024 * 1024);
        client.connect(hostname);
        if (client.login("anonymous", "")) {
            try {
                client.enterLocalPassiveMode();
                client.setFileType(FTP.BINARY_FILE_TYPE);
                for (ForecastConfiguration configuration : configurations) {
                    // DMI creates a Newest link once all files have been created
                    if (client.changeWorkingDirectory(configuration.getFolder() + "/Newest")) {
                        if (client.getReplyCode() != 250) {
                            log.error("Did not get reply 250 as expected, got {} ", client.getReplyCode());
                        }
                        String workingDirectory = new File(client.printWorkingDirectory()).getName();
                        String previousNewest = newestDirectories.get(configuration);
                        if (!workingDirectory.equals(previousNewest)) {
                            // a new directory for this configuration is available on the server
                            FTPFile[] listFiles = client.listFiles();
                            List<FTPFile> files = Arrays.stream(listFiles)
                                    .filter(f -> configuration.getFilePattern().matcher(f.getName()).matches())
                                    .collect(Collectors.toList());

                            try {
                                Map<File, Instant> localFiles = transferFilesIfNeeded(client, workingDirectory,
                                        files);
                                gridWeatherService.newFiles(localFiles, configuration);
                            } catch (IOException e) {
                                log.warn("Unable to get new weather files from DMI", e);
                            }

                            if (previousNewest != null) {
                                File previous = new File(tempDirLocation, previousNewest);
                                deleteRecursively(previous);
                            }
                            newestDirectories.put(configuration, workingDirectory);
                        }

                    } else {
                        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
                        log.error("Unable to change ftp directory to {}", configuration.getFolder());
                    }
                }
            } finally {
                try {
                    client.logout();
                } catch (IOException e) {
                    log.info("Failed to logout", e);
                }
            }
        } else {
            gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
            log.error("Unable to login to {}", hostname);
        }

    } catch (IOException e) {
        gridWeatherService.setErrorMessage(ErrorMessage.FTP_PROBLEM);
        log.error("Unable to update weather files from DMI", e);
    } finally {
        try {
            client.disconnect();
        } catch (IOException e) {
            log.info("Failed to disconnect", e);
        }
    }
    log.info("Check completed.");
}

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

private void configureFTPClient(final FTPClient ftpClient) {
    ftpClient.setDefaultTimeout(timeout);
    ftpClient.setDataTimeout(timeout);
    if (controlEncoding != null)
        ftpClient.setControlEncoding(controlEncoding);
}

From source file:com.ephesoft.dcma.ftp.service.FTPServiceImpl.java

/**
 * API for creating connection to ftp server.
 * /*from   ww  w.j a  va  2s .c  o m*/
 * @param client {@link FTPClient} the ftp client instance
 * @throws SocketException if any error occur while making the connection.
 * @throws IOException generate if any error occur while making the connection
 */
private void createConnection(FTPClient client) throws SocketException, IOException {
    client.connect(ftpServerURL);
    client.login(ftpUsername, ftpPassword);
    try {
        int ftpDataTimeOutLocal = Integer.parseInt(ftpDataTimeOut);
        client.setDataTimeout(ftpDataTimeOutLocal);
    } catch (NumberFormatException e) {
        LOGGER.error("Error occuring in converting ftpDataTimeOut :" + e.getMessage(), e);
    }
}

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 {//from  w  w  w.  j  a  v a  2s  .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.jaeksoft.searchlib.scheduler.task.TaskFtpXmlFeed.java

private void checkConnect(FTPClient ftp, String server, String login, String password) throws IOException {
    try {/*from ww  w .j  a  v a2s .c om*/
        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: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);/*w ww .  j  a v a  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: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);

    // This sets the timeout for the initial connection.
    client.setConnectTimeout(timeout);/*from  w  w w .jav a2  s .c  o  m*/

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