Example usage for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

List of usage examples for org.apache.http.conn.ssl SSLConnectionSocketFactory SSLConnectionSocketFactory

Introduction

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

Prototype

public SSLConnectionSocketFactory(final javax.net.ssl.SSLSocketFactory socketfactory,
            final X509HostnameVerifier hostnameVerifier) 

Source Link

Usage

From source file:net.shibboleth.idp.cas.authn.PkixProxyAuthenticator.java

/**
 * Creates a new instance./*w  w w  . j av a  2  s .c  om*/
 *
 * @param x509TrustEngine X.509 trust engine used to validate the TLS certificate presented by the proxy
 *                        callback endpoint.
 */
public PkixProxyAuthenticator(@Nonnull TrustEngine<X509Credential> x509TrustEngine) {
    Constraint.isNotNull(x509TrustEngine, "Trust engine cannot be null");
    try {
        SSLContext sslContext = SSLContexts.custom().useTLS()
                .loadTrustMaterial(null, new TrustEngineTrustStrategy(x509TrustEngine)).build();
        socketFactory = new SSLConnectionSocketFactory(sslContext,
                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    } catch (Exception e) {
        throw new RuntimeException("SSL initialization error", e);
    }
}

From source file:fr.wseduc.webdav.WebDav.java

private Sardine getSardine(String uri, Message<JsonObject> message) {
    String host;//from  w  ww.  j a v  a 2s . c  o m
    try {
        host = new URI(uri).getHost();
    } catch (URISyntaxException e) {
        sendError(message, e.getMessage(), e);
        return null;
    }
    JsonObject credential = credentials.getJsonObject(host);
    Sardine sardine;
    if (credential != null) {
        if (credential.getBoolean("insecure", false)) {
            sardine = new SardineImpl() {
                @Override
                protected ConnectionSocketFactory createDefaultSecureSocketFactory() {
                    SSLConnectionSocketFactory sf = null;
                    TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return null;
                        }

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

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] certs,
                                String authType) {
                        }
                    } };
                    try {
                        SSLContext context = SSLContext.getInstance("TLS");
                        context.init(null, trustAllCerts, null);

                        sf = new SSLConnectionSocketFactory(context,
                                SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
                    } catch (NoSuchAlgorithmException | KeyManagementException e) {
                        logger.error(e.getMessage(), e);
                    }
                    return sf;
                }
            };
            sardine.setCredentials(credential.getString("username"), credential.getString("password"));
        } else {
            sardine = SardineFactory.begin(credential.getString("username"), credential.getString("password"));
        }
        sardine.enablePreemptiveAuthentication(host);
    } else {
        sardine = SardineFactory.begin();
    }
    return sardine;
}

From source file:org.ow2.proactive_grid_cloud_portal.rm.server.serialization.CatalogRequestBuilder.java

private HttpClientBuilder getHttpClientBuilder()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    SSLContextBuilder sslContextBuilder = new SSLContextBuilder();
    sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    return HttpClients.custom().setSSLSocketFactory(sslSocketFactory);
}

From source file:io.pivotal.strepsirrhini.chaoslemur.infrastructure.StandardDirectorUtils.java

private static String getBoshDirectorUaaToken(String host, String directorName, String password)
        throws GeneralSecurityException {

    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS()
            .build();//from  w w w  . j  a  v  a2 s  . c o  m

    SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext,
            new AllowAllHostnameVerifier());

    HttpClient httpClient = HttpClientBuilder.create().disableRedirectHandling()
            .setSSLSocketFactory(connectionFactory).build();
    RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory(httpClient));

    MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
    String base64Passowrd = encodePassword(directorName, password);
    headers.add("Authorization", "Basic " + base64Passowrd);
    headers.add("Content-Type", "application/x-www-form-urlencoded");

    String postArgs = "grant_type=client_credentials";

    HttpEntity<String> requestEntity = new HttpEntity<String>(postArgs, headers);
    String uri = "https://" + host + ":8443/oauth/token";
    UaaToken response = restTemplate.postForObject(uri, requestEntity, UaaToken.class);

    log.info("Uaa token:" + response);
    return response.getAccess_token();
}

From source file:org.elasticsearch.xpack.watcher.common.http.HttpClient.java

