Example usage for javax.net.ssl SSLContext getSocketFactory

List of usage examples for javax.net.ssl SSLContext getSocketFactory

Introduction

In this page you can find the example usage for javax.net.ssl SSLContext getSocketFactory.

Prototype

public final SSLSocketFactory getSocketFactory() 

Source Link

Document

Returns a SocketFactory object for this context.

Usage

From source file:org.apache.nifi.processors.standard.TestListenRELP.java

protected void run(final List<RELPFrame> frames, final int expectedTransferred, final int expectedResponses,
        final SSLContextService sslContextService) throws IOException, InterruptedException {

    Socket socket = null;//from   w w w  . j a v a2 s.  c  o  m
    try {
        // schedule to start listening on a random port
        final ProcessSessionFactory processSessionFactory = runner.getProcessSessionFactory();
        final ProcessContext context = runner.getProcessContext();
        proc.onScheduled(context);

        // create a client connection to the port the dispatcher is listening on
        final int realPort = proc.getDispatcherPort();

        // create either a regular socket or ssl socket based on context being passed in
        if (sslContextService != null) {
            final SSLContext sslContext = sslContextService
                    .createSSLContext(SSLContextService.ClientAuth.REQUIRED);
            socket = sslContext.getSocketFactory().createSocket("localhost", realPort);
        } else {
            socket = new Socket("localhost", realPort);
        }
        Thread.sleep(100);

        // send the frames to the port the processors is listening on
        sendFrames(frames, socket);

        long responseTimeout = 30000;

        // this first loop waits until the internal queue of the processor has the expected
        // number of messages ready before proceeding, we want to guarantee they are all there
        // before onTrigger gets a chance to run
        long startTimeQueueSizeCheck = System.currentTimeMillis();
        while (proc.getQueueSize() < expectedResponses
                && (System.currentTimeMillis() - startTimeQueueSizeCheck < responseTimeout)) {
            Thread.sleep(100);
        }

        // want to fail here if the queue size isn't what we expect
        Assert.assertEquals(expectedResponses, proc.getQueueSize());

        // call onTrigger until we got a respond for all the frames, or a certain amount of time passes
        long startTimeProcessing = System.currentTimeMillis();
        while (proc.responses.size() < expectedResponses
                && (System.currentTimeMillis() - startTimeProcessing < responseTimeout)) {
            proc.onTrigger(context, processSessionFactory);
            Thread.sleep(100);
        }

        // should have gotten a response for each frame
        Assert.assertEquals(expectedResponses, proc.responses.size());

        // should have transferred the expected events
        runner.assertTransferCount(ListenRELP.REL_SUCCESS, expectedTransferred);

    } finally {
        // unschedule to close connections
        proc.onUnscheduled();
        IOUtils.closeQuietly(socket);
    }
}

From source file:open.hyperion.nimblestorage.connection.NimbleStorageAPIFactory.java

public ClientConfig configureClient() throws NoSuchAlgorithmException, KeyManagementException {

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

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };
    SSLContext ctx = null;
    try {
        ctx = SSLContext.getInstance("TLS");
        ctx.init(null, certs, new SecureRandom());
    } catch (java.security.GeneralSecurityException ex) {
    }
    HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

    ClientConfig config = new DefaultClientConfig();
    try {
        config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES,
                new HTTPSProperties(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                }, ctx));
    } catch (Exception e) {
    }
    config.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    return config;
}

From source file:riddimon.android.asianetautologin.HttpUtils.java

private HttpUtils(Context context) {
    // private constructor to prevent instantiation
    this.context = context;
    try {//w ww  .  j a v a2 s. com
        // get version number to be set as part of user agent string
        version = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
    } catch (NameNotFoundException e) {
    }
    if (debug) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        });
        try {
            TrustManager[] trustManagers = new X509TrustManager[1];
            trustManagers[0] = new TrustAllManager();

            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustManagers, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        } catch (Exception ex) {
        }
    }
    // We don't enable response cache because this scenario requires fresh
    // data every time
    //enableHttpResponseCache();
}

From source file:org.jivesoftware.spark.util.DummySSLSocketFactory.java

public DummySSLSocketFactory(Context context, String chatEventString) {

    mContext = context;//from  w  ww .j  a v a 2s.com
    mChatEventString = chatEventString;

    try {
        SSLContext sslcontent = SSLContext.getInstance("TLS");
        sslcontent.init(null, // KeyManager not required
                new TrustManager[] { new DummyTrustManager() }, new java.security.SecureRandom());
        factory = sslcontent.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        Log.wtf("F1 :" + getClass().getName(), e);
    }
}

From source file:com.phonegap.FileTransfer.java

/**
 * This function will install a trust manager that will blindly trust all SSL 
 * certificates.  The reason this code is being added is to enable developers 
 * to do development using self signed SSL certificates on their web server.
 * /* w  w w .j a  v  a 2s. c  o m*/
 * The standard HttpsURLConnection class will throw an exception on self 
 * signed certificates if this code is not run.
 */
private void trustAllHosts() {
    // Create a trust manager that does not validate certificate chains
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
            return new java.security.cert.X509Certificate[] {};
        }

        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }

        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    } };

    // Install the all-trusting trust manager
    try {
        // Backup the current SSL socket factory
        defaultSSLSocketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();
        // Install our all trusting manager
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
}

From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java

/**
 * @deprecated Use {@link #SSLSocketFactory(SSLContext)}
 *///from   w  w w .j  a v a 2s  .  co m
