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

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

Introduction

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

Prototype

public DefaultHostnameVerifier() 

Source Link

Usage

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

private IdmClient createIdmClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(this.keyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    IdmClient idmClient = new IdmClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    idmClient.setToken(restAccessToken);
    return idmClient;
}

From source file:io.fabric8.apiman.ApimanStarter.java

private static URL waitForDependency(URL url, String path, String serviceName, String key, String value,
        String username, String password) throws InterruptedException {
    boolean isFoundRunningService = false;
    ObjectMapper mapper = new ObjectMapper();
    int counter = 0;
    URL endpoint = null;//from   w  w  w. java 2s.c  om
    while (!isFoundRunningService) {
        endpoint = resolveServiceEndpoint(url.getProtocol(), url.getHost(), String.valueOf(url.getPort()));
        if (endpoint != null) {
            String isLive = null;
            try {
                URL statusURL = new URL(endpoint.toExternalForm() + path);
                HttpURLConnection urlConnection = (HttpURLConnection) statusURL.openConnection();
                urlConnection.setConnectTimeout(500);
                if (urlConnection instanceof HttpsURLConnection) {
                    try {
                        KeyStoreUtil.Info tPathInfo = new KeyStoreUtil().new Info(ApimanStarter.TRUSTSTORE_PATH,
                                ApimanStarter.TRUSTSTORE_PASSWORD_PATH);
                        TrustManager[] tms = KeyStoreUtil.getTrustManagers(tPathInfo);
                        KeyStoreUtil.Info kPathInfo = new KeyStoreUtil().new Info(
                                ApimanStarter.CLIENT_KEYSTORE_PATH,
                                ApimanStarter.CLIENT_KEYSTORE_PASSWORD_PATH);
                        KeyManager[] kms = KeyStoreUtil.getKeyManagers(kPathInfo);
                        final SSLContext sc = SSLContext.getInstance("TLS");
                        sc.init(kms, tms, new java.security.SecureRandom());
                        final SSLSocketFactory socketFactory = sc.getSocketFactory();
                        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
                        HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
                        httpsConnection.setHostnameVerifier(new DefaultHostnameVerifier());
                        httpsConnection.setSSLSocketFactory(socketFactory);
                    } catch (Exception e) {
                        log.error(e.getMessage(), e);
                        throw e;
                    }
                }
                if (Utils.isNotNullOrEmpty(username)) {
                    String encoded = Base64.getEncoder()
                            .encodeToString((username + ":" + password).getBytes("UTF-8"));
                    urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
                    log.info(username + ":" + "*****");
                }
                isLive = IOUtils.toString(urlConnection.getInputStream());
                Map<String, Object> esResponse = mapper.readValue(isLive,
                        new TypeReference<Map<String, Object>>() {
                        });
                if (esResponse.containsKey(key) && value.equals(String.valueOf(esResponse.get(key)))) {
                    isFoundRunningService = true;
                } else {
                    if (counter % 10 == 0)
                        log.info(endpoint.toExternalForm() + " not yet up. " + isLive);
                }
            } catch (Exception e) {
                if (counter % 10 == 0)
                    log.info(endpoint.toExternalForm() + " not yet up. " + e.getMessage());
            }
        } else {
            if (counter % 10 == 0)
                log.info("Could not find " + serviceName + " in namespace, waiting..");
        }
        counter++;
        Thread.sleep(1000l);
    }
    return endpoint;
}

From source file:com.vmware.identity.openidconnect.sample.RelyingPartyInstaller.java

private VmdirClient createVMdirClient(AccessToken accessToken, String domainControllerFQDN,
        int domainControllerPort) throws Exception {
    TrustManagerFactory trustManagerFactory = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());
    trustManagerFactory.init(this.keyStore);
    SSLContext sslContext = SSLContext.getInstance("SSL");
    sslContext.init(null, trustManagerFactory.getTrustManagers(), null);
    VmdirClient vmdirClient = new VmdirClient(domainControllerFQDN, domainControllerPort,
            new DefaultHostnameVerifier(), sslContext);
    com.vmware.identity.rest.core.client.AccessToken restAccessToken = new com.vmware.identity.rest.core.client.AccessToken(
            accessToken.getValue(), com.vmware.identity.rest.core.client.AccessToken.Type.JWT);
    vmdirClient.setToken(restAccessToken);
    return vmdirClient;
}

From source file:com.spotify.helios.client.DefaultRequestDispatcher.java