public HttpClient(Settings settings, HttpAuthRegistry httpAuthRegistry, SSLService sslService) {
    super(settings);
    this.httpAuthRegistry = httpAuthRegistry;
    this.defaultConnectionTimeout = HttpSettings.CONNECTION_TIMEOUT.get(settings);
    this.defaultReadTimeout = HttpSettings.READ_TIMEOUT.get(settings);
    this.maxResponseSize = HttpSettings.MAX_HTTP_RESPONSE_SIZE.get(settings);
    this.settingsProxy = getProxyFromSettings();

    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // ssl setup/*from  w w w  .  j a va2  s . co m*/
    Settings sslSettings = settings.getByPrefix(SETTINGS_SSL_PREFIX);
    boolean isHostnameVerificationEnabled = sslService.getVerificationMode(sslSettings, Settings.EMPTY)
            .isHostnameVerificationEnabled();
    HostnameVerifier verifier = isHostnameVerificationEnabled ? new DefaultHostnameVerifier()
            : NoopHostnameVerifier.INSTANCE;
    SSLConnectionSocketFactory factory = new SSLConnectionSocketFactory(
            sslService.sslSocketFactory(sslSettings), verifier);
    clientBuilder.setSSLSocketFactory(factory);

    clientBuilder.evictExpiredConnections();
    clientBuilder.setMaxConnPerRoute(MAX_CONNECTIONS);
    clientBuilder.setMaxConnTotal(MAX_CONNECTIONS);

    client = clientBuilder.build();
}

From source file:io.apiman.manager.api.es.DefaultEsClientFactory.java

/**
 * @param httpConfig//from   w  ww. ja  v  a2 s  . c o m
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig) {
    try {
        String clientKeystorePath = getConfig().get("client-keystore");
        String clientKeystorePassword = getConfig().get("client-keystore.password");
        String trustStorePath = getConfig().get("trust-store");
        String trustStorePassword = getConfig().get("trust-store.password");

        SSLContext sslContext = SSLContext.getInstance("TLS");
        Info kPathInfo = new Info(clientKeystorePath, clientKeystorePassword);
        Info tPathInfo = new Info(trustStorePath, trustStorePassword);
        sslContext.init(KeyStoreUtil.getKeyManagers(kPathInfo), KeyStoreUtil.getTrustManagers(tPathInfo), null);
        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext,
                hostnameVerifier);
        SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

        httpConfig.defaultSchemeForDiscoveredNodes("https");
        httpConfig.sslSocketFactory(sslSocketFactory); // for sync calls
        httpConfig.httpsIOSessionStrategy(httpsIOSessionStrategy); // for async calls

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:sk.datalan.solr.impl.HttpClientUtil.java

public static HttpClientBuilder configureClient(final HttpClientConfiguration config) {
    HttpClientBuilder clientBuilder = HttpClientBuilder.create();

    // max total connections
    if (config.isSetMaxConnections()) {
        clientBuilder.setMaxConnTotal(config.getMaxConnections());
    }//from  w  ww.  j a va2 s  .c om

    // max connections per route
    if (config.isSetMaxConnectionsPerRoute()) {
        clientBuilder.setMaxConnPerRoute(config.getMaxConnectionsPerRoute());
    }

    RequestConfig.Builder requestConfigBuilder = RequestConfig.custom().setCookieSpec(CookieSpecs.BEST_MATCH)
            .setExpectContinueEnabled(true).setStaleConnectionCheckEnabled(true);

    // connection timeout
    if (config.isSetConnectionTimeout()) {
        requestConfigBuilder.setConnectTimeout(config.getConnectionTimeout());
    }

    // soucket timeout
    if (config.isSetSocketTimeout()) {
        requestConfigBuilder.setSocketTimeout(config.getSocketTimeout());
    }

    // soucket timeout
    if (config.isSetFollowRedirects()) {
        requestConfigBuilder.setRedirectsEnabled(config.getFollowRedirects());
    }
    clientBuilder.setDefaultRequestConfig(requestConfigBuilder.build());

    if (config.isSetUseRetry()) {
        if (config.getUseRetry()) {
            clientBuilder.setRetryHandler(new DefaultHttpRequestRetryHandler());
        } else {
            clientBuilder.setRetryHandler(NO_RETRY);
        }
    }

    // basic authentication
    if (config.isSetBasicAuthUsername() && config.isSetBasicAuthPassword()) {
        CredentialsProvider credsProvider = new BasicCredentialsProvider();
        credsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(config.getBasicAuthUsername(), config.getBasicAuthPassword()));
    }

    if (config.isSetAllowCompression()) {
        clientBuilder.addInterceptorFirst(new UseCompressionRequestInterceptor());
        clientBuilder.addInterceptorFirst(new UseCompressionResponseInterceptor());
    }

    // SSL context for secure connections can be created either based on
    // system or application specific properties.
    SSLContext sslcontext = SSLContexts.createSystemDefault();
    // Use custom hostname verifier to customize SSL hostname verification.
    X509HostnameVerifier hostnameVerifier = new BrowserCompatHostnameVerifier();

    // Create a registry of custom connection socket factories for supported
    // protocol schemes.
    Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", PlainConnectionSocketFactory.INSTANCE)
            .register("https", new SSLConnectionSocketFactory(sslcontext, hostnameVerifier)).build();

    clientBuilder.setConnectionManager(new PoolingHttpClientConnectionManager(socketFactoryRegistry));

    return clientBuilder;
}

From source file:org.apache.manifoldcf.authorities.authorities.jira.JiraSession.java

/**
 * Constructor. Create a session.//w  w  w  . ja  va2  s.co  m
 */
