Example usage for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

List of usage examples for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER

Introduction

In this page you can find the example usage for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Prototype

X509HostnameVerifier ALLOW_ALL_HOSTNAME_VERIFIER

To view the source code for org.apache.http.conn.ssl SSLSocketFactory ALLOW_ALL_HOSTNAME_VERIFIER.

Click Source Link

Usage

From source file:org.obiba.opal.rest.client.magma.OpalJavaClient.java

private SchemeSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder builder = SSLContexts.custom().useTLS();
    try {//from   www  . j  a v a  2  s.c o  m
        builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    } catch (KeyStoreException e) {
        log.error("Unable to set SSL trust manager: {}", e.getMessage(), e);
    }

    if (keyStore != null) {
        try {
            builder.loadKeyMaterial(keyStore, credentials.getPassword().toCharArray(),
                    new PrivateKeyStrategy() {
                        @Override
                        public String chooseAlias(Map<String, PrivateKeyDetails> aliases, Socket socket) {
                            return credentials.getUserPrincipal().getName();
                        }
                    });
        } catch (KeyStoreException | UnrecoverableKeyException e) {
            log.error("Unable to set SSL key manager: {}", e.getMessage(), e);
        }
    }

    return new SSLSocketFactory(builder.build(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}

From source file:pl.psnc.synat.wrdz.zmkd.invocation.RestServiceCaller.java

/**
 * Gets client that can use HTTP or HTTPS protocol accepting all servers certificates.
 * //from w w w. ja v  a  2s. com
 * @return HTTP client
 */
private HttpClient getHttpClient() {
    Scheme httpScheme = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
    Scheme httpsScheme = null;
    try {
        httpsScheme = new Scheme("https", 443,
                new SSLSocketFactory(new TrustAllStrategy(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER));
    } catch (KeyManagementException e) {
        throw new WrdzRuntimeException(e);
    } catch (UnrecoverableKeyException e) {
        throw new WrdzRuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new WrdzRuntimeException(e);
    } catch (KeyStoreException e) {
        throw new WrdzRuntimeException(e);
    }

    ClientConnectionManager connectionManager = new BasicClientConnectionManager();
    connectionManager.getSchemeRegistry().register(httpScheme);
    connectionManager.getSchemeRegistry().register(httpsScheme);

    return new DefaultHttpClient(connectionManager);
}

From source file:com.vmware.bdd.plugin.ironfan.impl.RolePackageMapping.java

@SuppressWarnings("deprecation")
private String readDistroManifest() throws Exception {
    File manifestFile = new File(DISTRO_MANIFEST_FILE_PATH);
    if (manifestFile.exists()) {
        // The manifest file is on the local server.
        // No need to reload the file if it's not modified.
        if (lastModified != manifestFile.lastModified()) {
            lastModified = manifestFile.lastModified();
            logger.info("last modified date of manifest file changed. Reloading manifest.");
        } else {//from   w  w w . java 2 s.c om
            return null;
        }
    }

    BufferedReader in = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();
    try {
        SSLContext sslContext = SSLContexts.custom().useTLS().build();

        sslContext.init(null, new TrustManager[] { new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                return;
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s)
                    throws CertificateException {
                return;
            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        } }, null);

        TlsClientConfiguration tlsConfiguration = new TlsClientConfiguration();
        SSLSocketFactory socketFactory = new SSLSocketFactory(sslContext, tlsConfiguration.getSslProtocols(),
                tlsConfiguration.getCipherSuites(), SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);
        HttpGet httpget = new HttpGet(new URI(distrosManifestUrl));
        if (eTag != null) {
            httpget.addHeader("If-None-Match", eTag);
        }

        logger.info("executing request: " + httpget.getRequestLine());
        HttpResponse response = httpclient.execute(httpget);

        if (!manifestFile.exists()) {
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_MODIFIED) {
                return null;
            } else {
                logger.debug("ETag of manifest file changed. Reloading manifest.");
                eTag = response.getFirstHeader("ETag").getValue();
                ;
            }
        }
        HttpEntity entity = response.getEntity();

        in = new BufferedReader(new InputStreamReader(entity.getContent()));

        StringBuffer sb = new StringBuffer();
        String line;
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        EntityUtils.consume(entity);
        return sb.toString();
    } finally {
        httpclient.getConnectionManager().shutdown();
        if (in != null) {
            in.close();
        }
    }
}

