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:fr.acxio.tools.agia.ftp.DefaultFtpClientFactory.java

public FTPClient getFtpClient() throws IOException {
    FTPClient aClient = new FTPClient();

    // Debug output
    // aClient.addProtocolCommandListener(new PrintCommandListener(new
    // PrintWriter(System.out), true));

    if (activeExternalIPAddress != null) {
        aClient.setActiveExternalIPAddress(activeExternalIPAddress);
    }/*w  ww  .j av a  2  s . c o  m*/
    if (activeMinPort != null && activeMaxPort != null) {
        aClient.setActivePortRange(activeMinPort, activeMaxPort);
    }
    if (autodetectUTF8 != null) {
        aClient.setAutodetectUTF8(autodetectUTF8);
    }
    if (bufferSize != null) {
        aClient.setBufferSize(bufferSize);
    }
    if (charset != null) {
        aClient.setCharset(charset);
    }
    if (connectTimeout != null) {
        aClient.setConnectTimeout(connectTimeout);
    }
    if (controlEncoding != null) {
        aClient.setControlEncoding(controlEncoding);
    }
    if (controlKeepAliveReplyTimeout != null) {
        aClient.setControlKeepAliveReplyTimeout(controlKeepAliveReplyTimeout);
    }
    if (controlKeepAliveTimeout != null) {
        aClient.setControlKeepAliveTimeout(controlKeepAliveTimeout);
    }
    if (dataTimeout != null) {
        aClient.setDataTimeout(dataTimeout);
    }
    if (defaultPort != null) {
        aClient.setDefaultPort(defaultPort);
    }
    if (defaultTimeout != null) {
        aClient.setDefaultTimeout(defaultTimeout);
    }
    if (fileStructure != null) {
        aClient.setFileStructure(fileStructure);
    }
    if (keepAlive != null) {
        aClient.setKeepAlive(keepAlive);
    }
    if (listHiddenFiles != null) {
        aClient.setListHiddenFiles(listHiddenFiles);
    }
    if (parserFactory != null) {
        aClient.setParserFactory(parserFactory);
    }
    if (passiveLocalIPAddress != null) {
        aClient.setPassiveLocalIPAddress(passiveLocalIPAddress);
    }
    if (passiveNatWorkaround != null) {
        aClient.setPassiveNatWorkaround(passiveNatWorkaround);
    }
    if (proxy != null) {
        aClient.setProxy(proxy);
    }
    if (receieveDataSocketBufferSize != null) {
        aClient.setReceieveDataSocketBufferSize(receieveDataSocketBufferSize);
    }
    if (receiveBufferSize != null) {
        aClient.setReceiveBufferSize(receiveBufferSize);
    }
    if (remoteVerificationEnabled != null) {
        aClient.setRemoteVerificationEnabled(remoteVerificationEnabled);
    }
    if (reportActiveExternalIPAddress != null) {
        aClient.setReportActiveExternalIPAddress(reportActiveExternalIPAddress);
    }
    if (sendBufferSize != null) {
        aClient.setSendBufferSize(sendBufferSize);
    }
    if (sendDataSocketBufferSize != null) {
        aClient.setSendDataSocketBufferSize(sendDataSocketBufferSize);
    }
    if (strictMultilineParsing != null) {
        aClient.setStrictMultilineParsing(strictMultilineParsing);
    }
    if (tcpNoDelay != null) {
        aClient.setTcpNoDelay(tcpNoDelay);
    }
    if (useEPSVwithIPv4 != null) {
        aClient.setUseEPSVwithIPv4(useEPSVwithIPv4);
    }

    if (systemKey != null) {
        FTPClientConfig aClientConfig = new FTPClientConfig(systemKey);
        if (defaultDateFormat != null) {
            aClientConfig.setDefaultDateFormatStr(defaultDateFormat);
        }
        if (recentDateFormat != null) {
            aClientConfig.setRecentDateFormatStr(recentDateFormat);
        }
        if (serverLanguageCode != null) {
            aClientConfig.setServerLanguageCode(serverLanguageCode);
        }
        if (shortMonthNames != null) {
            aClientConfig.setShortMonthNames(shortMonthNames);
        }
        if (serverTimeZoneId != null) {
            aClientConfig.setServerTimeZoneId(serverTimeZoneId);
        }
        aClient.configure(aClientConfig);
    }

    if (LOGGER.isInfoEnabled()) {
        LOGGER.info("Connecting to : {}", host);
    }

    if (port == null) {
        aClient.connect(host);
    } else {
        aClient.connect(host, port);
    }

    int aReplyCode = aClient.getReplyCode();

    if (!FTPReply.isPositiveCompletion(aReplyCode)) {
        aClient.disconnect();
        throw new IOException("Cannot connect to " + host + ". Returned code : " + aReplyCode);
    }

    try {
        if (localPassiveMode) {
            aClient.enterLocalPassiveMode();
        }

        boolean aIsLoggedIn = false;
        if (account == null) {
            aIsLoggedIn = aClient.login(username, password);
        } else {
            aIsLoggedIn = aClient.login(username, password, account);
        }
        if (!aIsLoggedIn) {
            throw new IOException(aClient.getReplyString());
        }
    } catch (IOException e) {
        aClient.disconnect();
        throw e;
    }

    if (fileTransferMode != null) {
        aClient.setFileTransferMode(fileTransferMode);
    }
    if (fileType != null) {
        aClient.setFileType(fileType);
    }

    return aClient;
}

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

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

    FTPClient ftpClient = new FTPClient();
    ftpClient.enterLocalPassiveMode();// w  w  w.j a  va 2s  .c o m
    ftpClient.setBufferSize(1024000);

    int retryAttempt = runFileTransferEntity.getRetryAttempt();
    int attemptCount = 1;
    int i = 0;

    InputStream inputStream = null;
    boolean login = false;
    File filecheck = new File(runFileTransferEntity.getInputFilePath());
    log.info("input file name" + filecheck.getName());
    if (runFileTransferEntity.getFailOnError()) {
        if (!(filecheck.isFile() || filecheck.isDirectory())
                && !(runFileTransferEntity.getInputFilePath().contains("hdfs://"))) {
            log.error("Invalid input file path. Please provide valid input file path.");
            throw new FTPUtilException("Invalid input file path");
        }
    }

    boolean done = false;
    for (i = 0; i < retryAttempt; i++) {
        try {
            log.info("Connection attempt: " + (i + 1));
            if (runFileTransferEntity.getTimeOut() != 0)
                if (runFileTransferEntity.getEncoding() != null)
                    ftpClient.setControlEncoding(runFileTransferEntity.getEncoding());
            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();
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (runFileTransferEntity.getInputFilePath().contains("hdfs://")) {
                log.debug("Processing for HDFS input file path");
                String inputPath = runFileTransferEntity.getInputFilePath();

                String s1 = inputPath.substring(7, inputPath.length());

                String s2 = s1.substring(0, s1.indexOf("/"));

                int index = runFileTransferEntity.getInputFilePath()
                        .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');

                String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);

                File f = new File("/tmp");
                if (!f.exists())
                    f.mkdir();
                Configuration conf = new Configuration();
                conf.set("fs.defaultFS", "hdfs://" + s2);
                FileSystem hdfsFileSystem = FileSystem.get(conf);
                Path local = new Path("/tmp");
                String s = inputPath.substring(7, inputPath.length());
                String hdfspath = s.substring(s.indexOf("/"), s.length());
                File dir = new File(hdfspath);
                Random ran = new Random();
                String tempFolder = "ftp_sftp_" + System.nanoTime() + "_" + ran.nextInt(1000);
                File dirs = new File("/tmp/" + tempFolder);
                boolean success = dirs.mkdirs();
                if (hdfsFileSystem.isDirectory(new Path(hdfspath))) {
                    log.debug("Provided HDFS input path is for directory.");
                    InputStream is = null;
                    OutputStream os = null;
                    String localDirectory = hdfspath.substring(hdfspath.lastIndexOf("/") + 1);
                    FileStatus[] fileStatus = hdfsFileSystem
                            .listStatus(new Path(runFileTransferEntity.getInputFilePath()));
                    Path[] paths = FileUtil.stat2Paths(fileStatus);
                    try {
                        String folderName = hdfspath.substring(hdfspath.lastIndexOf("/") + 1);
                        Path hdfs = new Path(hdfspath);
                        for (Path file : paths) {
                            is = hdfsFileSystem.open(file);
                            os = new BufferedOutputStream(
                                    new FileOutputStream(dirs + "" + File.separatorChar + file.getName()));
                            IOUtils.copyBytes(is, os, conf);
                        }
                        ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath()
                                .replaceAll(Matcher.quoteReplacement("\\"), "/"));
                        ftpClient.removeDirectory(folderName);
                        ftpClient.makeDirectory(folderName);
                        ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath().replaceAll(
                                Matcher.quoteReplacement("\\"), "/") + File.separatorChar + folderName);
                        for (File files : dirs.listFiles()) {

                            if (files.isFile())
                                ftpClient.storeFile(files.getName().toString(),
                                        new BufferedInputStream(new FileInputStream(files)));

                        }
                    } catch (IOException e) {
                        log.error("Failed while doing FTP file", e);
                        //throw e;
                    } finally {
                        IOUtils.closeStream(is);
                        IOUtils.closeStream(os);
                        if (dirs != null) {
                            FileUtils.deleteDirectory(dirs);
                        }
                    }
                } else {
                    try {
                        Path hdfs = new Path(hdfspath);
                        hdfsFileSystem.copyToLocalFile(false, hdfs, local);
                        inputStream = new FileInputStream(dirs + file_name);
                        ftpClient.storeFile(file_name, new BufferedInputStream(inputStream));
                    } catch (Exception e) {
                        log.error("Failed while doing FTP file", e);
                        throw new FTPUtilException("Failed while doing FTP file", e);
                    } finally {
                        FileUtils.deleteDirectory(dirs);
                    }
                }
            } else {
                java.nio.file.Path file = new File(runFileTransferEntity.getInputFilePath()).toPath();
                if (Files.isDirectory(file)) {
                    log.debug("Provided input file path is for directory");
                    File dir = new File(runFileTransferEntity.getInputFilePath());
                    String folderName = new File(runFileTransferEntity.getInputFilePath()).getName();
                    ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/"));
                    try {
                        ftpClient.removeDirectory(folderName);
                    } catch (IOException e) {
                        log.error("Failed while doing FTP file", e);
                        throw new FTPUtilException("Failed while doing FTP file", e);
                    }
                    ftpClient.makeDirectory(folderName);

                    ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/") + "/" + folderName);
                    for (File files : dir.listFiles()) {

                        if (files.isFile())
                            ftpClient.storeFile(files.getName().toString(),
                                    new BufferedInputStream(new FileInputStream(files)));
                    }
                } else {

                    inputStream = new FileInputStream(runFileTransferEntity.getInputFilePath());
                    ftpClient.changeWorkingDirectory(runFileTransferEntity.getOutFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/"));
                    int index = runFileTransferEntity.getInputFilePath()
                            .replaceAll(Matcher.quoteReplacement("\\"), "/").lastIndexOf('/');
                    String file_name = runFileTransferEntity.getInputFilePath().substring(index + 1);
                    ftpClient.storeFile(file_name, new BufferedInputStream(inputStream));
                }

            }
        } catch (Exception e) {
            log.error("Failed while doing FTP file", e);
            if (!login && runFileTransferEntity.getFailOnError()) {
                throw new FTPUtilException("Invalid FTP details");
            }
            try {
                Thread.sleep(runFileTransferEntity.getRetryAfterDuration());
            } catch (Exception e1) {
                log.error("Failed while sleeping for retry duration", e1);
            }
            continue;
        } finally {
            try {
                if (inputStream != null)
                    inputStream.close();
            } catch (IOException ioe) {

            }
        }
        done = true;
        break;
    }

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

        }
    } catch (Exception e) {
        log.error("Failed while clossing the connection", e);
    } catch (Error e) {
        log.error("Failed while clossing the connection", e);
        //throw new RuntimeException(e);
    }

    if (runFileTransferEntity.getFailOnError() && !done) {
        log.error("File transfer failed");
        throw new FTPUtilException("File transfer failed");
    } else if (!done) {
        log.error("File transfer failed but mentioned fail on error as false");
    }
    log.debug("Finished FTPUtil upload");
}