public JiraSession(String clientId, String clientSecret, String protocol, String host, int port, String path,
        String proxyHost, int proxyPort, String proxyDomain, String proxyUsername, String proxyPassword)
        throws ManifoldCFException {
    this.host = new HttpHost(host, port, protocol);
    this.path = path;
    this.clientId = clientId;
    this.clientSecret = clientSecret;

    int socketTimeout = 900000;
    int connectionTimeout = 60000;

    javax.net.ssl.SSLSocketFactory httpsSocketFactory = KeystoreManagerFactory.getTrustingSecureSocketFactory();
    SSLConnectionSocketFactory myFactory = new SSLConnectionSocketFactory(
            new InterruptibleSocketFactory(httpsSocketFactory, connectionTimeout),
            SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

    connectionManager = new PoolingHttpClientConnectionManager();

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();

    // If authentication needed, set that
    if (clientId != null) {
        credentialsProvider.setCredentials(AuthScope.ANY,
                new UsernamePasswordCredentials(clientId, clientSecret));
    }

    RequestConfig.Builder requestBuilder = RequestConfig.custom().setCircularRedirectsAllowed(true)
            .setSocketTimeout(socketTimeout).setStaleConnectionCheckEnabled(true).setExpectContinueEnabled(true)
            .setConnectTimeout(connectionTimeout).setConnectionRequestTimeout(socketTimeout);

    // If there's a proxy, set that too.
    if (proxyHost != null && proxyHost.length() > 0) {

        // Configure proxy authentication
        if (proxyUsername != null && proxyUsername.length() > 0) {
            if (proxyPassword == null)
                proxyPassword = "";
            if (proxyDomain == null)
                proxyDomain = "";

            credentialsProvider.setCredentials(new AuthScope(proxyHost, proxyPort),
                    new NTCredentials(proxyUsername, proxyPassword, currentHost, proxyDomain));
        }

        HttpHost proxy = new HttpHost(proxyHost, proxyPort);
        requestBuilder.setProxy(proxy);
    }

    httpClient = HttpClients.custom().setConnectionManager(connectionManager).setMaxConnTotal(1)
            .disableAutomaticRetries().setDefaultRequestConfig(requestBuilder.build())
            .setDefaultSocketConfig(
                    SocketConfig.custom().setTcpNoDelay(true).setSoTimeout(socketTimeout).build())
            .setDefaultCredentialsProvider(credentialsProvider).setSSLSocketFactory(myFactory)
            .setRequestExecutor(new HttpRequestExecutor(socketTimeout))
            .setRedirectStrategy(new DefaultRedirectStrategy()).build();

}

From source file:org.obiba.mica.core.service.AgateRestService.java

/**
 * Do not check anything from the remote host (Agate server is trusted).
 *
 * @return/*from   w  w w .j  a v a2  s. c  o  m*/
 * @throws NoSuchAlgorithmException
 * @throws KeyManagementException
 */
private SSLConnectionSocketFactory getSocketFactory() throws NoSuchAlgorithmException, KeyManagementException {
    // Accepts any SSL certificate
    TrustManager tm = new X509TrustManager() {

        @Override
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }

        @Override
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {

        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
    };
    SSLContext sslContext = SSLContext.getInstance("TLS");
    sslContext.init(null, new TrustManager[] { tm }, null);

    return new SSLConnectionSocketFactory(sslContext, new NoopHostnameVerifier());
}