use of org.apache.http.conn.ssl.SSLSocketFactory in project ribbon by Netflix.
the class RestClient method apacheHttpClientSpecificInitialization.
protected Client apacheHttpClientSpecificInitialization() {
httpClient4 = NFHttpClientFactory.getNamedNFHttpClient(restClientName, this.ncc, true);
if (httpClient4 instanceof AbstractHttpClient) {
// DONT use our NFHttpClient's default Retry Handler since we have
// retry handling (same server/next server) in RestClient itself
((AbstractHttpClient) httpClient4).setHttpRequestRetryHandler(new NFHttpMethodRetryHandler(restClientName, 0, false, 0));
} else {
logger.warn("Unexpected error: Unable to disable NFHttpClient " + "retry handler, this most likely will not cause an " + "issue but probably should be looked at");
}
HttpParams httpClientParams = httpClient4.getParams();
// initialize Connection Manager cleanup facility
NFHttpClient nfHttpClient = (NFHttpClient) httpClient4;
// should we enable connection cleanup for idle connections?
try {
enableConnectionPoolCleanerTask = Boolean.parseBoolean(ncc.getProperty(CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, NFHttpClientConstants.DEFAULT_CONNECTIONIDLE_TIMETASK_ENABLED).toString());
nfHttpClient.getConnPoolCleaner().setEnableConnectionPoolCleanerTask(enableConnectionPoolCleanerTask);
} catch (Exception e1) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ConnectionPoolCleanerTaskEnabled, e1);
}
if (enableConnectionPoolCleanerTask) {
try {
connectionCleanerRepeatInterval = Integer.parseInt(String.valueOf(ncc.getProperty(CommonClientConfigKey.ConnectionCleanerRepeatInterval, NFHttpClientConstants.DEFAULT_CONNECTION_IDLE_TIMERTASK_REPEAT_IN_MSECS)));
nfHttpClient.getConnPoolCleaner().setConnectionCleanerRepeatInterval(connectionCleanerRepeatInterval);
} catch (Exception e1) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ConnectionCleanerRepeatInterval, e1);
}
try {
int iConnIdleEvictTimeMilliSeconds = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, NFHttpClientConstants.DEFAULT_CONNECTIONIDLE_TIME_IN_MSECS));
connIdleEvictTimeMilliSeconds = DynamicPropertyFactory.getInstance().getIntProperty(restClientName + ".nfhttpclient.connIdleEvictTimeMilliSeconds", iConnIdleEvictTimeMilliSeconds);
nfHttpClient.setConnIdleEvictTimeMilliSeconds(connIdleEvictTimeMilliSeconds);
} catch (Exception e1) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ConnIdleEvictTimeMilliSeconds, e1);
}
nfHttpClient.initConnectionCleanerTask();
}
try {
maxConnectionsperHost = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.MaxHttpConnectionsPerHost, maxConnectionsperHost));
ClientConnectionManager connMgr = httpClient4.getConnectionManager();
if (connMgr instanceof ThreadSafeClientConnManager) {
((ThreadSafeClientConnManager) connMgr).setDefaultMaxPerRoute(maxConnectionsperHost);
}
} catch (Exception e1) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.MaxHttpConnectionsPerHost, e1);
}
try {
maxTotalConnections = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.MaxTotalHttpConnections, maxTotalConnections));
ClientConnectionManager connMgr = httpClient4.getConnectionManager();
if (connMgr instanceof ThreadSafeClientConnManager) {
((ThreadSafeClientConnManager) connMgr).setMaxTotal(maxTotalConnections);
}
} catch (Exception e1) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.MaxTotalHttpConnections, e1);
}
try {
connectionTimeout = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ConnectTimeout, connectionTimeout));
HttpConnectionParams.setConnectionTimeout(httpClientParams, connectionTimeout);
} catch (Exception e1) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ConnectTimeout, e1);
}
try {
readTimeout = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ReadTimeout, readTimeout));
HttpConnectionParams.setSoTimeout(httpClientParams, readTimeout);
} catch (Exception e1) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ReadTimeout, e1);
}
// httpclient 4 seems to only have one buffer size controlling both
// send/receive - so let's take the bigger of the two values and use
// it as buffer size
int bufferSize = Integer.MIN_VALUE;
if (ncc.getProperty(CommonClientConfigKey.ReceiveBufferSize) != null) {
try {
bufferSize = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ReceiveBufferSize));
} catch (Exception e) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ReceiveBufferSize, e);
}
if (ncc.getProperty(CommonClientConfigKey.SendBufferSize) != null) {
try {
int sendBufferSize = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.SendBufferSize));
if (sendBufferSize > bufferSize) {
bufferSize = sendBufferSize;
}
} catch (Exception e) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.SendBufferSize, e);
}
}
}
if (bufferSize != Integer.MIN_VALUE) {
HttpConnectionParams.setSocketBufferSize(httpClientParams, bufferSize);
}
if (ncc.getProperty(CommonClientConfigKey.StaleCheckingEnabled) != null) {
try {
HttpConnectionParams.setStaleCheckingEnabled(httpClientParams, Boolean.parseBoolean(ncc.getProperty(CommonClientConfigKey.StaleCheckingEnabled, false).toString()));
} catch (Exception e) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.StaleCheckingEnabled, e);
}
}
if (ncc.getProperty(CommonClientConfigKey.Linger) != null) {
try {
HttpConnectionParams.setLinger(httpClientParams, Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.Linger)));
} catch (Exception e) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.Linger, e);
}
}
if (ncc.getProperty(CommonClientConfigKey.ProxyHost) != null) {
try {
proxyHost = (String) ncc.getProperty(CommonClientConfigKey.ProxyHost);
proxyPort = Integer.parseInt("" + ncc.getProperty(CommonClientConfigKey.ProxyPort));
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpClient4.getParams().setParameter(ConnRouteParams.DEFAULT_PROXY, proxy);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid value for property:" + CommonClientConfigKey.ProxyHost, e);
}
}
if (isSecure) {
final URL trustStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.TrustStore);
final URL keyStoreUrl = getResourceForOptionalProperty(CommonClientConfigKey.KeyStore);
final ClientConnectionManager currentManager = httpClient4.getConnectionManager();
AbstractSslContextFactory abstractFactory = null;
if (// if client is not is not required, we only need a keystore OR a truststore to warrant configuring
(isClientAuthRequired && (trustStoreUrl != null && keyStoreUrl != null)) || (!isClientAuthRequired && (trustStoreUrl != null || keyStoreUrl != null))) {
try {
abstractFactory = new URLSslContextFactory(trustStoreUrl, (String) ncc.getProperty(CommonClientConfigKey.TrustStorePassword), keyStoreUrl, (String) ncc.getProperty(CommonClientConfigKey.KeyStorePassword));
} catch (ClientSslSocketFactoryException e) {
throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
}
}
KeyStoreAwareSocketFactory awareSocketFactory;
try {
awareSocketFactory = isHostnameValidationRequired ? new KeyStoreAwareSocketFactory(abstractFactory) : new KeyStoreAwareSocketFactory(abstractFactory, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
currentManager.getSchemeRegistry().register(new Scheme("https", 443, awareSocketFactory));
} catch (Exception e) {
throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
}
}
// See http://hc.apache.org/httpcomponents-client-ga/tutorial/html/advanced.html
if (ignoreUserToken) {
((DefaultHttpClient) httpClient4).setUserTokenHandler(new UserTokenHandler() {
@Override
public Object getUserToken(HttpContext context) {
return null;
}
});
}
// custom SSL Factory handler
String customSSLFactoryClassName = (String) ncc.getProperty(CommonClientConfigKey.CustomSSLSocketFactoryClassName);
if (customSSLFactoryClassName != null) {
try {
SSLSocketFactory customSocketFactory = (SSLSocketFactory) ClientFactory.instantiateInstanceWithClientConfig(customSSLFactoryClassName, ncc);
httpClient4.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, customSocketFactory));
} catch (Exception e) {
throw new IllegalArgumentException("Invalid value associated with property:" + CommonClientConfigKey.CustomSSLSocketFactoryClassName, e);
}
}
ApacheHttpClient4Handler handler = new ApacheHttpClient4Handler(httpClient4, new BasicCookieStore(), false);
return new ApacheHttpClient4(handler, config);
}
use of org.apache.http.conn.ssl.SSLSocketFactory in project OpenAttestation by OpenAttestation.
the class SslUtil method getServerCertificates.
public static X509Certificate[] getServerCertificates(URL url) throws NoSuchAlgorithmException, KeyManagementException, IOException {
if (!"https".equals(url.getProtocol())) {
throw new IllegalArgumentException("URL scheme must be https");
}
int port = url.getPort();
if (port == -1) {
port = 443;
}
X509HostnameVerifier hostnameVerifier = new NopX509HostnameVerifierApache();
CertificateStoringX509TrustManager trustManager = new CertificateStoringX509TrustManager();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new X509TrustManager[] { trustManager }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext, hostnameVerifier);
Scheme https = new Scheme("https", port, sf);
SchemeRegistry sr = new SchemeRegistry();
sr.register(https);
BasicClientConnectionManager connectionManager = new BasicClientConnectionManager(sr);
HttpParams httpParams = new BasicHttpParams();
httpParams.setParameter(ClientPNames.HANDLE_REDIRECTS, false);
HttpClient httpClient = new DefaultHttpClient(connectionManager, httpParams);
log.debug("Saving certificates from server URL: {}", url.toExternalForm());
HttpHead request = new HttpHead(url.toExternalForm());
HttpResponse response = httpClient.execute(request);
log.debug("Server status line: {} {} ({})", new String[] { response.getProtocolVersion().getProtocol(), response.getStatusLine().getReasonPhrase(), String.valueOf(response.getStatusLine().getStatusCode()) });
httpClient.getConnectionManager().shutdown();
return trustManager.getStoredCertificates();
}
use of org.apache.http.conn.ssl.SSLSocketFactory in project OpenAttestation by OpenAttestation.
the class ApacheHttpClient method initSchemeRegistryWithPolicy.
/*
public final void setBaseURL(URL baseURL) {
this.baseURL = baseURL;
}
public final void setKeystore(SimpleKeystore keystore) {
this.keystore = keystore;
}
public final void setRequireTrustedCertificate(boolean value) {
requireTrustedCertificate = value;
}
public final void setVerifyHostname(boolean value) {
verifyHostname = value;
}
*
*/
/**
* Used in Mt Wilson 1.0-RC2
*
* Base URL and other configuration must already be set before calling this
* method.
*
* @param protocol either "http" or "https"
* @param port such as 80 for http, 443 for https
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
*/
/*
private SchemeRegistry initSchemeRegistry(String protocol, int port) throws KeyManagementException, NoSuchAlgorithmException {
SchemeRegistry sr = new SchemeRegistry();
if( "http".equals(protocol) ) {
Scheme http = new Scheme("http", port, PlainSocketFactory.getSocketFactory());
sr.register(http);
}
if( "https".equals(protocol) ) {
X509HostnameVerifier hostnameVerifier; // secure by default (default verifyHostname = true)
X509TrustManager trustManager; // secure by default, using Java's implementation which verifies the peer and using java's trusted keystore as default if user does not provide a specific keystore
if( verifyHostname ) {
hostnameVerifier = SSLSocketFactory.STRICT_HOSTNAME_VERIFIER;
}
else { // if( !config.getBoolean("mtwilson.api.ssl.verifyHostname", true) ) {
hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER;
}
if( requireTrustedCertificate && keystore != null ) {
trustManager = SslUtil.createX509TrustManagerWithKeystore(keystore);
}
else if( requireTrustedCertificate ) { // config.getBoolean("mtwilson.api.ssl.requireTrustedCertificate", true) ) {
//String truststore = config.getString("mtwilson.api.keystore", System.getProperty("javax.net.ssl.trustStorePath")); // if null use default java trust store...
//String truststorePassword = config.getString("mtwilson.api.keystore.password", System.getProperty("javax.net.ssl.trustStorePassword"));
// String truststore = System.getProperty("javax.net.ssl.trustStorePath");
String truststore = System.getProperty("javax.net.ssl.trustStore");
String truststorePassword = System.getProperty("javax.net.ssl.trustStorePassword");
// create a trust manager using only our trusted ssl certificates
if( truststore == null || truststorePassword == null ) {
throw new IllegalArgumentException("Require trusted certificates is enabled but truststore is not configured");
}
keystore = new SimpleKeystore(new File(truststore), truststorePassword);
trustManager = SslUtil.createX509TrustManagerWithKeystore(keystore);
}
else {
// user does not want to ensure certificates are trusted, so use a no-op trust manager
trustManager = new NopX509TrustManager();
}
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, new X509TrustManager[] { trustManager }, null); // key manager, trust manager, securerandom
SSLSocketFactory sf = new SSLSocketFactory(
sslcontext,
hostnameVerifier
);
Scheme https = new Scheme("https", port, sf); // URl defaults to 443 for https but if user specified a different port we use that instead
sr.register(https);
}
return sr;
}
*/
/**
* Used in Mt Wilson 1.1
*
* @param protocol
* @param port
* @param policy
* @return
* @throws KeyManagementException
* @throws NoSuchAlgorithmException
*/
private SchemeRegistry initSchemeRegistryWithPolicy(String protocol, int port, ApacheTlsPolicy policy) throws KeyManagementException, NoSuchAlgorithmException {
SchemeRegistry sr = new SchemeRegistry();
if ("http".equals(protocol)) {
Scheme http = new Scheme("http", port, PlainSocketFactory.getSocketFactory());
sr.register(http);
}
if ("https".equals(protocol)) {
SSLContext sslcontext = SSLContext.getInstance("TLS");
// key manager, trust manager, securerandom
sslcontext.init(null, new X509TrustManager[] { policy.getTrustManager() }, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext, policy.getApacheHostnameVerifier());
// URl defaults to 443 for https but if user specified a different port we use that instead
Scheme https = new Scheme("https", port, sf);
sr.register(https);
}
return sr;
}
use of org.apache.http.conn.ssl.SSLSocketFactory in project OpenMEAP by OpenMEAP.
the class SSLUtils method getRelaxedSSLVerificationHttpClient.
public static HttpClient getRelaxedSSLVerificationHttpClient() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new MySSLSocketFactory(trustStore);
sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, FormConstants.CHAR_ENC_DEFAULT);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
registry.register(new Scheme("https", sf, 443));
ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);
return new DefaultHttpClient(ccm, params);
} catch (Exception e) {
return new DefaultHttpClient();
}
}
use of org.apache.http.conn.ssl.SSLSocketFactory in project quickstarts by jboss-switchyard.
the class WorkServiceMain method main.
public static void main(String... args) throws Exception {
Set<String> policies = new HashSet<String>();
for (String arg : args) {
arg = Strings.trimToNull(arg);
if (arg != null) {
if (arg.equals(CONFIDENTIALITY) || arg.equals(CLIENT_AUTHENTICATION) || arg.equals(HELP)) {
policies.add(arg);
} else {
LOGGER.error(MAVEN_USAGE);
throw new Exception(MAVEN_USAGE);
}
}
}
if (policies.contains(HELP)) {
LOGGER.info(MAVEN_USAGE);
} else {
final String scheme;
final int port;
if (policies.contains(CONFIDENTIALITY)) {
scheme = "https";
port = getPort(8443);
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, null, null);
SSLSocketFactory sf = new SSLSocketFactory(sslcontext, SSLSocketFactory.STRICT_HOSTNAME_VERIFIER);
Scheme https = new Scheme(scheme, port, sf);
SchemeRegistry sr = new SchemeRegistry();
sr.register(https);
} else {
scheme = "http";
port = getPort(8080);
}
String[] userPass = policies.contains(CLIENT_AUTHENTICATION) ? new String[] { "kermit", "the-frog-1" } : null;
invokeWorkService(scheme, port, getContext(), userPass);
}
}
Aggregations