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.mongodb.MongoDBControllerService.java

protected MongoClientOptions.Builder getClientOptions(final SSLContext sslContext) {
    MongoClientOptions.Builder builder = MongoClientOptions.builder();
    builder.sslEnabled(true);/*from  w ww . j  ava2  s . c  om*/
    builder.socketFactory(sslContext.getSocketFactory());
    return builder;
}

From source file:com.amazon.alexa.avs.companion.ProvisioningClient.java

private SSLSocketFactory getPinnedSSLSocketFactory(Context context) throws Exception {
    InputStream caCertInputStream = null;
    try {//from w  ww .  j a  v a 2 s .co  m
        caCertInputStream = context.getResources().openRawResource(R.raw.ca);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate caCert = cf.generateCertificate(caCertInputStream);

        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);
        trustStore.setCertificateEntry("myca", caCert);

        TrustManagerFactory trustManagerFactory = TrustManagerFactory
                .getInstance(TrustManagerFactory.getDefaultAlgorithm());
        trustManagerFactory.init(trustStore);

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
        return sslContext.getSocketFactory();
    } finally {
        IOUtils.closeQuietly(caCertInputStream);
    }
}

From source file:org.openhab.action.openwebif.internal.impl.OpenWebIfCommunicator.java

/**
 * Executes the http request and parses the returned stream.
 *///from  w w w. j a v  a  2s.c o m
@SuppressWarnings("unchecked")
private <T> T executeRequest(OpenWebIfConfig config, String url, Class<T> clazz) throws IOException {
    HttpURLConnection con = null;
    try {
        logger.trace("Request [{}]: {}", config.getName(), url);

        con = (HttpURLConnection) new URL(url).openConnection();
        con.setConnectTimeout(CONNECTION_TIMEOUT);
        con.setReadTimeout(10000);

        if (config.hasLogin()) {
            String userpass = config.getUser() + ":" + config.getPassword();
            String basicAuth = "Basic " + DatatypeConverter.printBase64Binary(userpass.getBytes());
            con.setRequestProperty("Authorization", basicAuth);
        }

        if (con instanceof HttpsURLConnection) {
            HttpsURLConnection sCon = (HttpsURLConnection) con;
            TrustManager[] trustManager = new TrustManager[] { new SimpleTrustManager() };
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(new KeyManager[0], trustManager, new SecureRandom());
            sCon.setSSLSocketFactory(context.getSocketFactory());
            sCon.setHostnameVerifier(new AllowAllHostnameVerifier());
        }
        StringWriter sw = new StringWriter();
        IOUtils.copy(con.getInputStream(), sw);
        con.disconnect();

        if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String response = sw.toString();
            logger.trace("Response: [{}]: {}", config.getName(), response);

            Unmarshaller um = JAXBContext.newInstance(clazz).createUnmarshaller();
            return (T) um.unmarshal(new StringReader(response));
        } else {
            throw new IOException(con.getResponseMessage());
        }
    } catch (JAXBException ex) {
        throw new IOException(ex.getMessage(), ex);
    } catch (GeneralSecurityException ex) {
        throw new IOException(ex.getMessage(), ex);
    } finally {
        if (con != null) {
            con.disconnect();
        }
    }
}

From source file:com.orange.cloud.servicebroker.filter.core.config.OkHttpClientConfig.java

@Bean
public OkHttpClient squareHttpClient() {
    HostnameVerifier hostnameVerifier = new HostnameVerifier() {
        @Override/*from   w  w w . ja  va  2s .c o  m*/
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    TrustManager[] trustAllCerts = new TrustManager[] { new TrustAllCerts() };

    SSLSocketFactory sslSocketFactory = null;
    try {
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        sslSocketFactory = (SSLSocketFactory) sc.getSocketFactory();
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        new IllegalArgumentException(e);
    }

    log.info("===> configuring OkHttp");
    OkHttpClient.Builder ohc = new OkHttpClient.Builder().protocols(Arrays.asList(Protocol.HTTP_1_1))
            .followRedirects(true).followSslRedirects(true).hostnameVerifier(hostnameVerifier)
            .sslSocketFactory(sslSocketFactory).addInterceptor(LOGGING_INTERCEPTOR);

    if ((this.proxyHost != null) && (this.proxyHost.length() > 0)) {
        log.info("Activating proxy on host {} port {}", this.proxyHost, this.proxyPort);
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(this.proxyHost, this.proxyPort));
        ohc.proxy(proxy);
        ohc.proxySelector(new ProxySelector() {
            @Override
            public List<Proxy> select(URI uri) {
                return Arrays.asList(proxy);
            }

            @Override
            public void connectFailed(URI uri, SocketAddress socket, IOException e) {
                throw new IllegalArgumentException("connection to proxy failed", e);
            }
        });
    }

    return ohc.build();
}

From source file:com.qpark.eip.core.spring.security.https.EipHttpsClientHttpRequestFactory.java

/**
 * @see org.springframework.http.client.SimpleClientHttpRequestFactory#prepareConnection(java.net.HttpURLConnection,
 *      java.lang.String)//w ww  .  ja v  a2  s .c o m
 */