From source file:com.ut.healthelink.service.impl.transactionOutManagerImpl.java

/**
 * The 'FTPTargetFile' function will get the FTP details and send off the generated file
 *
 * @param batchId The id of the batch to FTP the file for
 *///from  w  w  w. j  a  v a 2 s.  com
private void FTPTargetFile(int batchId, configurationTransport transportDetails) throws Exception {

    try {

        /* Update the status of the batch to locked */
        transactionOutDAO.updateBatchStatus(batchId, 22);

        List<transactionTarget> targets = transactionOutDAO.getTransactionsByBatchDLId(batchId);

        if (!targets.isEmpty()) {

            for (transactionTarget target : targets) {

                /* Need to update the uploaded batch status */
                transactionInManager.updateBatchStatus(target.getbatchUploadId(), 22, "");

                /* Need to update the uploaded batch transaction status */
                transactionInManager.updateTransactionStatus(target.getbatchUploadId(),
                        target.gettransactionInId(), 0, 37);

                /* Update the downloaded batch transaction status */
                transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 37);

            }

        }

        /* get the batch details */
        batchDownloads batchFTPFileInfo = transactionOutDAO.getBatchDetails(batchId);

        /* Get the FTP Details */
        configurationFTPFields ftpDetails = configurationTransportManager
                .getTransportFTPDetailsPush(transportDetails.getId());

        if ("SFTP".equals(ftpDetails.getprotocol())) {

            JSch jsch = new JSch();
            Session session = null;
            ChannelSftp channel = null;
            FileInputStream localFileStream = null;

            String user = ftpDetails.getusername();
            int port = ftpDetails.getport();
            String host = ftpDetails.getip();

            Organization orgDetails = organizationManager.getOrganizationById(
                    configurationManager.getConfigurationById(transportDetails.getconfigId()).getorgId());

            if (ftpDetails.getcertification() != null && !"".equals(ftpDetails.getcertification())) {

                File newFile = null;

                fileSystem dir = new fileSystem();
                dir.setDir(orgDetails.getcleanURL(), "certificates");

                jsch.addIdentity(new File(dir.getDir() + ftpDetails.getcertification()).getAbsolutePath());
                session = jsch.getSession(user, host, port);
            } else if (ftpDetails.getpassword() != null && !"".equals(ftpDetails.getpassword())) {
                session = jsch.getSession(user, host, port);
                session.setPassword(ftpDetails.getpassword());
            }

            session.setConfig("StrictHostKeyChecking", "no");
            session.setTimeout(2000);

            session.connect();

            channel = (ChannelSftp) session.openChannel("sftp");

            channel.connect();

            if (ftpDetails.getdirectory() != null && !"".equals(ftpDetails.getdirectory())) {
                channel.cd(ftpDetails.getdirectory());

                String fileName = null;

                int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf(".");

                if (findExt >= 0) {
                    fileName = batchFTPFileInfo.getoutputFIleName();
                } else {
                    fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".")
                            .append(transportDetails.getfileExt()).toString();
                }

                //Set the directory to save the brochures to
                fileSystem dir = new fileSystem();

                String filelocation = transportDetails.getfileLocation();
                filelocation = filelocation.replace("/bowlink/", "");
                dir.setDirByName(filelocation);

                File file = new File(dir.getDir() + fileName);

                if (file.exists()) {
                    FileInputStream fileInput = new FileInputStream(file);

                    channel.put(fileInput, fileName);
                }

            }

            channel.disconnect();
            session.disconnect();

        } else {
            FTPClient ftp;

            if ("FTP".equals(ftpDetails.getprotocol())) {
                ftp = new FTPClient();
            } else {
                FTPSClient ftps;
                ftps = new FTPSClient(true);

                ftp = ftps;
                ftps.setTrustManager(null);
            }

            ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            ftp.setDefaultTimeout(3000);
            ftp.setConnectTimeout(3000);

            if (ftpDetails.getport() > 0) {
                ftp.connect(ftpDetails.getip(), ftpDetails.getport());
            } else {
                ftp.connect(ftpDetails.getip());
            }

            int reply = ftp.getReplyCode();

            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
            } else {
                ftp.login(ftpDetails.getusername(), ftpDetails.getpassword());

                ftp.enterLocalPassiveMode();

                String fileName = null;

                int findExt = batchFTPFileInfo.getoutputFIleName().lastIndexOf(".");

                if (findExt >= 0) {
                    fileName = batchFTPFileInfo.getoutputFIleName();
                } else {
                    fileName = new StringBuilder().append(batchFTPFileInfo.getoutputFIleName()).append(".")
                            .append(transportDetails.getfileExt()).toString();
                }

                //Set the directory to save the brochures to
                fileSystem dir = new fileSystem();

                String filelocation = transportDetails.getfileLocation();
                filelocation = filelocation.replace("/bowlink/", "");
                dir.setDirByName(filelocation);

                File file = new File(dir.getDir() + fileName);

                FileInputStream fileInput = new FileInputStream(file);

                ftp.changeWorkingDirectory(ftpDetails.getdirectory());
                ftp.storeFile(fileName, fileInput);
                ftp.logout();
                ftp.disconnect();

            }
        }

        // we should delete file now that we ftp'ed the file
        try {
            fileSystem dir = new fileSystem();
            String filelocation = transportDetails.getfileLocation();
            filelocation = filelocation.replace("/bowlink/", "");
            dir.setDirByName(filelocation);

            File sourceFile = new File(dir.getDir() + batchFTPFileInfo.getoutputFIleName());
            if (sourceFile.exists()) {
                sourceFile.delete();
            }

            transactionOutDAO.updateBatchStatus(batchId, 23);

            for (transactionTarget target : targets) {

                /* Need to update the uploaded batch status */
                transactionInManager.updateBatchStatus(target.getbatchUploadId(), 23, "");

                /* Need to update the uploaded batch transaction status */
                transactionInManager.updateTransactionStatus(target.getbatchUploadId(),
                        target.gettransactionInId(), 0, 20);

                /* Update the downloaded batch transaction status */
                transactionOutDAO.updateTargetTransasctionStatus(target.getbatchDLId(), 20);

            }

        } catch (Exception e) {
            throw new Exception(
                    "Error occurred during FTP - delete file and update statuses. batchId: " + batchId, e);

        }
    } catch (Exception e) {
        throw new Exception("Error occurred trying to FTP a batch target. batchId: " + batchId, e);
    }

}