From source file:org.opcfoundation.ua.transport.https.HttpsClient.java

/**
 * Initialize HttpsClient. //from   w w  w.  j  a v a  2s. co m
 * 
 * @param connectUrl
 * @param tcs
 */
public void initialize(String connectUrl, TransportChannelSettings tcs, EncoderContext ctx)
        throws ServiceResultException {

    this.connectUrl = connectUrl;
    this.securityPolicyUri = tcs.getDescription().getSecurityPolicyUri();
    this.transportChannelSettings = tcs;
    HttpsSettings httpsSettings = tcs.getHttpsSettings();
    HttpsSecurityPolicy[] policies = httpsSettings.getHttpsSecurityPolicies();
    if (policies != null && policies.length > 0)
        securityPolicy = policies[policies.length - 1];
    else
        securityPolicy = HttpsSecurityPolicy.TLS_1_1;
    // securityPolicy = SecurityPolicy.getSecurityPolicy( this.securityPolicyUri );
    if (securityPolicy != HttpsSecurityPolicy.TLS_1_0 && securityPolicy != HttpsSecurityPolicy.TLS_1_1
            && securityPolicy != HttpsSecurityPolicy.TLS_1_2)
        throw new ServiceResultException(StatusCodes.Bad_SecurityChecksFailed,
                "Https Client doesn't support securityPolicy " + securityPolicy);
    if (logger.isDebugEnabled()) {
        logger.debug("initialize: url={}; settings={}", tcs.getDescription().getEndpointUrl(),
                ObjectUtils.printFields(tcs));
    }

    // Setup Encoder
    EndpointConfiguration endpointConfiguration = tcs.getConfiguration();
    encoderCtx = ctx;
    encoderCtx.setMaxArrayLength(
            endpointConfiguration.getMaxArrayLength() != null ? endpointConfiguration.getMaxArrayLength() : 0);
    encoderCtx.setMaxStringLength(
            endpointConfiguration.getMaxStringLength() != null ? endpointConfiguration.getMaxStringLength()
                    : 0);
    encoderCtx.setMaxByteStringLength(endpointConfiguration.getMaxByteStringLength() != null
            ? endpointConfiguration.getMaxByteStringLength()
            : 0);
    encoderCtx.setMaxMessageSize(
            endpointConfiguration.getMaxMessageSize() != null ? endpointConfiguration.getMaxMessageSize() : 0);

    timer = TimerUtil.getTimer();
    try {
        SchemeRegistry sr = new SchemeRegistry();
        if (protocol.equals(UriUtil.SCHEME_HTTPS)) {
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(httpsSettings.getKeyManagers(), httpsSettings.getTrustManagers(), null);
            X509HostnameVerifier hostnameVerifier = httpsSettings.getHostnameVerifier() != null
                    ? httpsSettings.getHostnameVerifier()
                    : SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
            SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier) {
                protected void prepareSocket(javax.net.ssl.SSLSocket socket) throws IOException {
                    socket.setEnabledCipherSuites(cipherSuites);
                };
            };

            SSLEngine sslEngine = sslcontext.createSSLEngine();
            String[] enabledCipherSuites = sslEngine.getEnabledCipherSuites();
            cipherSuites = CryptoUtil.filterCipherSuiteList(enabledCipherSuites,
                    securityPolicy.getCipherSuites());

            logger.info("Enabled protocols in SSL Engine are {}",
                    Arrays.toString(sslEngine.getEnabledProtocols()));
            logger.info("Enabled CipherSuites in SSL Engine are {}", Arrays.toString(enabledCipherSuites));
            logger.info("Client CipherSuite selection for {} is {}", securityPolicy.getPolicyUri(),
                    Arrays.toString(cipherSuites));

            Scheme https = new Scheme("https", 443, sf);
            sr.register(https);
        }

        if (protocol.equals(UriUtil.SCHEME_HTTP)) {
            Scheme http = new Scheme("http", 80, PlainSocketFactory.getSocketFactory());
            sr.register(http);
        }

        if (ccm == null) {
            PoolingClientConnectionManager pccm = new PoolingClientConnectionManager(sr);
            ccm = pccm;
            pccm.setMaxTotal(maxConnections);
            pccm.setDefaultMaxPerRoute(maxConnections);
        }
        BasicHttpParams httpParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParams,
                transportChannelSettings.getConfiguration().getOperationTimeout());
        HttpConnectionParams.setSoTimeout(httpParams, 0);
        httpclient = new DefaultHttpClient(ccm, httpParams);

        // Set username and password authentication
        if (httpsSettings.getUsername() != null && httpsSettings.getPassword() != null) {
            BasicCredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(httpsSettings.getUsername(), httpsSettings.getPassword()));
            httpclient.setCredentialsProvider(credsProvider);
        }

    } catch (NoSuchAlgorithmException e) {
        new ServiceResultException(e);
    } catch (KeyManagementException e) {
        new ServiceResultException(e);
    }

}

