Example usage for org.apache.commons.net.ftp FTPSClient FTPSClient

List of usage examples for org.apache.commons.net.ftp FTPSClient FTPSClient

Introduction

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

Prototype

public FTPSClient(boolean isImplicit, SSLContext context) 

Source Link

Document

Constructor for FTPSClient, using #DEFAULT_PROTOCOL - i.e.

Usage

From source file:com.logic.test.FTPSLogic.java

public static void main(String[] args) {
    String serverAdress = "62.2.176.167";
    String username = "RLSFTPRead";
    String password = "ftp4rls";
    int port = 990;
    FTPSClient ftpsClient = new FTPSClient("TLS", true);
    String remoteFile = "REM - Persons Extract.csv";
    File localFile = new File("Persons Extract.csv");

    try {/*from  w  ww . j a v a  2s.c o m*/
        TrustManager[] trustManager = new TrustManager[] { new X509TrustManager() {
            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            @Override
            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        //ftpsClient.setTrustManager(trustManager[0]);
        //KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        //kmf.init(null, null);
        //KeyManager km = kmf.getKeyManagers()[0];

        //ftpsClient.setKeyManager(km);
        ftpsClient.setBufferSize(1024 * 1024);
        ftpsClient.setConnectTimeout(100000);
        ftpsClient.connect(InetAddress.getByName(serverAdress), port);
        ftpsClient.setSoTimeout(100000);

        if (ftpsClient.login(username, password)) {
            ftpsClient.execPBSZ(0);
            ftpsClient.execPROT("P");
            ftpsClient.changeWorkingDirectory("/");
            ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpsClient.enterLocalPassiveMode();

            //ftpsClient.retrieveFile(remoteFile, new FileOutputStream(localFile));
            for (FTPFile file : ftpsClient.listFiles()) {
                System.out.println("Nom " + file.getName());
            }

        }
    } catch (SocketException e) {
        ;
    } catch (UnknownHostException e) {
        ;
    } catch (IOException e) {
        ;
    } catch (Exception e) {
        ;
    } finally {
        try {
            ftpsClient.logout();
        } catch (Exception e2) {
        }

        try {
            ftpsClient.disconnect();
        } catch (Exception e2) {
        }
    }
}

From source file:com.mendhak.gpslogger.senders.ftp.Ftp.java

public static boolean Upload(String server, String username, String password, int port, boolean useFtps,
        String protocol, boolean implicit, InputStream inputStream, String fileName) {
    FTPClient client = null;//  w  w w.j  a  va2s . co  m

    try {
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        Utilities.LogDebug("Connecting to FTP");
        client.connect(server, port);

        Utilities.LogDebug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();

            Utilities.LogDebug("Uploading file to FTP server");

            FTPFile[] existingDirectory = client.listFiles("GPSLogger");

            if (existingDirectory.length <= 0) {
                client.makeDirectory("GPSLogger");
            }

            client.changeWorkingDirectory("GPSLogger");
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            if (result) {
                Utilities.LogDebug("Successfully FTPd file");
            } else {
                Utilities.LogDebug("Failed to FTP file");
            }

        } else {
            Utilities.LogDebug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        Utilities.LogError("Could not connect or upload to FTP server.", e);
    } finally {
        try {
            Utilities.LogDebug("Logging out of FTP server");
            client.logout();

            Utilities.LogDebug("Disconnecting from FTP server");
            client.disconnect();
        } catch (Exception e) {
            Utilities.LogError("Could not logout or disconnect", e);
        }
    }

    return true;
}

From source file:com.geotrackin.gpslogger.senders.ftp.Ftp.java

public synchronized static boolean Upload(String server, String username, String password, String directory,
        int port, boolean useFtps, String protocol, boolean implicit, InputStream inputStream,
        String fileName) {/*w  w w.j  a v  a2s  . com*/
    FTPClient client = null;

    try {
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

    } catch (Exception e) {
        tracer.error("Could not create FTP Client", e);
        return false;
    }

    try {
        tracer.debug("Connecting to FTP");
        client.connect(server, port);
        showServerReply(client);

        tracer.debug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();
            showServerReply(client);

            tracer.debug("Uploading file to FTP server " + server);

            tracer.debug("Checking for FTP directory " + directory);
            FTPFile[] existingDirectory = client.listFiles(directory);
            showServerReply(client);

            if (existingDirectory.length <= 0) {
                tracer.debug("Attempting to create FTP directory " + directory);
                //client.makeDirectory(directory);
                ftpCreateDirectoryTree(client, directory);
                showServerReply(client);

            }

            client.changeWorkingDirectory(directory);
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            showServerReply(client);
            if (result) {
                tracer.debug("Successfully FTPd file " + fileName);
            } else {
                tracer.debug("Failed to FTP file " + fileName);
                return false;
            }

        } else {
            tracer.debug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        tracer.error("Could not connect or upload to FTP server.", e);
        return false;
    } finally {
        try {
            tracer.debug("Logging out of FTP server");
            client.logout();
            showServerReply(client);

            tracer.debug("Disconnecting from FTP server");
            client.disconnect();
            showServerReply(client);
        } catch (Exception e) {
            tracer.error("Could not logout or disconnect", e);
            return false;
        }
    }

    return true;
}

From source file:gov.nih.nci.cacis.ip.mirthconnect.config.IPMirthConfig.java

/**
 * Creates FTPSClient.//from w  ww  . ja  v a  2  s . co m
 *
 * @return FTPSClient
 */
@Bean
@Scope(value = BeanDefinition.SCOPE_PROTOTYPE)
public FTPSClient ftpsCient() {
    return new FTPSClient("TLS", true);
}

From source file:imageuploader.FTPClientExample.java

FTPClientExample(String user, String pass) {
    username = user;
    password = pass;
    ftps = new FTPSClient("TLS", true);
}

From source file:com.mirth.connect.connectors.file.filesystems.FtpsConnection.java

public FtpsConnection(String host, int port, String username, String password, boolean passive, int timeout)
        throws Exception {
    String protocol = "SSL";
    client = new FTPSClient(protocol, true);

    // This sets the timeout for the initial connection.
    client.setConnectTimeout(timeout);/*from   ww w.  j a  v  a2s.  c om*/

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

        // XXX: 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("Ftps error: " + client.getReplyCode());
        }
        if (!client.login(username, password)) {
            throw new IOException("Ftps error: " + client.getReplyCode());
        }
        if (!client.setFileType(FTP.BINARY_FILE_TYPE)) {
            throw new IOException("Ftps error");
        }
        if (passive) {
            client.enterLocalPassiveMode();
        }
    } catch (Exception e) {
        if (client.isConnected()) {
            client.disconnect();
        }
        throw e;
    }
}

