Package org.apache.commons.net.ftp

Examples of org.apache.commons.net.ftp.FTPSClient


            e.printStackTrace();
            status.setMessage("Error obtaining FTP host: " + e.getMessage());
            return status;
        }

        FTPSClient ftp = null;
        try {
            ftp = new FTPSClient(false, SSLContext.getDefault());

            System.out.println("Connecting to " + ftpHost + ":" + FTP_HOST_PORT);
            // ADDED connection retry logic
            int tryCount = 0;
            int maxTries = 5;
            boolean connectionSuccessful = false;
            do {
                try {
                    ftp.connect(ftpHost, FTP_HOST_PORT);
                    connectionSuccessful = true;
                } catch (Exception connectException) {
                    // wait 2 secs, then retry connection
                    try {
                        Thread.sleep((long) (Math.pow(2, (tryCount + 1)) * 1000));
                    } catch (InterruptedException e) {
                        // do nothing
                    }
                }
                if (++tryCount > maxTries) {
                    status.setMessage("FTP server refused connection (connection timeout).");
                    return status;
                }
            } while(!connectionSuccessful);
            // END connection retry logic

            SocrataConnectionInfo connectionInfo = userPrefs.getConnectionInfo();
            ftp.login(connectionInfo.getUser(), connectionInfo.getPassword());

            // verify connection was successful
            if(FTPReply.isPositiveCompletion(ftp.getReplyCode())) {
                System.out.println("ftp.setFileType(FTP.BINARY_FILE_TYPE)");
                ftp.setFileType(FTP.BINARY_FILE_TYPE);
                System.out.println("ftp.enterLocalPassiveMode()");
                ftp.enterLocalPassiveMode();

                // Set protection buffer size (what does this do??)
                //ftp.execPBSZ(0);
                // Set data channel protection to private
                System.out.println("ftp.execPROT(\"P\")");
                ftp.execPROT("P");

                String pathToDomainRoot = getPathToDomainRoot(ftp, connectionInfo);
                String pathToDatasetDir = pathToDomainRoot + "/" + datasetId;

                // if datasetId does not exist then create the directory
                System.out.println("ftp.listFiles(" + pathToDatasetDir + "/" + FTP_STATUS_FILENAME + ")");
                FTPFile[] checkDatasetDirExists = ftp.listFiles(pathToDatasetDir + "/" + FTP_STATUS_FILENAME);
                if(checkDatasetDirExists.length == 0) {
                    System.out.println("ftp.makeDirectory(" + pathToDatasetDir + ")");
                    boolean datasetDirCreated = ftp.makeDirectory(pathToDatasetDir);
                    if(!datasetDirCreated) {
                        closeFTPConnection(ftp);
                        status.setMessage("Error creating dataset ID directory at" +
                                " '" + pathToDatasetDir + "': " + ftp.getReplyString());
                        return status;
                    }
                }

                // set request Id for control file upload
View Full Code Here


*
*/
public class MinaClientAuthTest extends SSLTestTemplate {

    protected FTPSClient createFTPClient() throws Exception {
        FTPSClient client = new FTPSClient(useImplicit());
        client.setNeedClientAuth(true);

        KeyStore ks = KeyStore.getInstance("JKS");
        FileInputStream fis = new FileInputStream(FTPCLIENT_KEYSTORE);
        ks.load(fis, KEYSTORE_PASSWORD.toCharArray());
        fis.close();

        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory
                .getDefaultAlgorithm());
        kmf.init(ks, KEYSTORE_PASSWORD.toCharArray());

        client.setKeyManager(kmf.getKeyManagers()[0]);

        return client;
    }
View Full Code Here

    protected String getClientAuth() {
        return "false";
    }

    protected FTPSClient createFTPClient() throws Exception {
        FTPSClient ftpsClient = new FTPSClient(useImplicit());

        FileInputStream fin = new FileInputStream(FTPCLIENT_KEYSTORE);
        KeyStore store = KeyStore.getInstance("jks");
        store.load(fin, KEYSTORE_PASSWORD.toCharArray());
        fin.close();

        // initialize key manager factory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance("SunX509");
        keyManagerFactory.init(store, KEYSTORE_PASSWORD.toCharArray());

        // initialize trust manager factory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance("SunX509");

        trustManagerFactory.init(store);
        ftpsClient.setKeyManager(keyManagerFactory.getKeyManagers()[0]);
        ftpsClient.setTrustManager(trustManagerFactory.getTrustManagers()[0]);

        String auth = getAuthValue();
        if (auth != null) {
            ftpsClient.setAuthValue(auth);
        }
        return ftpsClient;
    }
View Full Code Here

        return server;
    }

    protected FTPSClient createFTPClient() throws Exception {
        return new FTPSClient(true);
    }
View Full Code Here

    protected String getClientAuth() {
        return "false";
    }

    protected FTPSClient createFTPClient() throws Exception {
        FTPSClient ftpsClient = new FTPSClient(useImplicit());

        FileInputStream fin = new FileInputStream(FTPCLIENT_KEYSTORE);
        KeyStore store = KeyStore.getInstance("jks");
        store.load(fin, KEYSTORE_PASSWORD.toCharArray());
        fin.close();

        // initialize key manager factory
        KeyManagerFactory keyManagerFactory = KeyManagerFactory
                .getInstance("SunX509");
        keyManagerFactory.init(store, KEYSTORE_PASSWORD.toCharArray());

        // initialize trust manager factory
        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance("SunX509");

        trustManagerFactory.init(store);
        ftpsClient.setKeyManager(keyManagerFactory.getKeyManagers()[0]);
        ftpsClient.setTrustManager(trustManagerFactory.getTrustManagers()[0]);

        String auth = getAuthValue();
        if (auth != null) {
            ftpsClient.setAuthValue(auth);
        }
        return ftpsClient;
    }
View Full Code Here

  }

  @Override
  public FTPClient connect() throws IOException {
    if (log.isDebugEnabled()) log.debug( String.format( "Connecting to ftps://%s:%s@%s over %s", username, password, hostname, this.protocol ) );
    FTPSClient ftpClient;
    try {
      ftpClient = new FTPSClient( this.protocol.asString() );
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException( String.format( "%s does not understand %s", this.hostname, this.protocol ), e );
    }
    ftpClient.connect( InetAddress.getByName( hostname ) );
    if (!FTPReply.isPositiveCompletion( ftpClient.getReplyCode() )) {
      ftpClient.disconnect();
      throw new RuntimeException( String.format( "%s refused connection over %s", this.hostname, this.protocol ) );
    }
    ftpClient.login( this.username, this.password );
    ftpClient.enterLocalPassiveMode();
    return ftpClient;
  }