@Deprecated
public SSLSocketFactory(final SSLContext sslContext, final HostNameResolver nameResolver) {
    super();
    this.socketfactory = sslContext.getSocketFactory();
    this.hostnameVerifier = BROWSER_COMPATIBLE_HOSTNAME_VERIFIER;
    this.nameResolver = nameResolver;
}

From source file:org.dataconservancy.dcs.access.http.SeadDatastreamServlet.java

private void getFile(SeadFile file, OutputStream destination) {

    String filePath = null;//from www . ja  va  2 s  .  c  o m
    if (file.getPrimaryLocation().getType() != null && file.getPrimaryLocation().getType().length() > 0
            && file.getPrimaryLocation().getLocation() != null
            && file.getPrimaryLocation().getLocation().length() > 0
            && file.getPrimaryLocation().getName() != null
            && file.getPrimaryLocation().getName().length() > 0) {
        if ((file.getPrimaryLocation().getName()
                .equalsIgnoreCase(ArchiveEnum.Archive.IU_SCHOLARWORKS.getArchive()))
                || (file.getPrimaryLocation().getName()
                        .equalsIgnoreCase(ArchiveEnum.Archive.UIUC_IDEALS.getArchive()))) {
            URLConnection connection = null;
            try {
                String location = file.getPrimaryLocation().getLocation();
                location = location.replace("http://maple.dlib.indiana.edu:8245/",
                        "https://scholarworks.iu.edu/");
                connection = new URL(location).openConnection();
                connection.setDoOutput(true);
                final TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(final X509Certificate[] chain, final String authType) {
                    }

                    @Override
                    public void checkServerTrusted(final X509Certificate[] chain, final String authType) {
                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                } };
                if (connection.getURL().getProtocol().equalsIgnoreCase("https")) {
                    final SSLContext sslContext = SSLContext.getInstance("SSL");
                    sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
                    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
                    ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory);
                }
                IOUtils.copy(connection.getInputStream(), destination);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (NoSuchAlgorithmException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            } catch (KeyManagementException e) {
                e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
            }
            return;
        } else if (file.getPrimaryLocation().getType()
                .equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText())
                && file.getPrimaryLocation().getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) {
            filePath = file.getPrimaryLocation().getLocation();

            String[] pathArr = filePath.split("/");

            try {
                sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(),
                        config.getSdamount());
                sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')), pathArr[pathArr.length - 1],
                        destination);
                sftp.disConnectSession();
            } catch (JSchException e) {
                e.printStackTrace();
            } catch (SftpException e) {
                e.printStackTrace();
            }
        }
    } else {
        if (file.getSecondaryDataLocations() != null && file.getSecondaryDataLocations().size() > 0) {
            for (SeadDataLocation dataLocation : file.getSecondaryDataLocations()) {
                if (dataLocation.getType().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getType().getText())
                        && dataLocation.getName().equalsIgnoreCase(ArchiveEnum.Archive.SDA.getArchive())) {
                    filePath = dataLocation.getLocation();

                    String[] pathArr = filePath.split("/");

                    try {
                        sftp = new Sftp(config.getSdahost(), config.getSdauser(), config.getSdapwd(),
                                config.getSdamount());
                        sftp.downloadFile(filePath.substring(0, filePath.lastIndexOf('/')),
                                pathArr[pathArr.length - 1], destination);
                        sftp.disConnectSession();
                    } catch (JSchException e) {
                        e.printStackTrace();
                    } catch (SftpException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    return;
}

From source file:com.thejoshwa.ultrasonic.androidapp.service.ssl.SSLSocketFactory.java

/**
 * @since 4.1//w  w  w . j ava  2s. c o  m
 */
public SSLSocketFactory(final SSLContext sslContext, final X509HostnameVerifier hostnameVerifier) {
    super();
    this.socketfactory = sslContext.getSocketFactory();
    this.hostnameVerifier = hostnameVerifier;
    this.nameResolver = null;
}

From source file:com.appdynamics.monitors.azure.statsCollector.AzureServiceBusStatsCollector.java

private SSLSocketFactory getSSLSocketFactory(String keyStoreName, String password) {
    KeyStore ks = getKeyStore(keyStoreName, password);
    KeyManagerFactory keyManagerFactory = null;
    try {/*  ww  w.j  av  a2s  .  c  o m*/
        keyManagerFactory = KeyManagerFactory.getInstance("SunX509");
        keyManagerFactory.init(ks, password.toCharArray());
        SSLContext context = SSLContext.getInstance("TLS");
        context.init(keyManagerFactory.getKeyManagers(), null, new SecureRandom());
        return context.getSocketFactory();
    } catch (NoSuchAlgorithmException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (KeyStoreException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (UnrecoverableKeyException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    } catch (KeyManagementException e) {
        logger.error(e.getMessage(), e);
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:org.jenkinsci.plugins.codefresh.CFApi.java

private void secureContext(boolean selfSignedCert) {
    this.https = true;
    trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }//from w  ww .ja  va 2  s  .  c  o  m

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

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

    // Install the all-trusting trust manager
    try {
        SSLContext sc = SSLContext.getInstance("TLS");
        sc.init(null, trustAllCerts, new SecureRandom());
        this.sf = sc.getSocketFactory();
        HttpsURLConnection.setDefaultSSLSocketFactory(this.sf);
    } catch (Exception e) {
        LOGGER.log(Level.SEVERE, e.getMessage(), e);
    }
    if (selfSignedCert) {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession sslSession) {
                return true;
            }
        });
    }
}