private static SSLConnectionSocketFactory createSSLConnectionSocketFactory(Path path, char[] password, boolean strict, KeystoreType keystoreType) { try { SSLContextBuilder builder = SSLContexts.custom(); if (path != null) { KeyStore trustStore = KeyStore.getInstance(keystoreType.name()); try (InputStream is = Files.newInputStream(path)) { trustStore.load(is, password); } builder.loadTrustMaterial(trustStore); } else { builder.loadTrustMaterial(null, new TrustEverythingStrategy()); } X509HostnameVerifier verifier; if (strict) { verifier = SSLConnectionSocketFactory.STRICT_HOSTNAME_VERIFIER; } else { verifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; } return new SSLConnectionSocketFactory(builder.build(), new String[] {"TLSv1", "TLSv1.2"}, null, verifier); } catch (IOException | GeneralSecurityException ex) { throw new RuntimeException("Can't create SSL connection factory", ex); } }
/** * 获取LayeredConnectionSocketFactory 使用ssl单向认证 * * @date 2015年7月17日 * @return */ private LayeredConnectionSocketFactory getSSLSocketFactory() { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { // 信任所有 public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return sslsf; } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { logger.error(e.getMessage(), e); throw new RuntimeException(e.getMessage(), e); } }
public AbstractRestTemplateClient ignoreAuthenticateServer() { //backward compatible with android httpclient 4.3.x if(restTemplate.getRequestFactory() instanceof HttpComponentsClientHttpRequestFactory) { try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); X509HostnameVerifier verifier = ignoreSslWarning ? new AllowAllHostnameVerifier() : new BrowserCompatHostnameVerifier(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, verifier); HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build(); ((HttpComponentsClientHttpRequestFactory)restTemplate.getRequestFactory()).setHttpClient(httpClient); } catch (Exception e) { e.printStackTrace(); } } else { Debug.error("the request factory " + restTemplate.getRequestFactory().getClass().getName() + " does not support ignoreAuthenticateServer"); } return this; }
public static SSLConnectionSocketFactory getInstance() { if (sslConnectionSocketFactory == null) { synchronized (ConnectionManagerFactory.class) { if (sslConnectionSocketFactory == null) { try{ SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslConnectionSocketFactory = new SSLConnectionSocketFactory(builder.build()); }catch(Exception exception){ exception.getStackTrace(); } } } } return sslConnectionSocketFactory; }
private SSLConnectionSocketFactory getSSLSocketFactory() { KeyStore trustStore; try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy); sslContextBuilder.useTLS(); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); return sslSocketFactory; } catch (GeneralSecurityException | IOException e) { System.err.println("SSL Error : " + e.getMessage()); } return null; }
private CloseableHttpClient createSslHttpClient() throws Exception { final SSLContextBuilder wsBuilder = new SSLContextBuilder(); wsBuilder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(wsBuilder.build(), new AllowAllHostnameVerifier()); //This winds up using a PoolingHttpClientConnectionManager so need to pass the //RegistryBuilder final Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory> create().register("https", sslsf) .build(); final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry); return HttpClients .custom() .setConnectionManager(cm) .build(); }
public DWServerConnection(DWSettingsProvider settingsProvider) throws UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException { this.settingsProvider = settingsProvider; // SSLContextFactory to allow all hosts. Without this an SSLException is thrown with self signed certs SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build(); SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", socketFactory).build(); PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry); connectionManager.setMaxTotal(200); connectionManager.setDefaultMaxPerRoute(20); client = HttpClients.custom() .setConnectionManager(connectionManager) .build(); context = new HttpClientContext(); context.setCredentialsProvider(getCredientials()); }
/** * Produces a HTTPS client with client certificate-based authentication. * * @param keyStorePath * Key store where client certificate is stored. * @param keyStorePassword * Key store password. * @param keystoreType * The type of key store. * @return * @throws RuntimeException */ public static Client httpsCertAuth(String keyStorePath, String keyStorePassword, SslKeyStoreType keystoreType) throws RuntimeException { SSLContext sslContext; try (InputStream keystoreFile = new FileInputStream(keyStorePath)) { KeyStore keystore = KeyStore.getInstance(keystoreType.name()); keystore.load(keystoreFile, keyStorePassword.toCharArray()); sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()) .loadKeyMaterial(keystore, keyStorePassword.toCharArray()).build(); } catch (Exception e) { throw new RuntimeException("failed to set up an SSL context: " + e.getMessage(), e); } Client client = ClientBuilder.newBuilder().sslContext(sslContext).hostnameVerifier(allowAnyVerifier()).build(); client.register(new LoggingFilter()); return client; }
public CloseableHttpClient createHttpClient(boolean allowSelfSigned) throws IOException { CloseableHttpClient httpclient = null; if (allowSelfSigned) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf) .setDefaultCookieStore(cookieStore).build(); } catch (Exception e) { throw new IOException(e); } } else { httpclient = HttpClients.custom() .setDefaultCookieStore(cookieStore).build(); } return httpclient; }
/** * Create a standard builder, firefox agent and ssl easy support. * * @return the builder. */ public static HttpClientBuilder createBuilder() { try { return HttpClientBuilder .create() .setDefaultCookieStore( new BasicCookieStore() ) .setUserAgent( "Mozilla/5.0 (Windows NT 5.1; rv:15.0) Gecko/20100101 Firefox/15.0.1" ) .setSSLSocketFactory( new SSLConnectionSocketFactory( new SSLContextBuilder() .loadTrustMaterial( null , new TrustSelfSignedStrategy() ) .build() ) ); } catch( final KeyManagementException | KeyStoreException | NoSuchAlgorithmException ex ) { throw new RuntimeException( ex ); } }
private SSLContext buildSslContext() { try { SSLContextBuilder contextBuilder = new SSLContextBuilder(). useTLS(). loadTrustMaterial(null, new TrustSelfSignedStrategy()); return contextBuilder.build(); } catch (GeneralSecurityException e) { throw new CloudOperationException(e); } }
private javax.net.ssl.SSLContext buildSslContext() { try { return new SSLContextBuilder().useSSL().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); } catch (GeneralSecurityException gse) { throw new RuntimeException("An error occurred setting up the SSLContext", gse); } }
public static HttpClient createUnsafeClient() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); return HttpClients.custom() .setSSLSocketFactory(sslsf).build(); } catch (Exception e) { throw new RuntimeException(e); } }
/** * Ignore any validation about certificate. Use of this feature has security * consequences * * @return * @throws RestCallException */ public static CloseableHttpClient createIgnoringCertificate() throws RestCallException { try { CloseableHttpClient httpClient = HttpClients.custom().setHostnameVerifier(new AllowAllHostnameVerifier()) .setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, (arg0, arg1) -> true).build()).build(); return httpClient; } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { throw new RestCallException(); } }
private static CloseableHttpClient getConfiguredHttpClient() { try { return HttpClients.custom() .setDefaultRequestConfig(RequestConfig.custom().setSocketTimeout(SOCKET_TIMEOUT) .setConnectTimeout(CONNECTION_TIMEOUT).build()) .setHostnameVerifier(new AllowAllHostnameVerifier()) .setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, (_1, _2) -> true).build()).build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { throw new RuntimeException(e); } }
/** * Create a HTTP client that uses a self-signed and always trusted * SSL strategy. * * @param custom The client builder * @return builder with unsafe SSL strategy * @throws APIException If there is a problem creating the client or strategy */ private HttpClientBuilder setClientToSelfSigned( final HttpClientBuilder custom ) throws APIException { final SSLContextBuilder builder = new SSLContextBuilder(); try { builder.loadTrustMaterial( null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory( builder.build()); return custom.setSSLSocketFactory( sf ); } catch( NoSuchAlgorithmException | KeyStoreException | KeyManagementException e ) { throw new APIException( "Failed to create self-signed trust strategy and/or SSL-enabled HTTP Client", e ); } }
public static void init() throws RuntimeException { try { logger.warn(NOTICELINE + " httpUtil init begin " + NOTICELINE); SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); // sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslContextBuilder.loadTrustMaterial(null,new TrustAnyTrustManager()); SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory( sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create(). register("http", new PlainConnectionSocketFactory()). register("https", sslConnectionSocketFactory). build(); logger.warn(NOTICELINE + " SSL context init done " + NOTICELINE); //init connectionManager , ThreadSafe pooled conMgr PoolingHttpClientConnectionManager poolingHttpClientConnectionManager = new PoolingHttpClientConnectionManager(registry); poolingHttpClientConnectionManager.setMaxTotal(30); poolingHttpClientConnectionManager.setDefaultMaxPerRoute(3); //init request config. pooltimeout,sotime,contimeout RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(POOL_TIMECOUT).setConnectTimeout(CON_TIMEOUT).setSocketTimeout(SO_TIMEOUT).build(); // begin construct httpclient HttpClientBuilder httpClientBuilder = HttpClients.custom(); httpClientBuilder.setConnectionManager(poolingHttpClientConnectionManager); httpClientBuilder.setDefaultRequestConfig(requestConfig); httpClientBuilder.setRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { if (executionCount >= HTTP_RETRY_COUNT) { return false; } if (exception instanceof InterruptedIOException) { // Timeout logger.warn("httpUtil retry for InterruptIOException"); return true; } if (exception instanceof UnknownHostException) { // Unknown host return false; } if (exception instanceof SSLException) { // SSL handshake exception return false; } HttpClientContext clientContext = HttpClientContext.adapt(context); HttpRequest request = clientContext.getRequest(); boolean idempotent = !(request instanceof HttpEntityEnclosingRequest); if (idempotent) { // Retry if the request is considered idempotent logger.warn("httpUtil retry for idempotent"); return true; } return false; } }); logger.warn(NOTICELINE + " poolManager , requestconfig init done " + NOTICELINE); httpclient = httpClientBuilder.build(); logger.warn(NOTICELINE + " httpUtil init done " + NOTICELINE); } catch (Exception e) { logger.error(NOTICELINE + "httpclient init fail" + NOTICELINE, e); throw new RuntimeException(e); } }
public static HttpClient createUnsafeClient() { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory( builder.build()); CloseableHttpClient httpclient = HttpClients.custom() .setSSLSocketFactory(sslsf).build(); return httpclient; } catch (Exception e) { throw new RuntimeException(e); } }
private static CloseableHttpClient createHttpClient() { try { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); return HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build(); } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException e) { throw new RuntimeException(e); } }
private SSLContext trustAllSslContext() throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { return new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); }
private static CloseableHttpClient createHttpClientThatAcceptsAllServerCerts() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { final SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, (chain, authType) -> true); final SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); }
/** * Return a http client instance * * @param protocol- service endpoint protocol http/https * @return */ public static HttpClient getHttpClient(String protocol) throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException { HttpClient httpclient; if (HTTPS_PROTOCOL.equals(protocol)) { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else { httpclient = HttpClients.createDefault(); } return httpclient; }
public HttpClientBuilder untrustedConnectionClientBuilder() throws Exception { // setup a Trust Strategy that allows all certificates. // SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { return true; } }).build(); builder.setSslcontext(sslContext); // don't check Hostnames, either. // -- use SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; // here's the special part: // -- need to create an SSL Socket Factory, to use our weakened "trust strategy"; // -- and create a Registry, to register it. // SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, (X509HostnameVerifier) hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); // now, we create connection-manager using our Registry. // -- allows multi-threaded use PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); builder.setConnectionManager(connMgr); // finally, build the HttpClient; // -- done! return this; }
private static javax.net.ssl.SSLContext buildSslContext() { try { return new SSLContextBuilder().useSSL().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build(); } catch (GeneralSecurityException gse) { throw new RuntimeException("An error occurred setting up the SSLContext", gse); //$NON-NLS-1$ } }
protected SSLContext createSslContext() { try { SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(null, ACCEPT_ANY_CERTIFICATE_TRUST_STRATEGY); return sslContextBuilder.build(); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) { throw new IllegalStateException(e); } }
@Bean @Scope("prototype") @SuppressWarnings("deprecation") public CloseableHttpClient build() { final RequestConfig config = RequestConfig.custom() .setConnectionRequestTimeout(1000) .setConnectTimeout(1000) .setSocketTimeout(1000) .build(); try { return HttpClientBuilder.create() .disableAuthCaching() .disableAutomaticRetries() .disableConnectionState() .disableCookieManagement() .disableRedirectHandling() .setDefaultRequestConfig(config) .setUserAgent("fullstop-job (https://github.com/zalando-stups/fullstop)") .setHostnameVerifier(new AllowAllHostnameVerifier()) .setSslcontext( new SSLContextBuilder() .loadTrustMaterial( null, (arrayX509Certificate, value) -> true) .build()) .build(); } catch (NoSuchAlgorithmException | KeyManagementException | KeyStoreException e) { throw new IllegalStateException("Could not initialize httpClient", e); } }
/** * Build a HttpClient object trusting any SSL certificate. * @return HttpClient object */ @SuppressWarnings("deprecation") private HttpClient buildHttpClient() { HttpClientBuilder b = HttpClientBuilder.create(); SSLContext sslContext = null; try { sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build(); b.setSslcontext(sslContext); } catch (Exception e) { e.printStackTrace(); } // or SSLConnectionSocketFactory.getDefaultHostnameVerifier(), if you don't want to weaken //HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; HostnameVerifier hostnameVerifier = SSLConnectionSocketFactory.getDefaultHostnameVerifier(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create() .register("http", PlainConnectionSocketFactory.getSocketFactory()) .register("https", sslSocketFactory) .build(); // allows multi-threaded use PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry); b.setConnectionManager(connMgr); HttpClient client = b.build(); return client; }
/** * Connection to IBM Streams * * @param authorization * String representing Authorization header used for connections. * @param allowInsecure * Flag to allow insecure TLS/SSL connections. This is * <strong>not</strong> recommended in a production environment * @param resourcesUrl * String representing the root url to the REST API resources, * for example: https://server:port/streams/rest/resources */ AbstractStreamsConnection(String authorization, String resourcesUrl, boolean allowInsecure) throws IOException { this.authorization = authorization; this.resourcesUrl = resourcesUrl; // Create the executor with a custom verifier if insecure connections // were requested try { if (allowInsecure) { // Insecure host connections were requested, try to set up CloseableHttpClient httpClient = HttpClients.custom() .setHostnameVerifier(new AllowAllHostnameVerifier()) .setSslcontext(new SSLContextBuilder() .loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build()).build(); executor = Executor.newInstance(httpClient); traceLog.info("Insecure Host Connection enabled"); } else { // Default, secure host connections executor = Executor.newInstance(); } } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { // Insecure was requested but could not be set up executor = Executor.newInstance(); traceLog.info("Could not set up Insecure Host Connection"); } }
private CloseableHttpClient getHttpClient(ElasticSearchConfig esConfig) throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException { if(esConfig.getProtocol().equalsIgnoreCase("https")) { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build()); return HttpClients.custom().setSSLSocketFactory(sslsf).build(); } else if(esConfig.getProtocol().equalsIgnoreCase("http")) return HttpClients.createDefault(); return null; }
public HttpPoolingConnectionManager() throws KeyStoreException, KeyManagementException, NoSuchAlgorithmException { // Creating protocol schemes Registry<ConnectionSocketFactory> registry = RegistryBuilder .<ConnectionSocketFactory> create() .register("http", new PlainConnectionSocketFactory()) .register( "https", new SSLConnectionSocketFactory(new SSLContextBuilder().loadTrustMaterial(null, new TrustSelfSignedStrategy()).build())).build(); // Creating the connectionManager this.mConnectionManager = new PoolingHttpClientConnectionManager(registry); ((PoolingHttpClientConnectionManager) this.mConnectionManager).setMaxTotal(ConfigSingleton.INSTANCE .getMaxConnections()); ((PoolingHttpClientConnectionManager) this.mConnectionManager).setDefaultMaxPerRoute(ConfigSingleton.INSTANCE .getMaxConnectionsPerHost()); ((PoolingHttpClientConnectionManager) this.mConnectionManager).setDefaultConnectionConfig(ConnectionConfig .custom().setCharset(Consts.UTF_8).build()); ((PoolingHttpClientConnectionManager) this.mConnectionManager).setDefaultSocketConfig(SocketConfig.custom() .setSoTimeout(ConfigSingleton.INSTANCE.getSocketTimeout()).build()); // Run a Thread to Monitor the connections this.httpConnectionMonitoringThread = new Thread(this); this.httpConnectionMonitoringThread.setName("HttpConnectionMonitoringThread"); this.httpConnectionMonitoringThread.start(); // Initialize the lock for the multi-threaded access this.httpClientGenerationLock = new ReentrantLock(); }
@Override public void initialize(InputSplit rawSplit, TaskAttemptContext context) throws IOException, InterruptedException { Configuration jobConfig = context.getConfiguration(); esHost = jobConfig.get("elasticsearch.hostname"); esPort = jobConfig.get("elasticsearch.port"); batchSize = jobConfig.get("elasticsearch.batchsize"); esIndex = jobConfig.get("elasticsearch.index"); esUser = jobConfig.get("elasticsearch.username"); esDocType = jobConfig.get("elasticsearch.doctype"); esPassword = jobConfig.get("elasticsearch.password"); startTimestamp= jobConfig.get("elasticsearch.starttimestamp"); endTimeStamp = jobConfig.get("elasticsearch.endtimestamp"); esProtocol = jobConfig.get("elasticsearch.protocol"); SSLContextBuilder builder = new SSLContextBuilder(); SSLConnectionSocketFactory sslsf=null; try { builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslsf = new SSLConnectionSocketFactory(builder.build()); } catch(Exception e) { LOG.error(e.getMessage()); } if(esProtocol.equalsIgnoreCase("https")) httpClient = HttpClients.custom().setSSLSocketFactory(sslsf).build(); else if(esProtocol.equalsIgnoreCase("http")) httpClient = HttpClients.createDefault(); }
public RestClient() throws Exception { SSLContextBuilder builder = new SSLContextBuilder(); SSLConnectionSocketFactory sslConnectionFactory; builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); sslConnectionFactory = new SSLConnectionSocketFactory(builder.build()); this.httpClient = HttpClients.custom().setSSLSocketFactory(sslConnectionFactory) .setConnectionManager(HTTPConnectionManager.getInstance().getHttpConnectionManager()).build(); }
protected SSLConnectionSocketFactory createSSLConnectionSocketFactory() { try { SSLContextBuilder sslContextBuilder = new SSLContextBuilder() .loadTrustMaterial(null, new TrustSelfSignedStrategy()); return new SSLConnectionSocketFactory( sslContextBuilder.build(), createHostnameVerifier()); } catch (Exception e) { log.error(e.getMessage(), e); } return null; }
@Override protected void initFromConfiguration(LogAppenderDto appender, RestConfig configuration) { this.configuration = configuration; this.executor = Executors.newFixedThreadPool(configuration.getConnectionPoolSize()); target = new HttpHost(configuration.getHost(), configuration.getPort(), configuration.getSsl() ? "https" : "http"); HttpClientBuilder builder = HttpClients.custom(); if (configuration.getUsername() != null && configuration.getPassword() != null) { LOG.info("Adding basic auth credentials provider"); CredentialsProvider credsProvider = new BasicCredentialsProvider(); credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()), new UsernamePasswordCredentials(configuration.getUsername(), configuration.getPassword()) ); builder.setDefaultCredentialsProvider(credsProvider); } if (!configuration.getVerifySslCert()) { LOG.info("Adding trustful ssl context"); SSLContextBuilder sslBuilder = new SSLContextBuilder(); try { sslBuilder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslBuilder.build()); builder.setSSLSocketFactory(sslsf); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException ex) { LOG.error("Failed to init socket factory {}", ex.getMessage(), ex); } } PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(); cm.setDefaultMaxPerRoute(configuration.getConnectionPoolSize()); cm.setMaxTotal(configuration.getConnectionPoolSize()); builder.setConnectionManager(cm); this.client = builder.build(); }
/** * 创建SSL安全连接 * * @return */ private static SSLConnectionSocketFactory createSSLConnSocketFactory() { SSLConnectionSocketFactory sslsf = null; try { SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }).build(); sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public boolean verify(String arg0, SSLSession arg1) { return true; } @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } }); } catch (GeneralSecurityException e) { e.printStackTrace(); } return sslsf; }
private HttpClientBuilder configureSSL(HttpClientBuilder clientBuilder) { try { SSLContextBuilder builder = new SSLContextBuilder(); builder.loadTrustMaterial(null, new TrustSelfSignedStrategy()); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build(), allowAllHostname ? SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER : SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER); return clientBuilder.setSSLSocketFactory(sslsf); } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { throw new RuntimeException(e); } }