use of org.apache.http.conn.ssl.TrustStrategy in project voltdb by VoltDB.
the class TestJSONOverHttps method callProcOverJSON.
private String callProcOverJSON(String varString, final int expectedCode) throws Exception {
URI uri = URI.create("https://localhost:" + m_port + "/api/1.0/");
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return 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 b = HttpClientBuilder.create();
b.setSslcontext(sslContext);
b.setConnectionManager(connMgr);
try (CloseableHttpClient httpclient = b.build()) {
HttpPost post = new HttpPost(uri);
// 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();
post.setProtocolVersion(HttpVersion.HTTP_1_1);
post.setConfig(rc);
post.setEntity(new StringEntity(varString, utf8ApplicationFormUrlEncoded));
ResponseHandler<String> rh = new ResponseHandler<String>() {
@Override
public String handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
int status = response.getStatusLine().getStatusCode();
assertEquals(expectedCode, status);
if ((status >= 200 && status < 300) || status == 400) {
HttpEntity entity = response.getEntity();
return entity != null ? EntityUtils.toString(entity) : null;
}
return null;
}
};
return httpclient.execute(post, rh);
}
}
use of org.apache.http.conn.ssl.TrustStrategy in project cloudstack by apache.
the class HypervDirectConnectResource method postHttpRequest.
public static String postHttpRequest(final String jsonCmd, final URI agentUri) {
// Using Apache's HttpClient for HTTP POST
// Java-only approach discussed at on StackOverflow concludes with
// comment to use Apache HttpClient
// http://stackoverflow.com/a/2793153/939250, but final comment is to
// use Apache.
String logMessage = StringEscapeUtils.unescapeJava(jsonCmd);
logMessage = cleanPassword(logMessage);
s_logger.debug("POST request to " + agentUri.toString() + " with contents " + logMessage);
// Create request
HttpClient httpClient = null;
final TrustStrategy easyStrategy = new TrustStrategy() {
@Override
public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException {
return true;
}
};
try {
final SSLSocketFactory sf = new SSLSocketFactory(easyStrategy, new AllowAllHostnameVerifier());
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", DEFAULT_AGENT_PORT, sf));
final ClientConnectionManager ccm = new BasicClientConnectionManager(registry);
httpClient = new DefaultHttpClient(ccm);
} catch (final KeyManagementException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
} catch (final UnrecoverableKeyException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
} catch (final NoSuchAlgorithmException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
} catch (final KeyStoreException e) {
s_logger.error("failed to initialize http client " + e.getMessage());
}
String result = null;
// TODO: are there timeout settings and worker thread settings to tweak?
try {
final HttpPost request = new HttpPost(agentUri);
// JSON encode command
// Assumes command sits comfortably in a string, i.e. not used for
// large data transfers
final StringEntity cmdJson = new StringEntity(jsonCmd);
request.addHeader("content-type", "application/json");
request.setEntity(cmdJson);
s_logger.debug("Sending cmd to " + agentUri.toString() + " cmd data:" + logMessage);
final HttpResponse response = httpClient.execute(request);
// Unsupported commands will not route.
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
final String errMsg = "Failed to send : HTTP error code : " + response.getStatusLine().getStatusCode();
s_logger.error(errMsg);
final String unsupportMsg = "Unsupported command " + agentUri.getPath() + ". Are you sure you got the right type of" + " server?";
final Answer ans = new UnsupportedAnswer(null, unsupportMsg);
s_logger.error(ans);
result = s_gson.toJson(new Answer[] { ans });
} else if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
final String errMsg = "Failed send to " + agentUri.toString() + " : HTTP error code : " + response.getStatusLine().getStatusCode();
s_logger.error(errMsg);
return null;
} else {
result = EntityUtils.toString(response.getEntity());
final String logResult = cleanPassword(StringEscapeUtils.unescapeJava(result));
s_logger.debug("POST response is " + logResult);
}
} catch (final ClientProtocolException protocolEx) {
// Problem with HTTP message exchange
s_logger.error(protocolEx);
} catch (final IOException connEx) {
// Problem with underlying communications
s_logger.error(connEx);
} finally {
httpClient.getConnectionManager().shutdown();
}
return result;
}
use of org.apache.http.conn.ssl.TrustStrategy in project oxAuth by GluuFederation.
the class HttpService method getHttpsClientTrustAll.
public HttpClient getHttpsClientTrustAll() {
try {
SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}, new AllowAllHostnameVerifier());
PlainSocketFactory psf = PlainSocketFactory.getSocketFactory();
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", 80, psf));
registry.register(new Scheme("https", 443, sf));
ClientConnectionManager ccm = new PoolingClientConnectionManager(registry);
return new DefaultHttpClient(ccm);
} catch (Exception ex) {
log.error("Failed to create TrustAll https client", ex);
return new DefaultHttpClient();
}
}
use of org.apache.http.conn.ssl.TrustStrategy in project gocd by gocd.
the class GoAgentServerHttpClientBuilder method build.
public CloseableHttpClient build() throws Exception {
HttpClientBuilder builder = HttpClients.custom();
builder.setDefaultSocketConfig(SocketConfig.custom().setTcpNoDelay(true).setSoKeepAlive(true).build()).setKeepAliveStrategy(DefaultConnectionKeepAliveStrategy.INSTANCE);
HostnameVerifier hostnameVerifier = sslVerificationMode.verifier();
TrustStrategy trustStrategy = sslVerificationMode.trustStrategy();
KeyStore trustStore = agentTruststore();
SSLContextBuilder sslContextBuilder = SSLContextBuilder.create().useProtocol(systemEnvironment.get(SystemEnvironment.GO_SSL_TRANSPORT_PROTOCOL_TO_BE_USED_BY_AGENT));
if (trustStore != null || trustStrategy != null) {
sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy);
}
sslContextBuilder.loadKeyMaterial(agentKeystore(), keystorePassword().toCharArray());
SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContextBuilder.build(), hostnameVerifier);
builder.setSSLSocketFactory(sslConnectionSocketFactory);
return builder.build();
}
use of org.apache.http.conn.ssl.TrustStrategy in project openhab1-addons by openhab.
the class Util method getConnection.
public static Sardine getConnection(CalDavConfig config) {
if (config.isDisableCertificateVerification()) {
if (config.getUrl().startsWith(HTTP_URL_PREFIX)) {
log.error("do not use '{}' if no ssl is used", CalDavLoaderImpl.PROP_DISABLE_CERTIFICATE_VERIFICATION);
}
log.trace("connecting to caldav '{}' with disabled certificate verification (url={}, username={}, password={})", config.getKey(), config.getUrl(), config.getUsername(), config.getPassword());
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create().setHostnameVerifier(new AllowAllHostnameVerifier());
try {
httpClientBuilder.setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
@Override
public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {
return true;
}
}).build());
} catch (KeyManagementException e) {
log.error("error verifying certificate", e);
} catch (NoSuchAlgorithmException e) {
log.error("error verifying certificate", e);
} catch (KeyStoreException e) {
log.error("error verifying certificate", e);
}
if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
log.trace("connecting without credentials for '{}'", config.getKey());
return new SardineImpl(httpClientBuilder);
} else {
return new SardineImpl(httpClientBuilder, config.getUsername(), config.getPassword());
}
} else {
log.trace("connecting to caldav '{}' (url={}, username={}, password={})", config.getKey(), config.getUrl(), config.getUsername(), config.getPassword());
if (StringUtils.isEmpty(config.getUsername()) && StringUtils.isEmpty(config.getPassword())) {
log.trace("connecting without credentials for '{}'", config.getKey());
return new SardineImpl();
} else {
return new SardineImpl(config.getUsername(), config.getPassword());
}
}
}
Aggregations