Java 类org.apache.http.nio.conn.ssl.SSLIOSessionStrategy 实例源码

项目:loginsight-java-api    文件:AsyncLogInsightConnectionStrategy.java   
/**
 * Initializes and returns the httpClient with NoopHostnameVerifier
 * 
 * @return CloseableHttpAsyncClient
 */
@Override
public CloseableHttpAsyncClient getHttpClient() {
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = NonValidatingSSLSocketFactory.getSSLContext();
    // Allow TLSv1 protocol only

    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" }, null,
            new NoopHostnameVerifier());
    List<Header> headers = LogInsightClient.getDefaultHeaders();

    asyncHttpClient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).setDefaultHeaders(headers)
            .build();
    asyncHttpClient.start();

    return asyncHttpClient;
}
项目:currencybg.server    文件:AbstractSource.java   
/**
 * Creates an asynchronous HTTP client configuration with default timeouts.
 *
 * @see #newHttpAsyncClient(boolean)
 */
protected static CloseableHttpAsyncClient newHttpAsyncClient(boolean useSSL) {
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(DEFAULT_SOCKET_TIMEOUT)
            .setConnectTimeout(DEFAULT_CONNECT_TIMEOUT).build();

    HttpAsyncClientBuilder builder = HttpAsyncClients.custom();

    if (useSSL) {
        try {
            SSLContext context = SSLContext.getInstance("SSL");
            context.init(null, new TrustManager[]{new TrustAllX509Manager()}, new SecureRandom());

            SSLIOSessionStrategy strategy = new SSLIOSessionStrategy(context,
                    SSLIOSessionStrategy.getDefaultHostnameVerifier());

            builder.setSSLStrategy(strategy);
        } catch (Exception e) {
            log.error("Failed initializing SSL context! Skipped.", e);
        }
    }

    return builder.setDefaultRequestConfig(requestConfig).build();
}
项目:restendpoint    文件:RestEndpoints.java   
/**
     * Adds Keystore for SSL
     *
     * @param keyStore     KeyStore input stream
     * @param keyStorePass KeyStore password
     * @return This builder
     */
    public final Builder withSsl(InputStream keyStore, String keyStorePass) {
        SSLContext sslcontext;
        try {
            sslcontext = org.apache.http.ssl.SSLContexts.custom().loadTrustMaterial(IOUtils.loadKeyStore(keyStore, keyStorePass), null)
                    .build();
        } catch (Exception e) {
            throw new IllegalArgumentException("Unable to load trust store", e);
        }

        /*
         * Unreal magic, but we can't use
* org.apache.http.conn.ssl.SSLConnectionSocketFactory
* .BROWSER_COMPATIBLE_HOSTNAME_VERIFIER here due to some problems
* related to classloaders. Initialize host name verifier explicitly
*/
        SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(
                sslcontext,
                new DefaultHostnameVerifier());
        httpClientBuilder.setSSLStrategy(sslSessionStrategy);

        return this;
    }
项目:apiman    文件:DefaultEsClientFactory.java   
/**
 * @param httpConfig
 */
@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);
    }
}
项目:apiman    文件:DefaultESClientFactory.java   
/**
 * @param httpConfig
 * @param config 
 */