From source file:org.soyatec.windowsazure.internal.util.ssl.SslUtil.java

/**
 * Get the SSLSocketFactory by given SSLContext
 * /* w  ww .j  a  v  a 2  s . c  om*/
 * @param context
 *            the SSLContext object
 * @return the SSLSocketFactory object
 */
public static SSLSocketFactory getSSLSocketFactory(SSLContext context) {
    SSLSocketFactory factory = new SSLSocketFactory(context);
    factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return factory;
}

From source file:password.pwm.http.client.PwmHttpClient.java

private static ClientConnectionManager makeConnectionManager(TrustManager trustManager)
        throws NoSuchAlgorithmException, KeyManagementException {
    final SSLContext sslContext = SSLContext.getInstance("SSL");

    sslContext.init(null, new TrustManager[] { trustManager }, new SecureRandom());

    final SSLSocketFactory sf = new SSLSocketFactory(sslContext);
    final HostnameVerifier hostnameVerifier = org.apache.http.conn.ssl.SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;

    sf.setHostnameVerifier((X509HostnameVerifier) hostnameVerifier);
    final Scheme httpsScheme = new Scheme("https", 443, sf);
    final SchemeRegistry schemeRegistry = new SchemeRegistry();
    schemeRegistry.register(httpsScheme);

    return new SingleClientConnManager(schemeRegistry);
}

From source file:srl.distributed.client.Client.java

private DefaultHttpClient getNewHttpClient() {
    try {//from   ww w.j  a  v  a 2s  . c  o m
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new InsecureSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:sh.calaba.driver.server.CalabashNodeConfiguration.java

protected static HttpClient getDefaultHttpClient() throws KeyManagementException, NoSuchAlgorithmException {
    HttpClient base = new DefaultHttpClient();

    SSLContext ctx = SSLContext.getInstance("TLS");
    X509TrustManager tm = new X509TrustManager() {

        public void checkClientTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }// w  w w .  ja v  a2  s  .  c  o  m

        public void checkServerTrusted(X509Certificate[] xcs, String string) throws CertificateException {
        }

        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    ctx.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory ssf = new SSLSocketFactory(ctx);
    ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    ClientConnectionManager ccm = base.getConnectionManager();
    SchemeRegistry sr = ccm.getSchemeRegistry();
    sr.register(new Scheme("https", ssf, 443));
    return new DefaultHttpClient(ccm, base.getParams());
}

From source file:de.geomobile.joined.api.service.JOWebService.java

/**
 * @return//from  w  w  w.ja  v a2 s  . c o  m
 */
private HttpClient getNewHttpClient() {
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new JOSSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(params, 10000);
        HttpConnectionParams.setSoTimeout(params, 10000);
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

        return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        return new DefaultHttpClient();
    }
}

From source file:com.num.mobiperf.Checkin.java

/**
 * Return an appropriately-configured HTTP client.
 *//* www  . j ava  2 s.  c  o m*/
private HttpClient getNewHttpClient() {
    DefaultHttpClient client;
    try {
        KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
        trustStore.load(null, null);

        SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
        sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

        HttpConnectionParams.setConnectionTimeout(params, POST_TIMEOUT_MILLISEC);
        HttpConnectionParams.setSoTimeout(params, POST_TIMEOUT_MILLISEC);

        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", sf, 443));

        ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
        client = new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
        // Logger.w("Unable to create SSL HTTP client", e);
        client = new DefaultHttpClient();
    }

    // TODO(mdw): For some reason this is not sending the cookie to the
    // test server, probably because the cookie itself is not properly
    // initialized. Below I manually set the Cookie header instead.
    CookieStore store = new BasicCookieStore();
    store.addCookie(authCookie);
    client.setCookieStore(store);
    return client;
}