From source file:net.yacy.grid.io.assets.FTPStorageFactory.java

public FTPStorageFactory(String server, int port, String username, String password, boolean deleteafterread)
        throws IOException {
    this.server = server;
    this.username = username == null ? "" : username;
    this.password = password == null ? "" : password;
    this.port = port;
    this.deleteafterread = deleteafterread;

    this.ftpClient = new Storage<byte[]>() {

        @Override//from   w  w w  .j  av  a  2 s. c o m
        public void checkConnection() throws IOException {
            return;
        }

        private FTPClient initConnection() throws IOException {
            FTPClient ftp = new FTPClient();
            ftp.setDataTimeout(3000);
            ftp.setConnectTimeout(20000);
            if (FTPStorageFactory.this.port < 0 || FTPStorageFactory.this.port == DEFAULT_PORT) {
                ftp.connect(FTPStorageFactory.this.server);
            } else {
                ftp.connect(FTPStorageFactory.this.server, FTPStorageFactory.this.port);
            }
            ftp.enterLocalPassiveMode(); // the server opens a data port to which the client conducts data transfers
            int reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("bad connection to ftp server: " + reply);
            }
            if (!ftp.login(FTPStorageFactory.this.username, FTPStorageFactory.this.password)) {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
                throw new IOException("login failure");
            }
            ftp.setFileType(FTP.BINARY_FILE_TYPE);
            ftp.setBufferSize(8192);
            return ftp;
        }

        @Override
        public StorageFactory<byte[]> store(String path, byte[] asset) throws IOException {
            long t0 = System.currentTimeMillis();
            FTPClient ftp = initConnection();
            try {
                long t1 = System.currentTimeMillis();
                String file = cdPath(ftp, path);
                long t2 = System.currentTimeMillis();
                ftp.enterLocalPassiveMode();
                boolean success = ftp.storeFile(file, new ByteArrayInputStream(asset));
                long t3 = System.currentTimeMillis();
                if (!success)
                    throw new IOException("storage to path " + path + " was not successful (storeFile=false)");
                Data.logger.debug("FTPStorageFactory.store ftp store successfull: check connection = "
                        + (t1 - t0) + ", cdPath = " + (t2 - t1) + ", store = " + (t3 - t2));
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return FTPStorageFactory.this;
        }

        @Override
        public Asset<byte[]> load(String path) throws IOException {
            FTPClient ftp = initConnection();
            ByteArrayOutputStream baos = null;
            byte[] b = null;
            try {
                String file = cdPath(ftp, path);
                baos = new ByteArrayOutputStream();
                ftp.retrieveFile(file, baos);
                b = baos.toByteArray();
                if (FTPStorageFactory.this.deleteafterread)
                    try {
                        boolean deleted = ftp.deleteFile(file);
                        FTPFile[] remaining = ftp.listFiles();
                        if (remaining.length == 0) {
                            ftp.cwd("/");
                            if (path.startsWith("/"))
                                path = path.substring(1);
                            int p = path.indexOf('/');
                            if (p > 0)
                                path = path.substring(0, p);
                            ftp.removeDirectory(path);
                        }
                    } catch (Throwable e) {
                        Data.logger.warn("FTPStorageFactory.load failed to remove asset " + path, e);
                    }
            } catch (IOException e) {
                throw e;
            } finally {
                if (ftp != null)
                    try {
                        ftp.disconnect();
                    } catch (Throwable ee) {
                    }
            }
            return new Asset<byte[]>(FTPStorageFactory.this, b);
        }

        @Override
        public void close() {
        }

        private String cdPath(FTPClient ftp, String path) throws IOException {
            int success_code = ftp.cwd("/");
            if (success_code >= 300)
                throw new IOException("cannot cd into " + path + ": " + success_code);
            if (path.length() == 0 || path.equals("/"))
                return "";
            if (path.charAt(0) == '/')
                path = path.substring(1); // we consider that all paths are absolute to / (home)
            int p;
            while ((p = path.indexOf('/')) > 0) {
                String dir = path.substring(0, p);
                int code = ftp.cwd(dir);
                if (code >= 300) {
                    // path may not exist, try to create the path
                    boolean success = ftp.makeDirectory(dir);
                    if (!success)
                        throw new IOException("unable to create directory " + dir + " for path " + path);
                    code = ftp.cwd(dir);
                    if (code >= 300)
                        throw new IOException("unable to cwd into directory " + dir + " for path " + path);
                }
                path = path.substring(p + 1);
            }
            return path;
        }
    };
}