@SuppressWarnings("nls")
private void updateSslConfig(Builder httpConfig, Map<String, String> config) {
    try {
        String clientKeystorePath = config.get("client-keystore");
        String clientKeystorePassword = config.get("client-keystore.password");
        String trustStorePath = config.get("trust-store");
        String trustStorePassword = config.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);
    }
}
项目:elasticsearch_my    文件:ESRestTestCase.java   
protected RestClient buildClient(Settings settings, HttpHost[] hosts) throws IOException {
    RestClientBuilder builder = RestClient.builder(hosts);
    String keystorePath = settings.get(TRUSTSTORE_PATH);
    if (keystorePath != null) {
        final String keystorePass = settings.get(TRUSTSTORE_PASSWORD);
        if (keystorePass == null) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is provided but not " + TRUSTSTORE_PASSWORD);
        }
        Path path = PathUtils.get(keystorePath);
        if (!Files.exists(path)) {
            throw new IllegalStateException(TRUSTSTORE_PATH + " is set but points to a non-existing file");
        }
        try {
            KeyStore keyStore = KeyStore.getInstance("jks");
            try (InputStream is = Files.newInputStream(path)) {
                keyStore.load(is, keystorePass.toCharArray());
            }
            SSLContext sslcontext = SSLContexts.custom().loadTrustMaterial(keyStore, null).build();
            SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslcontext);
            builder.setHttpClientConfigCallback(httpClientBuilder -> httpClientBuilder.setSSLStrategy(sessionStrategy));
        } catch (KeyStoreException|NoSuchAlgorithmException|KeyManagementException|CertificateException e) {
            throw new RuntimeException("Error setting up ssl", e);
        }
    }

    try (ThreadContext threadContext = new ThreadContext(settings)) {
        Header[] defaultHeaders = new Header[threadContext.getHeaders().size()];
        int i = 0;
        for (Map.Entry<String, String> entry : threadContext.getHeaders().entrySet()) {
            defaultHeaders[i++] = new BasicHeader(entry.getKey(), entry.getValue());
        }
        builder.setDefaultHeaders(defaultHeaders);
    }
    return builder.build();
}
项目:yunpian-java-sdk    文件:AsyncClientCustomSSL.java   
public final static void main(String[] args) throws Exception {
    // KeyStore trustStore =
    // KeyStore.getInstance(KeyStore.getDefaultType());
    // FileInputStream instream = new FileInputStream(new
    // File("my.keystore"));
    // try {
    // trustStore.load(instream, "nopassword".toCharArray());
    // } finally {
    // instream.close();
    // }
    // // Trust own CA and all self-signed certs
    // SSLContext sslcontext =
    // SSLContexts.custom().loadTrustMaterial(trustStore, new
    // TrustSelfSignedStrategy())
    // .build();
    SSLContext sslcontext = SSLContexts.createDefault();
    // Allow TLSv1 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(sslcontext, new String[] { "TLSv1" }, null,
            SSLIOSessionStrategy.getDefaultHostnameVerifier());
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setSSLStrategy(sslSessionStrategy).build();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("https://github.com/dzh");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
项目:Android-Studio-Translate-Tool    文件:AsyncClientCustomSSL.java   
public final static void main(String[] args) throws Exception {
    KeyStore trustStore  = KeyStore.getInstance(KeyStore.getDefaultType());
    FileInputStream instream = new FileInputStream(new File("my.keystore"));
    try {
        trustStore.load(instream, "nopassword".toCharArray());
    } finally {
        instream.close();
    }
    // Trust own CA and all self-signed certs
    SSLContext sslcontext = SSLContexts.custom()
            .loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
            .build();
    // Allow TLSv1 protocol only
    SSLIOSessionStrategy sslSessionStrategy = new SSLIOSessionStrategy(
            sslcontext,
            new String[] { "TLSv1" },
            null,
            SSLIOSessionStrategy.getDefaultHostnameVerifier());
    CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom()
            .setSSLStrategy(sslSessionStrategy)
            .build();
    try {
        httpclient.start();
        HttpGet request = new HttpGet("https://issues.apache.org/");
        Future<HttpResponse> future = httpclient.execute(request, null);
        HttpResponse response = future.get();
        System.out.println("Response: " + response.getStatusLine());
        System.out.println("Shutting down");
    } finally {
        httpclient.close();
    }
    System.out.println("Done");
}
项目:oap    文件:Client.java   
private HttpAsyncClientBuilder initialize() {
    try {
        final PoolingNHttpClientConnectionManager connManager = new PoolingNHttpClientConnectionManager(
            new DefaultConnectingIOReactor( IOReactorConfig.custom()
                .setConnectTimeout( connectTimeout )
                .setSoTimeout( readTimeout )
                .build() ),
            RegistryBuilder.<SchemeIOSessionStrategy>create()
                .register( "http", NoopIOSessionStrategy.INSTANCE )
                .register( "https",
                    new SSLIOSessionStrategy( certificateLocation != null ?
                        createSSLContext( certificateLocation, certificatePassword )
                        : SSLContexts.createDefault(),
                        split( System.getProperty( "https.protocols" ) ),
                        split( System.getProperty( "https.cipherSuites" ) ),
                        new DefaultHostnameVerifier( PublicSuffixMatcherLoader.getDefault() ) ) )
                .build() );

        connManager.setMaxTotal( maxConnTotal );
        connManager.setDefaultMaxPerRoute( maxConnPerRoute );

        return ( certificateLocation != null ?
            HttpAsyncClients.custom()
                .setSSLContext( createSSLContext( certificateLocation, certificatePassword ) )
            : HttpAsyncClients.custom() )
            .setMaxConnPerRoute( maxConnPerRoute )
            .setConnectionManager( connManager )
            .setMaxConnTotal( maxConnTotal )
            .setKeepAliveStrategy( DefaultConnectionKeepAliveStrategy.INSTANCE )
            .setDefaultRequestConfig( RequestConfig
                .custom()
                .setRedirectsEnabled( redirectsEnabled )
                .setCookieSpec( cookieSpec )
                .build() )
            .setDefaultCookieStore( basicCookieStore );
    } catch( IOReactorException e ) {
        throw new UncheckedIOException( e );
    }
}
项目:java-restclient    文件:HTTPCBuilder.java   
protected ExecCallbackAsyncREST<HttpResponse> buildAsyncClient(RESTPool pool) throws IOException {
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getDefault();
    } catch (NoSuchAlgorithmException e) {
        throw new IOException(e);
    }

    Registry<SchemeIOSessionStrategy> socketRegistry = RegistryBuilder.<SchemeIOSessionStrategy>create()
            .register("http", NoopIOSessionStrategy.INSTANCE)
            .register("https", new SSLIOSessionStrategy(sslContext, NoopHostnameVerifier.INSTANCE))
            .build();

    IOReactorConfig socketConfig = IOReactorConfig.custom()
            .setIoThreadCount(pool.getReactorThreadCount())
            .setSoTimeout(new Long(pool.getSocketTimeout()).intValue())
            .setTcpNoDelay(true)
            .setSoKeepAlive(true)
            .setSelectInterval(REACTOR_SELECT_INTERVAL)
            .build();

    ConnectionConfig connectionConfig = ConnectionConfig.custom()
            .setCharset(StandardCharsets.UTF_8)
            .setMalformedInputAction(CodingErrorAction.IGNORE)
            .setUnmappableInputAction(CodingErrorAction.IGNORE)
            .build();

    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectionRequestTimeout(new Long(pool.getMaxPoolWait()).intValue())
            .setConnectTimeout(new Long(pool.getConnectionTimeout()).intValue())
            .setExpectContinueEnabled(pool.expectContinue())
            .setRedirectsEnabled(false)
            .setStaleConnectionCheckEnabled(pool.getValidationOnInactivity() >= 0)
            .build();

    NHttpConnectionFactory<ManagedNHttpClientConnection> connFactory = new ManagedNHttpClientConnectionFactory(
            new org.apache.http.impl.nio.codecs.DefaultHttpRequestWriterFactory(),
            new org.apache.http.impl.nio.codecs.DefaultHttpResponseParserFactory(),
            HeapByteBufferAllocator.INSTANCE
    );

    //TODO set validateAfterInactivity when supported
    PoolingNHttpClientConnectionManager ccm = new PoolingNHttpClientConnectionManager(
            new DefaultConnectingIOReactor(socketConfig),
            connFactory,
            socketRegistry,
            new SystemDefaultDnsResolver()
    );

    ccm.setMaxTotal(pool.getMaxTotal());
    ccm.setDefaultMaxPerRoute(pool.getMaxPerRoute());
    ccm.setDefaultConnectionConfig(connectionConfig);

    HttpAsyncClientBuilder builder = HttpAsyncClients.custom()
            .setConnectionManager(ccm)
            .setDefaultRequestConfig(requestConfig)
            .setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE)
            .disableCookieManagement();

    IdleAsyncConnectionEvictor evictor = new IdleAsyncConnectionEvictor(ccm, pool.getEvictorSleep(), TimeUnit.MILLISECONDS, pool.getMaxIdleTime(), TimeUnit.MILLISECONDS);

    addProxy(pool, builder);

    handleRedirects(pool, builder);

    CloseableHttpAsyncClient servClient = builder.build();

    servClient.start();

    HTTPCClientMonitor monitor = pool.hasConnectionMetrics() ? new HTTPCAsyncClientMonitor(pool.getName(), ccm) : null;

    return new HTTPCAsyncClient(servClient, evictor, monitor);
}
项目:beam    文件:ElasticsearchIO.java   
@VisibleForTesting
RestClient createClient() throws IOException {
  HttpHost[] hosts = new HttpHost[getAddresses().size()];
  int i = 0;
  for (String address : getAddresses()) {
    URL url = new URL(address);
    hosts[i] = new HttpHost(url.getHost(), url.getPort(), url.getProtocol());
    i++;
  }
  RestClientBuilder restClientBuilder = RestClient.builder(hosts);
  if (getUsername() != null) {
    final CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(
        AuthScope.ANY, new UsernamePasswordCredentials(getUsername(), getPassword()));
    restClientBuilder.setHttpClientConfigCallback(
        new RestClientBuilder.HttpClientConfigCallback() {
          public HttpAsyncClientBuilder customizeHttpClient(
              HttpAsyncClientBuilder httpAsyncClientBuilder) {
            return httpAsyncClientBuilder.setDefaultCredentialsProvider(credentialsProvider);
          }
        });
  }
  if (getKeystorePath() != null && !getKeystorePath().isEmpty()) {
    try {
      KeyStore keyStore = KeyStore.getInstance("jks");
      try (InputStream is = new FileInputStream(new File(getKeystorePath()))) {
        String keystorePassword = getKeystorePassword();
        keyStore.load(is, (keystorePassword == null) ? null : keystorePassword.toCharArray());
      }
      final SSLContext sslContext = SSLContexts.custom()
          .loadTrustMaterial(keyStore, new TrustSelfSignedStrategy()).build();
      final SSLIOSessionStrategy sessionStrategy = new SSLIOSessionStrategy(sslContext);
      restClientBuilder.setHttpClientConfigCallback(
          new RestClientBuilder.HttpClientConfigCallback() {
        @Override
        public HttpAsyncClientBuilder customizeHttpClient(
            HttpAsyncClientBuilder httpClientBuilder) {
          return httpClientBuilder.setSSLContext(sslContext).setSSLStrategy(sessionStrategy);
        }
      });
    } catch (Exception e) {
      throw new IOException("Can't load the client certificate from the keystore", e);
    }
  }
  return restClientBuilder.build();
}
项目:saki-monkey    文件:MandrillAsyncClient.java   
/**
 * This SSLIOSessionStategy can be overridden by createConnectionManager 
 * @return
 */
protected SSLIOSessionStrategy createSSLIOSessionStrategy(){
    return new SSLIOSessionStrategy(SSLContexts.createDefault(), 
            createHostnameVerifier());
}