@Override
protected void prepareConnection(final HttpURLConnection connection, final String httpMethod) {
    try {
        /* Setup HttpsURLConnection. */
        if (HttpsURLConnection.class.isInstance(connection)) {
            HttpsURLConnection httpsConnection = (HttpsURLConnection) connection;
            httpsConnection.setHostnameVerifier(this.x509TrustManager);
            TrustManager[] trustManagers = new TrustManager[] { this.x509TrustManager };
            SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustManagers, new java.security.SecureRandom());
            ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
        }
        super.prepareConnection(connection, httpMethod);
        /* Setup the basic Authentication. */
        if (HttpURLConnection.class.isInstance(connection) && this.userName != null) {
            HttpURLConnection httpsConnection = connection;
            httpsConnection.setRequestProperty("Authorization",
                    new StringBuffer(128).append("Basic ").append(this.base64UserNamePassword).toString());
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.apache.camel.component.mail.security.DummySSLSocketFactory.java

public DummySSLSocketFactory() {
    try {//from  w w w .  jav  a 2 s. co m
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager[] trustManagers = new TrustManager[] { new DummyTrustManager() };
        sslContext.init(null, trustManagers, new java.security.SecureRandom());
        factory = sslContext.getSocketFactory();
    } catch (Exception e) {
        throw new RuntimeCamelException("Error creating DummySSLSocketFactory: " + e.getMessage(), e);
    }
}

From source file:org.rhq.enterprise.server.util.security.UntrustedSSLProtocolSocketFactory.java

public UntrustedSSLProtocolSocketFactory() {
    super();//from  w  ww.j a va 2  s.  c  o  m

    try {
        BogusTrustManager trustMan;
        SSLContext tlsContext;

        trustMan = new BogusTrustManager();
        tlsContext = SSLContext.getInstance("TLS");
        tlsContext.init(null, new X509TrustManager[] { trustMan }, null);
        this.factory = tlsContext.getSocketFactory();
    } catch (NoSuchAlgorithmException exc) {
        throw new IllegalStateException("Unable to get SSL context: " + exc.getMessage());
    } catch (KeyManagementException exc) {
        throw new IllegalStateException("Unable to initialize ctx with BogusTrustManager: " + exc.getMessage());
    }
}

From source file:org.eclipse.mylyn.internal.commons.http.PollingSslProtocolSocketFactory.java

public PollingSslProtocolSocketFactory() {
    KeyManager[] keymanagers = null;
    if (System.getProperty(KEY_STORE) != null && System.getProperty(KEY_STORE_PASSWORD) != null) {
        try {/*ww w. j  av  a 2  s.  c  om*/
            String type = System.getProperty(KEY_STORE_TYPE, KeyStore.getDefaultType());
            KeyStore keyStore = KeyStore.getInstance(type);
            char[] password = System.getProperty(KEY_STORE_PASSWORD).toCharArray();
            keyStore.load(new FileInputStream(System.getProperty(KEY_STORE)), password);
            KeyManagerFactory keyManagerFactory = KeyManagerFactory
                    .getInstance(KeyManagerFactory.getDefaultAlgorithm());
            keyManagerFactory.init(keyStore, password);
            keymanagers = keyManagerFactory.getKeyManagers();
        } catch (Exception e) {
            CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize keystore", e); //$NON-NLS-1$
        }
    }

    hasKeyManager = keymanagers != null;

    try {
        SSLContext sslContext = SSLContext.getInstance("SSL"); //$NON-NLS-1$
        sslContext.init(keymanagers, new TrustManager[] { new TrustAllTrustManager() }, null);
        this.socketFactory = sslContext.getSocketFactory();
    } catch (Exception e) {
        CommonsHttpPlugin.log(IStatus.ERROR, "Could not initialize SSL context", e); //$NON-NLS-1$
    }
}

From source file:com.wunding.mlplayer.hudong.DummySSLSocketFactory.java

public DummySSLSocketFactory() {

    try {/*from ww w.j av a2  s .  c o m*/
        SSLContext sslcontent = SSLContext.getInstance("TLS");
        sslcontent.init(null, // KeyManager not required
                new TrustManager[] { new DummyTrustManager() }, null);
        factory = sslcontent.getSocketFactory();

        //            factory = new org.apache.http.conn.ssl.SSLSocketFactory(sslcontent);
        //            // Accept any hostname, so the self-signed certificates don't fail
        //            factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER)            
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
}

From source file:client.lib.Client.java

public Client() throws NoSuchAlgorithmException, KeyManagementException {
    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
        public X509Certificate[] getAcceptedIssuers() {
            X509Certificate[] myTrustedAnchors = new X509Certificate[0];
            return myTrustedAnchors;
        }/*from  w ww . ja  v  a 2 s  .  c  o m*/

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

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

    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustAllCerts, new SecureRandom());

    // Create an ssl socket factory with our all-trusting manager
    final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

    http2Client = new OkHttpClient();
    http2Client.setSslSocketFactory(sslSocketFactory);
    http2Client.setHostnameVerifier(new HostnameVerifier() {
        @Override
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    });

    httpClient = http2Client.clone();

    httpClient.setProtocols(Arrays.asList(Protocol.HTTP_1_1));
    http2Client.setProtocols(Arrays.asList(Protocol.HTTP_2));
}