private HttpURLConnection connect0(final URI ipUri, final String method, final byte[] entity,
        final Map<String, List<String>> headers, final String hostname, final AgentProxy agentProxy,
        final Identity identity) throws IOException {
    if (log.isTraceEnabled()) {
        log.trace("req: {} {} {} {} {} {}", method, ipUri, headers.size(),
                Joiner.on(',').withKeyValueSeparator("=").join(headers), entity.length,
                Json.asPrettyStringUnchecked(entity));
    } else {/*from   w  w w.  j ava  2s  .  c o  m*/
        log.debug("req: {} {} {} {}", method, ipUri, headers.size(), entity.length);
    }

    final URLConnection urlConnection = ipUri.toURL().openConnection();
    final HttpURLConnection connection = (HttpURLConnection) urlConnection;

    // We verify the TLS certificate against the original hostname since verifying against the
    // IP address will fail
    if (urlConnection instanceof HttpsURLConnection) {
        System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
        connection.setRequestProperty("Host", hostname);

        final HttpsURLConnection httpsConnection = (HttpsURLConnection) urlConnection;
        httpsConnection.setHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String ip, SSLSession sslSession) {
                final String tHostname = hostname.endsWith(".") ? hostname.substring(0, hostname.length() - 1)
                        : hostname;
                return new DefaultHostnameVerifier().verify(tHostname, sslSession);
            }
        });

        if (!isNullOrEmpty(user) && (agentProxy != null) && (identity != null)) {
            final SSLSocketFactory factory = new SshAgentSSLSocketFactory(agentProxy, identity, user);
            httpsConnection.setSSLSocketFactory(factory);
        }
    }

    connection.setRequestProperty("Accept-Encoding", "gzip");
    connection.setInstanceFollowRedirects(false);
    connection.setConnectTimeout((int) HTTP_TIMEOUT_MILLIS);
    connection.setReadTimeout((int) HTTP_TIMEOUT_MILLIS);
    for (Map.Entry<String, List<String>> header : headers.entrySet()) {
        for (final String value : header.getValue()) {
            connection.addRequestProperty(header.getKey(), value);
        }
    }
    if (entity.length > 0) {
        connection.setDoOutput(true);
        connection.getOutputStream().write(entity);
    }
    if (urlConnection instanceof HttpsURLConnection) {
        setRequestMethod(connection, method, true);
    } else {
        setRequestMethod(connection, method, false);
    }

    final int responseCode = connection.getResponseCode();
    if (responseCode == HTTP_BAD_GATEWAY) {
        throw new ConnectException("502 Bad Gateway");
    }

    return connection;
}

From source file:org.commonjava.util.jhttpc.HttpFactory.java

