use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project openhab1-addons by openhab.
the class IhcConnectionPool method init.
private void init() {
// Create a local instance of cookie store
cookieStore = new BasicCookieStore();
// Create local HTTP context
localContext = HttpClientContext.create();
// Bind custom cookie store to the local context
localContext.setCookieStore(cookieStore);
httpClientBuilder = HttpClientBuilder.create();
// Setup a Trust Strategy that allows all certificates.
logger.debug("Initialize SSL context");
// Create a trust manager that does not validate certificate chains,
// but accept all.
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) {
logger.trace("Trusting server cert: " + certs[0].getIssuerDN());
}
} };
try {
// Controller supports only SSLv3 and TLSv1
sslContext = SSLContext.getInstance("TLSv1");
sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
} catch (NoSuchAlgorithmException e) {
logger.warn("Exception", e);
} catch (KeyManagementException e) {
logger.warn("Exception", e);
}
httpClientBuilder.setSslcontext(sslContext);
// Controller accepts only HTTPS connections and because normally IP
// address are used on home network rather than DNS names, create custom
// host name verifier.
HostnameVerifier hostnameVerifier = new HostnameVerifier() {
@Override
public boolean verify(String arg0, SSLSession arg1) {
logger.trace("HostnameVerifier: arg0 = " + arg0);
logger.trace("HostnameVerifier: arg1 = " + arg1);
return true;
}
};
// Create an SSL Socket Factory, to use our weakened "trust strategy"
SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1" }, null, hostnameVerifier);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", sslSocketFactory).build();
// Create connection-manager using our Registry. Allows multi-threaded
// use
PoolingHttpClientConnectionManager connMngr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
// Increase max connection counts
connMngr.setMaxTotal(20);
connMngr.setDefaultMaxPerRoute(6);
httpClientBuilder.setConnectionManager(connMngr);
}
use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project ats-framework by Axway.
the class HttpsClient method connect.
/**
* Connect to a remote host using basic authentication.
*
* @param hostname the host to connect to
* @param userName the user name
* @param password the password for the provided user name
* @throws FileTransferException
*/
@Override
public void connect(String hostname, String userName, String password) throws FileTransferException {
super.connect(hostname, userName, password);
// trust everybody
try {
SSLContext sslContext = SslUtils.getTrustAllSSLContext();
SSLConnectionSocketFactory ssf = new SSLConnectionSocketFactory(sslContext, encryptionProtocols, cipherSuites, new NoopHostnameVerifier());
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("https", ssf).build();
HttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
this.httpBuilder.setConnectionManager(connectionManager).setSchemePortResolver(new DefaultSchemePortResolver());
this.httpClient = this.httpBuilder.build();
} catch (Exception e) {
throw new FileTransferException("Error setting trust manager", e);
}
}
use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project ats-framework by Axway.
the class HttpClient method createNewHttpClientWithCredentials.
private void createNewHttpClientWithCredentials(String hostname, String userName, String password) throws FileTransferException {
log.debug("Creating new HTTP client to host " + hostname);
httpBuilder = HttpClientBuilder.create();
RequestConfig.Builder requestConfig = RequestConfig.custom();
requestConfig.setConnectTimeout(this.timeout);
httpBuilder.setDefaultRequestConfig(requestConfig.build());
SocketConfig.Builder socket = SocketConfig.custom();
socket.setRcvBufSize(this.socketBufferSize);
socket.setSndBufSize(this.socketBufferSize);
PoolingHttpClientConnectionManager conManager = new PoolingHttpClientConnectionManager();
// set stale connection check
conManager.setValidateAfterInactivity(-1);
httpBuilder.setConnectionManager(conManager);
Object socketTimeout = customProperties.get(HTTP_HTTPS_SOCKET_READ_TIMEOUT);
if (socketTimeout != null) {
// TODO this could be set either with the request config
socket.setSoTimeout(Integer.parseInt(socketTimeout.toString()));
}
httpBuilder.setDefaultSocketConfig(socket.build());
if (httpClient != null) {
// cleanup previous client
disconnect();
}
if (userName != null) {
BasicCredentialsProvider credentials = new BasicCredentialsProvider();
credentials.setCredentials(new AuthScope(hostname, this.port), new UsernamePasswordCredentials(userName, password));
httpBuilder.setDefaultCredentialsProvider(credentials);
}
httpClient = httpBuilder.build();
}
use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project camel by apache.
the class GooglePubsubConnectionFactory method getMultiThreadClient.
public Pubsub getMultiThreadClient(int parallelThreads) throws Exception {
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(parallelThreads);
cm.setMaxTotal(parallelThreads);
CloseableHttpClient httpClient = HttpClients.createMinimal(cm);
return buildClient(new ApacheHttpTransport(httpClient));
}
use of org.apache.http.impl.conn.PoolingHttpClientConnectionManager in project voltdb by VoltDB.
the class TestJSONInterface method httpUrlOverJSONExecute.
private static String httpUrlOverJSONExecute(String method, String url, String user, String password, String scheme, int expectedCode, String expectedCt, String varString) throws Exception {
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, (X509Certificate[] arg0, String arg1) -> true).build();
SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sf).build();
// allows multi-threaded use
PoolingHttpClientConnectionManager connMgr = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
HttpClientBuilder hb = HttpClientBuilder.create();
hb.setSslcontext(sslContext);
hb.setConnectionManager(connMgr);
try (CloseableHttpClient httpclient = hb.build()) {
HttpRequestBase request;
switch(method) {
case "POST":
HttpPost post = new HttpPost(url);
post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
request = post;
break;
case "PUT":
HttpPut put = new HttpPut(url);
put.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
request = put;
break;
case "DELETE":
HttpDelete delete = new HttpDelete(url);
request = delete;
break;
case "GET":
request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
break;
default:
request = new HttpGet(url + ((varString != null && varString.trim().length() > 0) ? ("?" + varString.trim()) : ""));
break;
}
// play nice by using HTTP 1.1 continue requests where the client sends the request headers first
// to the server to see if the server is willing to accept it. This allows us to test large requests
// without incurring server socket connection terminations
RequestConfig rc = RequestConfig.copy(RequestConfig.DEFAULT).setExpectContinueEnabled(true).build();
request.setProtocolVersion(HttpVersion.HTTP_1_1);
request.setConfig(rc);
if (user != null && password != null) {
if (scheme.equalsIgnoreCase("hashed")) {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
request.setHeader("Authorization", "Hashed " + h);
} else if (scheme.equalsIgnoreCase("hashed256")) {
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] hashedPasswordBytes = md.digest(password.getBytes("UTF-8"));
String h = user + ":" + Encoder.hexEncode(hashedPasswordBytes);
request.setHeader("Authorization", "Hashed " + h);
} else if (scheme.equalsIgnoreCase("basic")) {
request.setHeader("Authorization", "Basic " + new String(Base64.encodeToString(new String(user + ":" + password).getBytes(), false)));
}
}
ResponseHandler<String> rh = new ResponseHandler<String>() {
@Override
public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
String ct = response.getHeaders("Content-Type")[0].getValue();
if (expectedCt != null) {
assertTrue(ct.contains(expectedCt));
}
assertEquals(expectedCode, status);
if ((status >= 200 && status < 300) || HANDLED_CLIENT_ERRORS.contains(status)) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return null;
}
};
return httpclient.execute(request, rh);
}
}
Aggregations