View Full Code Here

    {
        int base = 0;
        boolean storeFile = false, binaryTransfer = false, error = false;
        String server, username, password, remote, local;
        String protocol = "SSL";    // SSL/TLS
        FTPSClient ftps;
       
        for (base = 0; base < args.length; base++)
        {
            if (args[base].startsWith("-s"))
                storeFile = true;
            else if (args[base].startsWith("-b"))
                binaryTransfer = true;
            else
                break;
        }

        if ((args.length - base) != 5)
        {
            System.err.println(USAGE);
            System.exit(1);
        }

        server = args[base++];
        username = args[base++];
        password = args[base++];
        remote = args[base++];
        local = args[base];

        ftps = new FTPSClient(protocol);
      
        ftps.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));

        try
        {
            int reply;

            ftps.connect(server);
            System.out.println("Connected to " + server + ".");

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

            if (!FTPReply.isPositiveCompletion(reply))
            {
                ftps.disconnect();
                System.err.println("FTP server refused connection.");
                System.exit(1);
            }
        }
        catch (IOException e)
        {
            if (ftps.isConnected())
            {
                try
                {
                    ftps.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
            }
            System.err.println("Could not connect to server.");
            e.printStackTrace();
            System.exit(1);
        }

__main:
        try
        {
            ftps.setBufferSize(1000);

            if (!ftps.login(username, password))
            {
                ftps.logout();
                error = true;
                break __main;
            }

           
            System.out.println("Remote system is " + ftps.getSystemName());

            if (binaryTransfer) ftps.setFileType(FTP.BINARY_FILE_TYPE);

            // Use passive mode as default because most of us are
            // behind firewalls these days.
            ftps.enterLocalPassiveMode();

            if (storeFile)
            {
                InputStream input;

                input = new FileInputStream(local);

                ftps.storeFile(remote, input);

                input.close();
            }
            else
            {
                OutputStream output;

                output = new FileOutputStream(local);

                ftps.retrieveFile(remote, output);

                output.close();
            }

            ftps.logout();
        }
        catch (FTPConnectionClosedException e)
        {
            error = true;
            System.err.println("Server closed connection.");
            e.printStackTrace();
        }
        catch (IOException e)
        {
            error = true;
            e.printStackTrace();
        }
        finally
        {
            if (ftps.isConnected())
            {
                try
                {
                    ftps.disconnect();
                }
                catch (IOException f)
                {
                    // do nothing
                }
View Full Code Here

   
    /**
     * Create the FTPS client.
     */
    protected FTPClient createFtpClient() throws Exception {
        FTPSClient 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;
    }
View Full Code Here

    }

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

        if (client == null) {
            // must use a new client if not explicit configured to use a custom client
            client = (FTPSClient) createFtpClient();
        }

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

        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 FTPSClient [connectTimeout: " + client.getConnectTimeout() + ", soTimeout: " + getSoTimeout() + ", dataTimeout: " + dataTimeout + "]: " + client);
        }

        FtpsOperations operations = new FtpsOperations(client, getFtpClientConfig());
        operations.setEndpoint(this);
        return operations;
View Full Code Here

   
    @Override
    protected JndiRegistry createRegistry() throws Exception {
        JndiRegistry jndi = super.createRegistry();

        FTPSClient ftpsClient = new FTPSClient("SSL");

        jndi.bind("ftpsClient", ftpsClient);
        return jndi;
    }
View Full Code Here

TOP

Related Classes of org.apache.commons.net.ftp.FTPSClient

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.