private SSLConnectionSocketFactory createSSLSocketFactory(final SiteConfig location) throws JHttpCException {
    SSLConnectionSocketFactory fac = (SSLConnectionSocketFactory) location.getAttribute(SSL_FACTORY_ATTRIB);
    if (fac != null) {
        return fac;
    }/*from  w  w w .  j  a  v  a2s  .c om*/

    KeyStore ks = null;
    KeyStore ts = null;

    final String kcPem = location.getKeyCertPem();

    final String kcPass = passwords.lookup(new PasswordKey(location, PasswordType.KEY));
    if (kcPem != null) {
        logger.debug("Adding client key/certificate from: {}", location);
        if (kcPass == null || kcPass.length() < 1) {
            logger.error("Invalid configuration. Location: {} cannot have an empty key password!",
                    location.getUri());
            throw new JHttpCException(
                    "Location: " + location.getUri() + " is misconfigured! Key password cannot be empty.");
        }

        try {
            logger.trace("Reading Client SSL key from:\n\n{}\n\n", kcPem);
            ks = SSLUtils.readKeyAndCert(kcPem, kcPass);

            logger.trace("Keystore contains the following certificates: {}", new CertEnumerator(ks, kcPass));
        } catch (final CertificateException e) {
            logger.error(String.format(
                    "Invalid configuration. Location: %s has an invalid client certificate! Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final InvalidKeySpecException e) {
            logger.error(
                    String.format("Invalid configuration. Invalid client key for repository: %s. Error: %s",
                            location.getUri(), e.getMessage()),
                    e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (IOException e) {
            throw new JHttpCException("Failed to read client SSL key/certificate from: %s. Reason: %s", e,
                    location, e.getMessage());
        } catch (JHttpCException e) {
            throw new JHttpCException("Failed to read client SSL key/certificate from: %s. Reason: %s", e,
                    location, e.getMessage());
        }
    } else {
        logger.debug("No client key/certificate found");
    }

    final String sPem = location.getServerCertPem();

    //        logger.debug( "Server certificate PEM:\n{}", sPem );
    if (sPem != null) {
        logger.debug("Loading TrustStore (server SSL) information from: {}", location);
        try {
            logger.trace("Reading Server SSL cert from:\n\n{}\n\n", sPem);
            ts = SSLUtils.decodePEMTrustStore(sPem, location.getHost());

            logger.trace("Trust store contains the following certificates:\n{}", new CertEnumerator(ts, null));
        } catch (final CertificateException e) {
            logger.error(String.format(
                    "Invalid configuration. Location: %s has an invalid server certificate! Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(String.format(
                    "Invalid configuration. Cannot initialize keystore for repository: %s. Error: %s",
                    location.getUri(), e.getMessage()), e);
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (IOException e) {
            throw new JHttpCException(
                    "Failed to read server SSL certificate(s) (or couldn't parse server hostname) from: %s. Reason: %s",
                    e, location, e.getMessage());
        }
    } else {
        logger.debug("No server certificates found");
    }

    if (ks != null || ts != null) {
        logger.debug("Setting up SSL context.");
        try {
            SSLContextBuilder sslBuilder = SSLContexts.custom().useProtocol(SSLConnectionSocketFactory.TLS);
            if (ks != null) {
                logger.trace("Loading key material for SSL context...");
                PrivateKeyStrategy pkStrategy = new MonolithicKeyStrategy();
                sslBuilder.loadKeyMaterial(ks, kcPass.toCharArray(), pkStrategy);
            }

            if (ts != null) {
                logger.trace("Loading trust material for SSL context...");

                SiteTrustType trustType = location.getTrustType();
                if (trustType == null) {
                    trustType = SiteTrustType.DEFAULT;
                }

                sslBuilder.loadTrustMaterial(ts, trustType.getTrustStrategy());
            }

            SSLContext ctx = sslBuilder.build();

            fac = new SSLConnectionSocketFactory(ctx, new DefaultHostnameVerifier());
            location.setAttribute(SSL_FACTORY_ATTRIB, fac);
            return fac;
        } catch (final KeyManagementException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final UnrecoverableKeyException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final NoSuchAlgorithmException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        } catch (final KeyStoreException e) {
            logger.error(
                    "Invalid configuration. Cannot initialize SSL socket factory for repository: {}. Error: {}",
                    e, location.getUri(), e.getMessage());
            throw new JHttpCException(
                    "Failed to initialize SSL connection for repository: " + location.getUri());
        }
    } else {
        logger.debug("No SSL configuration present; no SSL context created.");
    }

    return null;
}

From source file:nl.nn.adapterframework.http.HttpSenderBase.java

public void configure() throws ConfigurationException {
    super.configure();

    if (!getMethodType().equals("POST")) {
        if (!isParamsInUrl()) {
            throw new ConfigurationException(
                    getLogPrefix() + "paramsInUrl can only be set to false for methodType POST");
        }//  ww  w .j a v  a2 s . c  o m
        if (StringUtils.isNotEmpty(getInputMessageParam())) {
            throw new ConfigurationException(
                    getLogPrefix() + "inputMessageParam can only be set for methodType POST");
        }
    }

    /**
     * TODO find out if this really breaks proxy authentication or not.
     */
    //      httpClientBuilder.disableAuthCaching();
    httpClientBuilder.disableAutomaticRetries();

    Builder requestConfig = RequestConfig.custom();
    requestConfig.setConnectTimeout(getTimeout());
    requestConfig.setConnectionRequestTimeout(getTimeout());
    requestConfig.setSocketTimeout(getTimeout());

    if (paramList != null) {
        paramList.configure();
        if (StringUtils.isNotEmpty(getUrlParam())) {
            urlParameter = paramList.findParameter(getUrlParam());
            addParameterToSkip(urlParameter);
        }
    }
    if (getMaxConnections() <= 0) {
        throw new ConfigurationException(getLogPrefix() + "maxConnections is set to [" + getMaxConnections()
                + "], which is not enough for adequate operation");
    }
    try {
        if (urlParameter == null) {
            if (StringUtils.isEmpty(getUrl())) {
                throw new ConfigurationException(
                        getLogPrefix() + "url must be specified, either as attribute, or as parameter");
            }
            staticUri = getURI(getUrl());
        }

        URL certificateUrl = null;
        URL truststoreUrl = null;

        if (!StringUtils.isEmpty(getCertificate())) {
            certificateUrl = ClassUtils.getResourceURL(getClassLoader(), getCertificate());
            if (certificateUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for certificate resource [" + getCertificate() + "]");
            }
            log.info(getLogPrefix() + "resolved certificate-URL to [" + certificateUrl.toString() + "]");
        }
        if (!StringUtils.isEmpty(getTruststore())) {
            truststoreUrl = ClassUtils.getResourceURL(getClassLoader(), getTruststore());
            if (truststoreUrl == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find URL for truststore resource [" + getTruststore() + "]");
            }
            log.info(getLogPrefix() + "resolved truststore-URL to [" + truststoreUrl.toString() + "]");
        }

        HostnameVerifier hostnameVerifier = new DefaultHostnameVerifier();
        if (!isVerifyHostname())
            hostnameVerifier = new NoopHostnameVerifier();

        // Add javax.net.ssl.SSLSocketFactory.getDefault() SSLSocketFactory if non has been set.
        // See: http://httpcomponents.10934.n7.nabble.com/Upgrading-commons-httpclient-3-x-to-HttpClient4-x-td19333.html
        // 
        // The first time this method is called, the security property "ssl.SocketFactory.provider" is examined. 
        // If it is non-null, a class by that name is loaded and instantiated. If that is successful and the 
        // object is an instance of SSLSocketFactory, it is made the default SSL socket factory.
        // Otherwise, this method returns SSLContext.getDefault().getSocketFactory(). If that call fails, an inoperative factory is returned.
        javax.net.ssl.SSLSocketFactory socketfactory = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory
                .getDefault();
        sslSocketFactory = new SSLConnectionSocketFactory(socketfactory, hostnameVerifier);

        if (certificateUrl != null || truststoreUrl != null || isAllowSelfSignedCertificates()) {
            try {
                CredentialFactory certificateCf = new CredentialFactory(getCertificateAuthAlias(), null,
                        getCertificatePassword());
                CredentialFactory truststoreCf = new CredentialFactory(getTruststoreAuthAlias(), null,
                        getTruststorePassword());

                SSLContext sslContext = AuthSSLConnectionSocket.createSSLContext(certificateUrl,
                        certificateCf.getPassword(), getKeystoreType(), getKeyManagerAlgorithm(), truststoreUrl,
                        truststoreCf.getPassword(), getTruststoreType(), getTrustManagerAlgorithm(),
                        isAllowSelfSignedCertificates(), isVerifyHostname(),
                        isIgnoreCertificateExpiredException(), getProtocol());

                sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
                log.debug(getLogPrefix() + "created custom SSLConnectionSocketFactory");

            } catch (Throwable t) {
                throw new ConfigurationException(getLogPrefix() + "cannot create or initialize SocketFactory",
                        t);
            }
        }

        // This method will be overwritten by the connectionManager when connectionPooling is enabled!
        // Can still be null when no default or an invalid system sslSocketFactory has been defined
        if (sslSocketFactory != null)
            httpClientBuilder.setSSLSocketFactory(sslSocketFactory);

        credentials = new CredentialFactory(getAuthAlias(), getUserName(), getPassword());
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        if (!StringUtils.isEmpty(credentials.getUsername())) {
            String uname;
            if (StringUtils.isNotEmpty(getAuthDomain())) {
                uname = getAuthDomain() + "\\" + credentials.getUsername();
            } else {
                uname = credentials.getUsername();
            }

            credentialsProvider.setCredentials(new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT),
                    new UsernamePasswordCredentials(uname, credentials.getPassword()));

            requestConfig.setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));
            requestConfig.setAuthenticationEnabled(true);
        }
        if (StringUtils.isNotEmpty(getProxyHost())) {
            HttpHost proxy = new HttpHost(getProxyHost(), getProxyPort());
            AuthScope scope = new AuthScope(proxy, getProxyRealm(), AuthScope.ANY_SCHEME);

            CredentialFactory pcf = new CredentialFactory(getProxyAuthAlias(), getProxyUserName(),
                    getProxyPassword());

            if (StringUtils.isNotEmpty(pcf.getUsername())) {
                Credentials credentials = new UsernamePasswordCredentials(pcf.getUsername(), pcf.getPassword());
                credentialsProvider.setCredentials(scope, credentials);
            }
            log.trace("setting credentialProvider [" + credentialsProvider.toString() + "]");

            if (prefillProxyAuthCache()) {
                requestConfig.setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC));

                AuthCache authCache = httpClientContext.getAuthCache();
                if (authCache == null)
                    authCache = new BasicAuthCache();

                authCache.put(proxy, new BasicScheme());
                httpClientContext.setAuthCache(authCache);
            }

            requestConfig.setProxy(proxy);
            httpClientBuilder.setProxy(proxy);
        }

        httpClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
    } catch (URISyntaxException e) {
        throw new ConfigurationException(getLogPrefix() + "cannot interpret uri [" + getUrl() + "]");
    }

    if (StringUtils.isNotEmpty(getStyleSheetName())) {
        try {
            URL stylesheetURL = ClassUtils.getResourceURL(getClassLoader(), getStyleSheetName());
            if (stylesheetURL == null) {
                throw new ConfigurationException(
                        getLogPrefix() + "cannot find stylesheet [" + getStyleSheetName() + "]");
            }
            transformerPool = TransformerPool.getInstance(stylesheetURL);
        } catch (IOException e) {
            throw new ConfigurationException(getLogPrefix() + "cannot retrieve [" + getStyleSheetName() + "]",
                    e);
        } catch (TransformerConfigurationException te) {
            throw new ConfigurationException(
                    getLogPrefix() + "got error creating transformer from file [" + getStyleSheetName() + "]",
                    te);
        }
    }

    httpClientBuilder.setDefaultRequestConfig(requestConfig.build());

    // The redirect strategy used to only redirect GET, DELETE and HEAD.
    httpClientBuilder.setRedirectStrategy(new DefaultRedirectStrategy() {
        @Override
        protected boolean isRedirectable(String method) {
            return isFollowRedirects();
        }
    });
}