From source file:no.imr.sea2data.stox.InstallerUtil.java

public static Boolean retrieveFromFTP(String ftpPath, String outFile, FTPFileFilter filter) {
    try {//  www . j a  v  a  2  s  . c om
        FTPClient ftpClient = new FTPClient();
        // pass directory path on server to connect
        if (ftpPath == null) {
            return false;
        }
        ftpPath = ftpPath.replace("ftp://", "");
        String[] s = ftpPath.split("/", 2);
        if (s.length != 2) {
            return false;
        }
        String server = s[0];
        String subPath = s[1];
        ftpClient.setConnectTimeout(5000);
        ftpClient.connect(server);
        ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
        if (!ftpClient.login("anonymous", "")) {
            return false;
        }
        ftpClient.enterLocalPassiveMode(); // bug : mac doesnt allow ftp server connect through through local firewall - thus use passive server
        try (FileOutputStream fos = new FileOutputStream(outFile)) {
            try {
                String path = subPath + "/";
                FTPFile[] files = ftpClient.listFiles(path, filter);
                Optional<FTPFile> opt = Arrays.stream(files)
                        .sorted((f1, f2) -> Integer.compare(f1.getName().length(), f2.getName().length()))
                        .findFirst();
                if (opt.isPresent()) {
                    ftpClient.retrieveFile(path + opt.get().getName(), fos);
                }
            } finally {
                ftpClient.logout();
                ftpClient.disconnect();
            }
        }
        return true;
    } catch (IOException ex) {
        throw new UncheckedIOException(ex);
    }
}

