use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project credhub by cloudfoundry-incubator.
the class RestTemplateFactory method createRestTemplate.
public RestTemplate createRestTemplate(String trustStorePath, String trustStorePassword) throws CertificateException, NoSuchAlgorithmException, KeyStoreException, IOException, KeyManagementException {
File trustStore = new File(trustStorePath);
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(trustStore, trustStorePassword.toCharArray()).build();
SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext);
HttpClient httpClient = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
return new RestTemplate(requestFactory);
}
use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project LogHub by fbacchella.
the class AbstractHttpSender method configure.
@Override
public boolean configure(Properties properties) {
endPoints = Helpers.stringsToUrl(destinations, port, protocol, logger);
if (endPoints.length == 0) {
return false;
}
// Create the senders threads and the common queue
batch = new Batch();
threads = new Thread[publisherThreads];
for (int i = 1; i <= publisherThreads; i++) {
String tname = getPublishName() + "Publisher" + i;
threads[i - 1] = new Thread(publisher) {
{
setDaemon(false);
setName(tname);
start();
}
};
}
// The HTTP connection management
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setUserAgent(VersionInfo.getUserAgent("LogHub-HttpClient", "org.apache.http.client", HttpClientBuilder.class));
// Set the Configuration manager
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(properties.ssl)).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setDefaultMaxPerRoute(2);
cm.setMaxTotal(2 * publisherThreads);
cm.setValidateAfterInactivity(timeout * 1000);
builder.setConnectionManager(cm);
if (properties.ssl != null) {
builder.setSSLContext(properties.ssl);
}
builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build());
builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).setSoTimeout(timeout * 1000).build());
builder.setDefaultConnectionConfig(ConnectionConfig.custom().build());
builder.disableCookieManagement();
builder.setRetryHandler(new HttpRequestRetryHandler() {
@Override
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
return false;
}
});
client = builder.build();
if (user != null && password != null) {
credsProvider = new BasicCredentialsProvider();
for (URL i : endPoints) {
credsProvider.setCredentials(new AuthScope(i.getHost(), i.getPort()), new UsernamePasswordCredentials(user, password));
}
}
// Schedule a task to flush every 5 seconds
Runnable flush = () -> {
synchronized (publisher) {
long now = new Date().getTime();
if ((now - lastFlush) > 5000) {
batches.add(batch);
batch = new Batch();
publisher.notify();
}
}
};
properties.registerScheduledTask(getPublishName() + "Flusher", flush, 5000);
return true;
}
use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project LogHub by fbacchella.
the class TestHttpSsl method TestHcComplex.
@Test
public void TestHcComplex() throws NoSuchAlgorithmException, KeyStoreException, CertificateException, IOException, KeyManagementException {
CloseableHttpClient client = null;
;
try {
int publisherThreads = 1;
int timeout = 2;
// The HTTP connection management
HttpClientBuilder builder = HttpClientBuilder.create();
builder.setUserAgent(VersionInfo.getUserAgent("LogHub-HttpClient", "org.apache.http.client", HttpClientBuilder.class));
Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", new SSLConnectionSocketFactory(getContext.get(), localhostVerifier)).build();
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
cm.setDefaultMaxPerRoute(2);
cm.setMaxTotal(2 * publisherThreads);
cm.setValidateAfterInactivity(timeout * 1000);
builder.setConnectionManager(cm);
builder.setDefaultRequestConfig(RequestConfig.custom().setConnectionRequestTimeout(timeout * 1000).setConnectTimeout(timeout * 1000).setSocketTimeout(timeout * 1000).build());
builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).setSoTimeout(timeout * 1000).build());
builder.setDefaultConnectionConfig(ConnectionConfig.custom().setCharset(Charset.forName("UTF-8")).build());
builder.disableCookieManagement();
client = builder.build();
HttpClientContext context = HttpClientContext.create();
HttpHost host;
RequestLine requestLine = new BasicRequestLine("GET", theurl.getPath(), HttpVersion.HTTP_1_1);
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest(requestLine);
host = new HttpHost(theurl.getHost(), theurl.getPort(), "https");
CloseableHttpResponse response = client.execute(host, request, context);
Assert.assertEquals(200, response.getStatusLine().getStatusCode());
try {
HttpEntity entity = response.getEntity();
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
if (client != null) {
client.close();
}
}
}
use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project fabric8 by fabric8io.
the class JolokiaClients method createJolokiaClient.
protected J4pClient createJolokiaClient(Container container, String jolokiaUrl) {
String name = container.getName();
LOG.debug("Creating jolokia client for : " + name + " at URL: " + jolokiaUrl);
J4pClientBuilder builder = J4pClient.url(jolokiaUrl);
if (useKubeProxy) {
// When using the https proxy, inject the Kubernetes client's SSL context
URL masterUrl = getKubernetes().getMasterUrl();
if (masterUrl != null && masterUrl.toString().startsWith("https")) {
try {
SSLContext sslCtx = SSLUtils.sslContext(kubernetes.getConfiguration());
ConnectionSocketFactory factory = new SSLConnectionSocketFactory(sslCtx);
builder = builder.sslConnectionSocketFactory(factory);
} catch (Exception e) {
LOG.warn("Unable to inject the Kubernetes SSL context into the Jolokia client. Using the default context", e);
}
}
}
AuthenticationMode mode = locateAuthenticationMode();
switch(mode) {
case BEARER:
builder = builder.authenticator(new BearerTokenAuthenticator());
String token = kubernetes.getConfiguration().getOauthToken();
builder = builder.user(token);
break;
case BASIC:
builder = builder.authenticator(new BasicAuthenticator());
if (Strings.isNotBlank(user)) {
builder = builder.user(user);
}
if (Strings.isNotBlank(password)) {
builder = builder.password(password);
}
break;
default:
throw new IllegalStateException("Unsupported authentication mode: " + mode);
}
return builder.build();
}
use of org.apache.http.conn.ssl.SSLConnectionSocketFactory in project ovirt-engine by oVirt.
the class HttpClientBuilder method build.
public CloseableHttpClient build() throws IOException, GeneralSecurityException {
// Prepare the default configuration for all requests:
RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(connectTimeout != null ? connectTimeout : 0).setSocketTimeout(readTimeout != null ? readTimeout : 0).build();
// Configure the trust manager:
TrustManager[] trustManager = null;
if (verifyChain) {
if (trustStore != null) {
try (InputStream is = new FileInputStream(trustStore)) {
KeyStore ks = KeyStore.getInstance(trustStoreType);
ks.load(is, StringUtils.isEmpty(trustStorePassword) ? null : trustStorePassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory.getInstance(trustManagerAlgorithm);
tmf.init(ks);
trustManager = tmf.getTrustManagers();
}
}
} else {
trustManager = new TrustManager[] { new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[] {};
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(X509Certificate[] certs, String authType) {
}
} };
}
// Create the SSL context:
SSLContext sslContext = SSLContext.getInstance(tlsProtocol);
sslContext.init(null, trustManager, null);
// Create the SSL host name verifier:
HostnameVerifier sslHostnameVerifier = null;
if (!verifyHost) {
sslHostnameVerifier = (hostname, session) -> true;
}
// Create the socket factory for HTTP:
ConnectionSocketFactory httpSocketFactory = new PlainConnectionSocketFactory();
// Create the socket factory for HTTPS:
ConnectionSocketFactory httpsSocketFactory = new SSLConnectionSocketFactory(sslContext, sslHostnameVerifier);
// Create the socket factory registry:
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", httpSocketFactory).register("https", httpsSocketFactory).build();
// Create the connection manager:
HttpClientConnectionManager connectionManager;
if (poolSize != null) {
PoolingHttpClientConnectionManager poolManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
poolManager.setDefaultMaxPerRoute(poolSize);
poolManager.setMaxTotal(poolSize);
poolManager.setValidateAfterInactivity(validateAfterInactivity == null ? 100 : validateAfterInactivity);
connectionManager = poolManager;
} else {
connectionManager = new BasicHttpClientConnectionManager(socketFactoryRegistry);
}
// Create the client:
return org.apache.http.impl.client.HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).setSSLHostnameVerifier(sslHostnameVerifier).setConnectionManager(connectionManager).setRetryHandler(new StandardHttpRequestRetryHandler(retryCount == null ? 1 : retryCount, true)).build();
}
Aggregations