From source file:com.networknt.client.Client.java

private HostnameVerifier hostnameVerifier() {
    Map<String, Object> tlsMap = (Map) config.get(TLS);
    HostnameVerifier verifier = null;
    if (tlsMap != null) {
        Boolean verifyHostname = (Boolean) tlsMap.get(VERIFY_HOSTNAME);
        if (verifyHostname != null && verifyHostname == false) {
            verifier = new NoopHostnameVerifier();
        } else {//from   w  w w.j av  a 2s  .  c  o  m
            verifier = new DefaultHostnameVerifier();
        }
    }
    return verifier;
}

From source file:org.elasticsearch.xpack.security.authc.saml.SamlRealm.java

private static Tuple<AbstractReloadingMetadataResolver, Supplier<EntityDescriptor>> parseHttpMetadata(
        String metadataUrl, RealmConfig config, SSLService sslService)
        throws ResolverException, ComponentInitializationException, PrivilegedActionException {
    final String entityId = require(config, IDP_ENTITY_ID);

    HttpClientBuilder builder = HttpClientBuilder.create();
    // ssl setup//from ww  w . j  a  va  2  s .  c  o m
    Settings sslSettings = config.settings().getByPrefix(SamlRealmSettings.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);
    builder.setSSLSocketFactory(factory);

    HTTPMetadataResolver resolver = new PrivilegedHTTPMetadataResolver(builder.build(), metadataUrl);
    TimeValue refresh = IDP_METADATA_HTTP_REFRESH.get(config.settings());
    resolver.setMinRefreshDelay(refresh.millis());
    resolver.setMaxRefreshDelay(refresh.millis());
    initialiseResolver(resolver, config);

    return new Tuple<>(resolver, () -> {
        // for some reason the resolver supports its own trust engine and custom socket factories.
        // we do not use these as we'd rather rely on the JDK versions for TLS security!
        SpecialPermission.check();
        try {
            return AccessController.doPrivileged(
                    (PrivilegedExceptionAction<EntityDescriptor>) () -> resolveEntityDescriptor(resolver,
                            entityId, metadataUrl));
        } catch (PrivilegedActionException e) {
            throw ExceptionsHelper.convertToRuntime((Exception) ExceptionsHelper.unwrapCause(e));
        }
    });
}