From source file:org.apache.camel.component.file.remote.FtpEndpoint.java

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   ww  w.java  2 s .  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) {
        Map<String, Object> localParameters = new HashMap<String, Object>(ftpClientParameters);
        // setting soTimeout has to be done later on FTPClient (after it has connected)
        Object timeout = localParameters.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 = localParameters.remove("dataTimeout");
        if (timeout != null) {
            dataTimeout = getCamelContext().getTypeConverter().convertTo(int.class, dataTimeout);
        }
        setProperties(client, localParameters);
    }

    if (ftpClientConfigParameters != null) {
        // client config is optional so create a new one if we have parameter for it
        if (ftpClientConfig == null) {
            ftpClientConfig = new FTPClientConfig();
        }
        Map<String, Object> localConfigParameters = new HashMap<String, Object>(ftpClientConfigParameters);
        setProperties(ftpClientConfig, localConfigParameters);
    }

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

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

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

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

/**
 * Uses FTPClient to obtain the IOR string from the provided URL via FTP.
 *///from  ww w . j  ava 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.jumpmind.metl.core.runtime.resource.FtpDirectory.java

protected FTPClient createClient() {
    FTPClient ftpClient = new FTPClient();
    FTPClientConfig config = new FTPClientConfig();
    ftpClient.configure(config);//from ww  w .  j  a va2 s  . c o  m

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

}

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);
    ftp.setDataTimeout(3000);/*from  ww w  . jav  a 2 s.c  o m*/
    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);
    ftp.setDataTimeout(3000);/*from w w  w. ja v  a2 s  .c o  m*/
    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;
}