From source file:net.seedboxer.common.ftp.FtpUploaderCommons.java

@Override
public void configure(String server, String username, String password, String remotePath, boolean ssl)
        throws Exception {
    if (ssl) {//w  w w  .  j  av a 2 s  .c o m
        this.ftpClient = new FTPSClient("SSL", true);
    } else {
        this.ftpClient = new FTPClient();
    }
    this.server = server;
    this.username = username;
    this.password = password;
    this.remotePath = remotePath;
}

From source file:fr.chaffottem.bonita.connector.ftp.FTPClientConnector.java

protected FTPClient build() {
    final Boolean ftps = (Boolean) getInputParameter(FTPS, false);
    if (!ftps) {/*from ww w  . j  a  v  a  2  s .c om*/
        return new FTPClient();
    } else {
        final String securityProtocol = (String) getInputParameter(SECURITY_PROTOCOL, "TLS");
        final boolean isImplicit = isImplicit();
        return new FTPSClient(securityProtocol, isImplicit);
    }
}

From source file:com.claim.controller.FileTransferController.java

public boolean uploadMutiFilesWithFTPS(ObjFileTransfer ftpObj) throws Exception {
    FTPSClient ftpsClient = null;/* w  w w  .  j  av a  2 s . c om*/
    int replyCode;
    boolean completed = false;
    try {

        FtpProperties properties = new ResourcesProperties().loadFTPProperties();

        try {
            ftpsClient = new FTPSClient(properties.getFtp_protocal(), properties.isFtp_impicit());
            //ftpsClient.setAuthValue(ConstantFtp.FTPS_PROTOCAL);
            ftpsClient.setDataTimeout(ConstantFtp.FTP_TIMEOUT);

            ftpsClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
            System.out.print(ftpsClient.getReplyString());

            ftpsClient.connect(properties.getFtp_server(), properties.getFtp_port());
            FtpUtil.showServerReply(ftpsClient);

        } catch (ConnectException ex) {
            FtpUtil.showServerReply(ftpsClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("ConnectException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (SocketException ex) {
            FtpUtil.showServerReply(ftpsClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("SocketException: " + ex.getMessage());
            ex.printStackTrace();
        } catch (UnknownHostException ex) {
            FtpUtil.showServerReply(ftpsClient);
            Console.LOG(ex.getMessage(), 0);
            System.out.println("UnknownHostException: " + ex.getMessage());
            ex.printStackTrace();
        }

        replyCode = ftpsClient.getReplyCode();
        FtpUtil.showServerReply(ftpsClient);

        if (!FTPReply.isPositiveCompletion(replyCode)) {
            ftpsClient.disconnect();
            Console.LOG("Exception in connecting to FTP Serve ", 0);
            throw new Exception("Exception in connecting to FTP Server");
        } else {
            Console.LOG("Success in connecting to FTP Serve ", 1);
        }

        try {
            boolean success = ftpsClient.login(properties.getFtp_username(), properties.getFtp_password());

            FtpUtil.showServerReply(ftpsClient);
            if (!success) {
                throw new Exception("Could not login to the FTP server.");
            } else {
                Console.LOG("login to the FTP server. Successfully ", 1);
            }
            //ftpClient.enterLocalPassiveMode();
        } catch (FTPConnectionClosedException ex) {
            Console.LOG(ex.getMessage(), 0);
            FtpUtil.showServerReply(ftpsClient);
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        }

        ftpsClient.setFileType(FTP.BINARY_FILE_TYPE);
        ftpsClient.execPBSZ(0);

        //FTP_REMOTE_HOME = ftpClient.printWorkingDirectory();
        String workingDirectoryReportType = properties.getFtp_remote_directory() + File.separator
                + ftpObj.getFtp_report_type();
        FtpUtil.ftpCreateDirectoryTree(ftpsClient, workingDirectoryReportType);
        FtpUtil.showServerReply(ftpsClient);

        String workingDirectoryStmp = workingDirectoryReportType + File.separator + ftpObj.getFtp_stmp();
        FtpUtil.ftpCreateDirectoryTree(ftpsClient, workingDirectoryStmp);
        FtpUtil.showServerReply(ftpsClient);

        // APPROACH #2: uploads second file using an OutputStream
        File files = new File(ftpObj.getFtp_directory_path());

        for (File file : files.listFiles()) {
            if (file.isFile()) {
                System.out.println("file ::" + file.getName());
                InputStream in = new FileInputStream(file);
                ftpsClient.changeWorkingDirectory(workingDirectoryStmp);
                completed = ftpsClient.storeFile(file.getName(), in);
                in.close();
                Console.LOG(
                        "  " + file.getName() + " ",
                        1);
                FtpUtil.showServerReply(ftpsClient);
            }
        }
        Console.LOG(" ?... ", 1);

        //completed = ftpClient.completePendingCommand();
        FtpUtil.showServerReply(ftpsClient);
        completed = true;
        ftpsClient.disconnect();

    } catch (IOException ex) {
        Console.LOG(ex.getMessage(), 0);
        FtpUtil.showServerReply(ftpsClient);
        System.out.println("Error: " + ex.getMessage());
        ex.printStackTrace();
    } finally {
        try {
            if (ftpsClient.isConnected()) {
                ftpsClient.logout();
                ftpsClient.disconnect();
            }
        } catch (IOException ex) {
            FtpUtil.showServerReply(ftpsClient);
            Console.LOG(ex.getMessage(), 0);
            ex.printStackTrace();
        }
    }
    return completed;
}

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

/**
 * Create the FTPS client./*from ww w .  j  a  v a2s . c  o  m*/
 */
protected FTPClient createFtpClient() throws Exception {
    FTPSClient client = null;

    if (sslContextParameters != null) {
        SSLContext context = sslContextParameters.createSSLContext();

        client = new FTPSClient(getFtpsConfiguration().isImplicit(), context);

        // The FTPSClient tries to manage the following SSLSocket related configuration options
        // on its own based on internal configuration options.  FTPSClient does not lend itself
        // to subclassing for the purpose of overriding this behavior (private methods, fields, etc.).
        // As such, we create a socket (preconfigured by SSLContextParameters) from the context
        // we gave to FTPSClient and then setup FTPSClient to reuse the already configured configuration
        // from the socket for all future sockets it creates.  Not sexy and a little brittle, but it works.
        SSLSocket socket = (SSLSocket) context.getSocketFactory().createSocket();
        client.setEnabledCipherSuites(socket.getEnabledCipherSuites());
        client.setEnabledProtocols(socket.getEnabledProtocols());
        client.setNeedClientAuth(socket.getNeedClientAuth());
        client.setWantClientAuth(socket.getWantClientAuth());
        client.setEnabledSessionCreation(socket.getEnableSessionCreation());
    } else {
        client = new FTPSClient(getFtpsConfiguration().getSecurityProtocol(),
                getFtpsConfiguration().isImplicit());

        if (ftpClientKeyStoreParameters != null) {
            String type = (ftpClientKeyStoreParameters.containsKey("type"))
                    ? (String) ftpClientKeyStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientKeyStoreParameters.get("file");
            String password = (String) ftpClientKeyStoreParameters.get("password");
            String algorithm = (ftpClientKeyStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientKeyStoreParameters.get("algorithm")
                    : KeyManagerFactory.getDefaultAlgorithm();
            String keyPassword = (String) ftpClientKeyStoreParameters.get("keyPassword");

            KeyStore keyStore = KeyStore.getInstance(type);
            FileInputStream keyStoreFileInputStream = new FileInputStream(new File(file));
            try {
                keyStore.load(keyStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(keyStoreFileInputStream, "keyStore", log);
            }

            KeyManagerFactory keyMgrFactory = KeyManagerFactory.getInstance(algorithm);
            keyMgrFactory.init(keyStore, keyPassword.toCharArray());
            client.setNeedClientAuth(true);
            client.setKeyManager(keyMgrFactory.getKeyManagers()[0]);
        }

        if (ftpClientTrustStoreParameters != null) {
            String type = (ftpClientTrustStoreParameters.containsKey("type"))
                    ? (String) ftpClientTrustStoreParameters.get("type")
                    : KeyStore.getDefaultType();
            String file = (String) ftpClientTrustStoreParameters.get("file");
            String password = (String) ftpClientTrustStoreParameters.get("password");
            String algorithm = (ftpClientTrustStoreParameters.containsKey("algorithm"))
                    ? (String) ftpClientTrustStoreParameters.get("algorithm")
                    : TrustManagerFactory.getDefaultAlgorithm();

            KeyStore trustStore = KeyStore.getInstance(type);
            FileInputStream trustStoreFileInputStream = new FileInputStream(new File(file));
            try {
                trustStore.load(trustStoreFileInputStream, password.toCharArray());
            } finally {
                IOHelper.close(trustStoreFileInputStream, "trustStore", log);
            }

            TrustManagerFactory trustMgrFactory = TrustManagerFactory.getInstance(algorithm);
            trustMgrFactory.init(trustStore);

            client.setTrustManager(trustMgrFactory.getTrustManagers()[0]);
        }
    }

    return client;
}