From source file:org.apache.http.localserver.AbstractAsyncTest.java

@Before
public void setUp() throws Exception {
    this.serverBootstrap = ServerBootstrap.bootstrap();
    final IOReactorConfig ioReactorConfig = IOReactorConfig.custom().setSoTimeout(15000).build();
    this.serverBootstrap.setServerInfo("TEST/1.1");
    this.serverBootstrap.setIOReactorConfig(ioReactorConfig);
    this.serverBootstrap.setExceptionLogger(new ExceptionLogger() {

        private final Log log = LogFactory.getLog(AbstractAsyncTest.class);

        @Override//from   w  w w. j a  v  a2  s. c o  m
        public void log(final Exception ex) {
            log.error(ex.getMessage(), ex);
        }
    });
    if (this.scheme.equals(ProtocolScheme.https)) {
        this.serverBootstrap.setSslContext(createServerSSLContext());
    }

    final RegistryBuilder<SchemeIOSessionStrategy> builder = RegistryBuilder.create();
    builder.register("http", NoopIOSessionStrategy.INSTANCE);
    if (this.scheme.equals(ProtocolScheme.https)) {
        builder.register("https",
                new SSLIOSessionStrategy(createClientSSLContext(), new DefaultHostnameVerifier()));
    }
    final Registry<SchemeIOSessionStrategy> registry = builder.build();
    final DefaultConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(ioReactorConfig);
    this.connMgr = new PoolingNHttpClientConnectionManager(ioReactor, registry);
}

