List of usage examples for org.apache.http.conn.ssl SSLSocketFactory setHostnameVerifier
public void setHostnameVerifier(final X509HostnameVerifier hostnameVerifier)
From source file:com.archivas.clienttools.arcutils.impl.adapter.Hcp3AuthNamespaceAdapter.java
public void getAdditionalHcapProtocolSchemeRegistryForHttpClient(SchemeRegistry schemeRegistry, SSLCertificateCallback sslExceptionCallback) throws StorageAdapterException { try {/* w w w.j av a2 s . c om*/ SSLSocketFactory getCertsFactory; SSLContext sslcontext = SSLContext.getInstance("TLS"); TrustManager tm = new GetCertsX509TrustManager(getProfile(), sslExceptionCallback); sslcontext.init(null, new TrustManager[] { tm }, null); getCertsFactory = new SSLSocketFactory(sslcontext); getCertsFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); getCertsFactory = new SSLSocketFactory(sslcontext); Scheme getCerts = new Scheme("getcerts", getCertsFactory, 443); schemeRegistry.register(getCerts); } catch (Exception e) { LOG.log(Level.INFO, "Unable to initialize SSL for hcaphttps protocol!", e); throw new StorageAdapterException("Unable to initialize SSL for https protocol", e); } }
From source file:bixo.fetcher.SimpleHttpFetcher.java
private synchronized void init() { if (_httpClient == null) { // Create and initialize HTTP parameters HttpParams params = new BasicHttpParams(); // TODO KKr - w/4.1, switch to new api (ThreadSafeClientConnManager) // cm.setMaxTotalConnections(_maxThreads); // cm.setDefaultMaxPerRoute(Math.max(10, _maxThreads/10)); ConnManagerParams.setMaxTotalConnections(params, _maxThreads); // Set the maximum time we'll wait for a spare connection in the // connection pool. We // shouldn't actually hit this, as we make sure (in FetcherManager) that // the max number // of active requests doesn't exceed the value returned by getMaxThreads() // here.//from ww w. j a v a2 s . c o m ConnManagerParams.setTimeout(params, CONNECTION_POOL_TIMEOUT); // Set the socket and connection timeout to be something reasonable. HttpConnectionParams.setSoTimeout(params, _socketTimeout); HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout); // Even with stale checking enabled, a connection can "go stale" between // the check and the // next request. So we still need to handle the case of a closed socket // (from the server side), // and disabling this check improves performance. HttpConnectionParams.setStaleCheckingEnabled(params, false); // FUTURE - set this on a per-route (host) basis when we have per-host // policies for // doing partner crawls. We could define a BixoConnPerRoute class that // supports this. ConnPerRouteBean connPerRoute = new ConnPerRouteBean(_fetcherPolicy.getMaxConnectionsPerHost()); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); HttpProtocolParams.setVersion(params, _httpVersion); HttpProtocolParams.setUserAgent(params, _userAgent.getUserAgentString()); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setHttpElementCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); // TODO KKr - set on connection manager params, or client params? CookieSpecParamBean cookieParams = new CookieSpecParamBean(params); cookieParams.setSingleHeader(true); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sf = null; for (String contextName : SSL_CONTEXT_NAMES) { try { SSLContext sslContext = SSLContext.getInstance(contextName); sslContext.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null); sf = new SSLSocketFactory(sslContext); break; } catch (NoSuchAlgorithmException e) { LOGGER.debug("SSLContext algorithm not available: " + contextName); } catch (Exception e) { LOGGER.debug("SSLContext can't be initialized: " + contextName, e); } } if (sf != null) { sf.setHostnameVerifier(new DummyX509HostnameVerifier()); schemeRegistry.register(new Scheme("https", sf, 443)); } else { LOGGER.warn("No valid SSLContext found for https"); } // Use ThreadSafeClientConnManager since more than one thread will be // using the HttpClient. ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); _httpClient = new DefaultHttpClient(cm, params); _httpClient.setHttpRequestRetryHandler(new MyRequestRetryHandler(_maxRetryCount)); _httpClient.setRedirectHandler(new MyRedirectHandler(_fetcherPolicy.getRedirectMode())); _httpClient.addRequestInterceptor(new MyRequestInterceptor()); params = _httpClient.getParams(); // FUTURE KKr - support authentication HttpClientParams.setAuthenticating(params, false); HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH); ClientParamBean clientParams = new ClientParamBean(params); if (_fetcherPolicy.getMaxRedirects() == 0) { clientParams.setHandleRedirects(false); } else { clientParams.setHandleRedirects(true); clientParams.setMaxRedirects(_fetcherPolicy.getMaxRedirects()); } // Set up default headers. This helps us get back from servers what we // want. HashSet<Header> defaultHeaders = new HashSet<Header>(); defaultHeaders .add(new BasicHeader(HttpHeaderNames.ACCEPT_LANGUAGE, _fetcherPolicy.getAcceptLanguage())); defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET)); defaultHeaders.add(new BasicHeader(HttpHeaderNames.ACCEPT, DEFAULT_ACCEPT)); clientParams.setDefaultHeaders(defaultHeaders); } }
From source file:crawlercommons.fetcher.SimpleHttpFetcher.java
private synchronized void init() { if (_httpClient == null) { // Create and initialize HTTP parameters HttpParams params = new BasicHttpParams(); // TODO KKr - w/4.1, switch to new api (ThreadSafeClientConnManager) // cm.setMaxTotalConnections(_maxThreads); // cm.setDefaultMaxPerRoute(Math.max(10, _maxThreads/10)); ConnManagerParams.setMaxTotalConnections(params, _maxThreads); // Set the maximum time we'll wait for a spare connection in the connection pool. We // shouldn't actually hit this, as we make sure (in FetcherManager) that the max number // of active requests doesn't exceed the value returned by getMaxThreads() here. ConnManagerParams.setTimeout(params, CONNECTION_POOL_TIMEOUT); // Set the socket and connection timeout to be something reasonable. HttpConnectionParams.setSoTimeout(params, _socketTimeout); HttpConnectionParams.setConnectionTimeout(params, _connectionTimeout); // Even with stale checking enabled, a connection can "go stale" between the check and the // next request. So we still need to handle the case of a closed socket (from the server side), // and disabling this check improves performance. HttpConnectionParams.setStaleCheckingEnabled(params, false); // FUTURE - set this on a per-route (host) basis when we have per-host policies for // doing partner crawls. We could define a BixoConnPerRoute class that supports this. ConnPerRouteBean connPerRoute = new ConnPerRouteBean(getMaxConnectionsPerHost()); ConnManagerParams.setMaxConnectionsPerRoute(params, connPerRoute); HttpProtocolParams.setVersion(params, _httpVersion); HttpProtocolParams.setUserAgent(params, _userAgent.getUserAgentString()); HttpProtocolParams.setContentCharset(params, "UTF-8"); HttpProtocolParams.setHttpElementCharset(params, "UTF-8"); HttpProtocolParams.setUseExpectContinue(params, true); // TODO KKr - set on connection manager params, or client params? CookieSpecParamBean cookieParams = new CookieSpecParamBean(params); cookieParams.setSingleHeader(true); // Create and initialize scheme registry SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80)); SSLSocketFactory sf = null; for (String contextName : SSL_CONTEXT_NAMES) { try { SSLContext sslContext = SSLContext.getInstance(contextName); sslContext.init(null, new TrustManager[] { new DummyX509TrustManager(null) }, null); sf = new SSLSocketFactory(sslContext); break; } catch (NoSuchAlgorithmException e) { LOGGER.debug("SSLContext algorithm not available: " + contextName); } catch (Exception e) { LOGGER.debug("SSLContext can't be initialized: " + contextName, e); }//from w w w. j a va 2 s.c o m } if (sf != null) { sf.setHostnameVerifier(new DummyX509HostnameVerifier()); schemeRegistry.register(new Scheme("https", sf, 443)); } else { LOGGER.warn("No valid SSLContext found for https"); } // Use ThreadSafeClientConnManager since more than one thread will be using the HttpClient. ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, schemeRegistry); _httpClient = new DefaultHttpClient(cm, params); _httpClient.setHttpRequestRetryHandler(new MyRequestRetryHandler(_maxRetryCount)); _httpClient.setRedirectHandler(new MyRedirectHandler(getRedirectMode())); _httpClient.addRequestInterceptor(new MyRequestInterceptor()); params = _httpClient.getParams(); // FUTURE KKr - support authentication HttpClientParams.setAuthenticating(params, false); HttpClientParams.setCookiePolicy(params, CookiePolicy.BEST_MATCH); ClientParamBean clientParams = new ClientParamBean(params); if (getMaxRedirects() == 0) { clientParams.setHandleRedirects(false); } else { clientParams.setHandleRedirects(true); clientParams.setMaxRedirects(getMaxRedirects()); } // Set up default headers. This helps us get back from servers what we want. HashSet<Header> defaultHeaders = new HashSet<Header>(); defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_LANGUAGE, getAcceptLanguage())); defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_CHARSET, DEFAULT_ACCEPT_CHARSET)); defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, DEFAULT_ACCEPT_ENCODING)); defaultHeaders.add(new BasicHeader(HttpHeaders.ACCEPT, DEFAULT_ACCEPT)); clientParams.setDefaultHeaders(defaultHeaders); } }
From source file:org.spiffyui.server.AuthServlet.java
/** * If the authentication URL uses SSL then we need to use an SSLContext to connect to * it. The JDK provides on by default that will work fine for us, but it is possible * for some code running in some other place of the JVM to set a new default and that * new default might not be compatible with the type of connection we want to create. * //from w w w. j a v a 2 s .co m * The solution is to always set our own SSLContext. In that case we will use a context * that allows any connection since we let administrators control this connection using * the whitelist so we know that we will only connect to trusted servers. * * @param httpclient the HTTPClient making the connection * @param port the port of the connection */ private void setupClientSSL(HttpClient httpclient, int port) { try { SSLSocketFactory sslSocketFactory = null; SSLContext sslContext = SSLContext.getInstance("TLS"); TrustManager relaxedTrustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { /* We accept all certs so there is nothing to test here. */ } @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { /* We accept all certs so there is nothing to test here. */ } @Override public X509Certificate[] getAcceptedIssuers() { /* This indicates that we accept all certificates */ return null; } }; sslContext.init(null, new TrustManager[] { relaxedTrustManager }, new SecureRandom()); sslSocketFactory = new SSLSocketFactory(sslContext); sslSocketFactory.setHostnameVerifier(new HostVerifier()); /* No that we've configured our SSLContext we'll make sure our request uses it. */ ClientConnectionManager connMgr = httpclient.getConnectionManager(); SchemeRegistry schemeReg = connMgr.getSchemeRegistry(); schemeReg.unregister("https"); if (port != -1) { schemeReg.register(new Scheme("https", sslSocketFactory, port)); } else { /* If the port is -1 it means they were access the server without a port. 443 is the default port for SSL so we fill that in when making the connection. */ schemeReg.register(new Scheme("https", sslSocketFactory, 443)); } } catch (NoSuchAlgorithmException nsae) { LOGGER.throwing(AuthServlet.class.getName(), "setupClientSSL", nsae); } catch (KeyManagementException mke) { LOGGER.throwing(AuthServlet.class.getName(), "setupClientSSL", mke); } }
From source file:com.udps.hive.jdbc.HiveConnection.java
private DefaultHttpClient getHttpClient(Boolean useSsl) throws SQLException { DefaultHttpClient httpClient = new DefaultHttpClient(); // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; // If Kerberos if (isKerberosAuthMode()) { if (useSsl) { String msg = "SSL encryption is currently not supported with " + "kerberos authentication"; throw new SQLException(msg, " 08S01"); }//from w w w .j a v a2s . co m /** * Add an interceptor which sets the appropriate header in the * request. It does the kerberos authentication and get the final * service ticket, for sending to the server before every request. */ requestInterceptor = new HttpKerberosRequestInterceptor(sessConfMap.get(HIVE_AUTH_PRINCIPAL), host, getServerHttpUrl(false)); } else { /** * Add an interceptor to pass username/password in the header. In * https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor(getUserName(), getPassword()); // Configure httpClient for SSL if (useSsl) { String sslTrustStorePath = sessConfMap.get(HIVE_SSL_TRUST_STORE); String sslTrustStorePassword = sessConfMap.get(HIVE_SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLSocketFactory socketFactory; try { if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard // JSSE trust material socketFactory = SSLSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(HIVE_SSL_TRUST_STORE_TYPE); sslTrustStore.load(new FileInputStream(sslTrustStorePath), sslTrustStorePassword.toCharArray()); socketFactory = new SSLSocketFactory(sslTrustStore); } socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme sslScheme = new Scheme("https", 443, socketFactory); httpClient.getConnectionManager().getSchemeRegistry().register(sslScheme); } catch (Exception e) { String msg = "Could not create an https connection to " + jdbcURI + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } } httpClient.addRequestInterceptor(requestInterceptor); return httpClient; }
From source file:org.apache.ambari.view.hive.client.Connection.java
private CloseableHttpClient getHttpClient(Boolean useSsl) throws SQLException { boolean isCookieEnabled = authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH) == null || (!Utils.HiveAuthenticationParams.COOKIE_AUTH_FALSE .equalsIgnoreCase(authParams.get(Utils.HiveAuthenticationParams.COOKIE_AUTH))); String cookieName = authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME) == null ? Utils.HiveAuthenticationParams.DEFAULT_COOKIE_NAMES_HS2 : authParams.get(Utils.HiveAuthenticationParams.COOKIE_NAME); CookieStore cookieStore = isCookieEnabled ? new BasicCookieStore() : null; HttpClientBuilder httpClientBuilder; // Request interceptor for any request pre-processing logic HttpRequestInterceptor requestInterceptor; Map<String, String> additionalHttpHeaders = new HashMap<String, String>(); // Retrieve the additional HttpHeaders for (Map.Entry<String, String> entry : authParams.entrySet()) { String key = entry.getKey(); if (key.startsWith(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX)) { additionalHttpHeaders.put(key.substring(Utils.HiveAuthenticationParams.HTTP_HEADER_PREFIX.length()), entry.getValue());// w w w .j ava2s .c o m } } // Configure http client for kerberos/password based authentication if (isKerberosAuthMode()) { /** * Add an interceptor which sets the appropriate header in the request. * It does the kerberos authentication and get the final service ticket, * for sending to the server before every request. * In https mode, the entire information is encrypted */ Boolean assumeSubject = Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE_FROM_SUBJECT .equals(authParams.get(Utils.HiveAuthenticationParams.AUTH_KERBEROS_AUTH_TYPE)); requestInterceptor = new HttpKerberosRequestInterceptor( authParams.get(Utils.HiveAuthenticationParams.AUTH_PRINCIPAL), host, getServerHttpUrl(useSsl), assumeSubject, cookieStore, cookieName, useSsl, additionalHttpHeaders); } else { /** * Add an interceptor to pass username/password in the header. * In https mode, the entire information is encrypted */ requestInterceptor = new HttpBasicAuthInterceptor( getAuthParamDefault(Utils.HiveAuthenticationParams.AUTH_USER, getUsername()), getPassword(), cookieStore, cookieName, useSsl, additionalHttpHeaders); } // Configure http client for cookie based authentication if (isCookieEnabled) { // Create a http client with a retry mechanism when the server returns a status code of 401. httpClientBuilder = HttpClients.custom() .setServiceUnavailableRetryStrategy(new ServiceUnavailableRetryStrategy() { @Override public boolean retryRequest(final HttpResponse response, final int executionCount, final HttpContext context) { int statusCode = response.getStatusLine().getStatusCode(); boolean ret = statusCode == 401 && executionCount <= 1; // Set the context attribute to true which will be interpreted by the request interceptor if (ret) { context.setAttribute(Utils.HIVE_SERVER2_RETRY_KEY, Utils.HIVE_SERVER2_RETRY_TRUE); } return ret; } @Override public long getRetryInterval() { // Immediate retry return 0; } }); } else { httpClientBuilder = HttpClientBuilder.create(); } // Add the request interceptor to the client builder httpClientBuilder.addInterceptorFirst(requestInterceptor); // Configure http client for SSL if (useSsl) { String useTwoWaySSL = authParams.get(Utils.HiveAuthenticationParams.USE_TWO_WAY_SSL); String sslTrustStorePath = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE); String sslTrustStorePassword = authParams.get(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_PASSWORD); KeyStore sslTrustStore; SSLSocketFactory socketFactory; /** * The code within the try block throws: * 1. SSLInitializationException * 2. KeyStoreException * 3. IOException * 4. NoSuchAlgorithmException * 5. CertificateException * 6. KeyManagementException * 7. UnrecoverableKeyException * We don't want the client to retry on any of these, hence we catch all * and throw a SQLException. */ try { if (useTwoWaySSL != null && useTwoWaySSL.equalsIgnoreCase(Utils.HiveAuthenticationParams.TRUE)) { socketFactory = getTwoWaySSLSocketFactory(); } else if (sslTrustStorePath == null || sslTrustStorePath.isEmpty()) { // Create a default socket factory based on standard JSSE trust material socketFactory = SSLSocketFactory.getSocketFactory(); } else { // Pick trust store config from the given path sslTrustStore = KeyStore.getInstance(Utils.HiveAuthenticationParams.SSL_TRUST_STORE_TYPE); try (FileInputStream fis = new FileInputStream(sslTrustStorePath)) { sslTrustStore.load(fis, sslTrustStorePassword.toCharArray()); } socketFactory = new SSLSocketFactory(sslTrustStore); } socketFactory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create() .register("https", socketFactory).build(); httpClientBuilder.setConnectionManager(new BasicHttpClientConnectionManager(registry)); } catch (Exception e) { String msg = "Could not create an https connection to " + getServerHttpUrl(useSsl) + ". " + e.getMessage(); throw new SQLException(msg, " 08S01", e); } } return httpClientBuilder.build(); }
From source file:org.wso2.carbon.appmgt.impl.utils.AppManagerUtil.java
/** * Return a http client instance/*w w w . jav a2 s. co m*/ * * @param port - server port * @param protocol - service endpoint protocol http/https * @return */ public static HttpClient getHttpClient(int port, String protocol) { SchemeRegistry registry = new SchemeRegistry(); SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory(); String ignoreHostnameVerification = System.getProperty("org.wso2.ignoreHostnameVerification"); if (ignoreHostnameVerification != null && "true".equalsIgnoreCase(ignoreHostnameVerification)) { X509HostnameVerifier hostnameVerifier = SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER; socketFactory.setHostnameVerifier(hostnameVerifier); } if (AppMConstants.HTTPS_PROTOCOL.equalsIgnoreCase(protocol)) { if (port >= 0) { registry.register(new Scheme(AppMConstants.HTTPS_PROTOCOL, port, socketFactory)); } else { registry.register(new Scheme(AppMConstants.HTTPS_PROTOCOL, 443, socketFactory)); } } else if (AppMConstants.HTTP_PROTOCOL.equalsIgnoreCase(protocol)) { if (port >= 0) { registry.register( new Scheme(AppMConstants.HTTP_PROTOCOL, port, PlainSocketFactory.getSocketFactory())); } else { registry.register( new Scheme(AppMConstants.HTTP_PROTOCOL, 80, PlainSocketFactory.getSocketFactory())); } } HttpParams params = new BasicHttpParams(); ThreadSafeClientConnManager tcm = new ThreadSafeClientConnManager(registry); return new DefaultHttpClient(tcm, params); }