From source file:org.apache.nutch.indexwriter.elasticrest.ElasticRestIndexWriter.java

@Override
public void open(IndexWriterParams parameters) throws IOException {
    host = parameters.get(ElasticRestConstants.HOST);
    if (StringUtils.isBlank(host)) {
        String message = "Missing host. It should be set in index-writers.xml";
        message += "\n" + describe();
        LOG.error(message);//from w w w.  ja v a 2 s.c o m
        throw new RuntimeException(message);
    }

    port = parameters.getInt(ElasticRestConstants.PORT, 9200);
    user = parameters.get(ElasticRestConstants.USER);
    password = parameters.get(ElasticRestConstants.PASSWORD);
    https = parameters.getBoolean(ElasticRestConstants.HTTPS, false);
    trustAllHostnames = parameters.getBoolean(ElasticRestConstants.HOSTNAME_TRUST, false);

    languages = parameters.getStrings(ElasticRestConstants.LANGUAGES);
    separator = parameters.get(ElasticRestConstants.SEPARATOR, DEFAULT_SEPARATOR);
    sink = parameters.get(ElasticRestConstants.SINK, DEFAULT_SINK);

    // trust ALL certificates
    SSLContext sslContext = null;
    try {
        sslContext = new SSLContextBuilder().loadTrustMaterial(new TrustStrategy() {
            public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
                return true;
            }
        }).build();
    } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) {
        LOG.error("Failed to instantiate sslcontext object: \n{}", ExceptionUtils.getStackTrace(e));
        throw new SecurityException();
    }

    // skip hostname checks
    HostnameVerifier hostnameVerifier = null;
    if (trustAllHostnames) {
        hostnameVerifier = NoopHostnameVerifier.INSTANCE;
    } else {
        hostnameVerifier = new DefaultHostnameVerifier();
    }

    SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext);
    SchemeIOSessionStrategy httpsIOSessionStrategy = new SSLIOSessionStrategy(sslContext, hostnameVerifier);

    JestClientFactory jestClientFactory = new JestClientFactory();
    URL urlOfElasticsearchNode = new URL(https ? "https" : "http", host, port, "");

    if (host != null && port > 1) {
        HttpClientConfig.Builder builder = new HttpClientConfig.Builder(urlOfElasticsearchNode.toString())
                .multiThreaded(true).connTimeout(300000).readTimeout(300000);
        if (https) {
            if (user != null && password != null) {
                builder.defaultCredentials(user, password);
            }
            builder.defaultSchemeForDiscoveredNodes("https").sslSocketFactory(sslSocketFactory) // this only affects sync calls
                    .httpsIOSessionStrategy(httpsIOSessionStrategy); // this only affects async calls
        }
        jestClientFactory.setHttpClientConfig(builder.build());
    } else {
        throw new IllegalStateException(
                "No host or port specified. Please set the host and port in nutch-site.xml");
    }

    client = jestClientFactory.getObject();

    defaultIndex = parameters.get(ElasticRestConstants.INDEX, "nutch");
    defaultType = parameters.get(ElasticRestConstants.TYPE, "doc");

    maxBulkDocs = parameters.getInt(ElasticRestConstants.MAX_BULK_DOCS, DEFAULT_MAX_BULK_DOCS);
    maxBulkLength = parameters.getInt(ElasticRestConstants.MAX_BULK_LENGTH, DEFAULT_MAX_BULK_LENGTH);

    bulkBuilder = new Bulk.Builder().defaultIndex(defaultIndex).defaultType(defaultType);
}