List of usage examples for org.apache.http.conn.ssl TrustStrategy TrustStrategy
TrustStrategy
From source file:com.couchbase.jdbc.core.ProtocolImpl.java
public ProtocolImpl(String url, Properties props) { if (props.containsKey(ConnectionParameters.USER)) { user = props.getProperty(ConnectionParameters.USER); }//w ww. j av a 2 s . c om if (props.containsKey(ConnectionParameters.PASSWORD)) { password = props.getProperty(ConnectionParameters.PASSWORD); } if (props.containsKey("credentials")) { credentials = props.getProperty("credentials"); } this.url = url; setConnectionTimeout(props.getProperty(ConnectionParameters.CONNECTION_TIMEOUT)); if (props.containsKey(ConnectionParameters.SCAN_CONSISTENCY)) { scanConsistency = props.getProperty(ConnectionParameters.SCAN_CONSISTENCY); } requestConfig = RequestConfig.custom().setConnectionRequestTimeout(0).setConnectTimeout(connectTimeout) .setSocketTimeout(connectTimeout).build(); if (props.containsKey(ConnectionParameters.ENABLE_SSL) && props.getProperty(ConnectionParameters.ENABLE_SSL).equals("true")) { SSLContextBuilder builder = SSLContexts.custom(); try { builder.loadTrustMaterial(null, new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }); SSLContext sslContext = builder.build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new X509HostnameVerifier() { @Override public void verify(String host, SSLSocket ssl) throws IOException { } @Override public void verify(String host, X509Certificate cert) throws SSLException { } @Override public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException { } @Override public boolean verify(String s, SSLSession sslSession) { return true; } }); Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder .<ConnectionSocketFactory>create().register("https", sslsf).build(); HttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(socketFactoryRegistry); httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(requestConfig) .build(); ssl = true; } catch (Exception ex) { logger.error("Error creating ssl client", ex); } } else { httpClient = HttpClientBuilder.create().setDefaultRequestConfig(requestConfig).build(); } }
From source file:org.sonatype.nexus.client.rest.jersey.NexusClientFactoryImpl.java
protected ApacheHttpClient4 doCreateHttpClientFor(final ConnectionInfo connectionInfo, final XStream xstream) { final ApacheHttpClient4Config config = new DefaultApacheHttpClient4Config(); config.getSingletons().add(new XStreamXmlProvider(xstream, APPLICATION_XML_UTF8_TYPE)); // set _real_ URL for baseUrl, and not a redirection (typically http instead of https) config.getProperties().put(PROPERTY_FOLLOW_REDIRECTS, Boolean.FALSE); applyAuthenticationIfAny(connectionInfo, config); applyProxyIfAny(connectionInfo, config); // obey JSSE defined system properties config.getProperties().put(ApacheHttpClient4Config.PROPERTY_CONNECTION_MANAGER, new PoolingClientConnectionManager(SchemeRegistryFactory.createSystemDefault())); final ApacheHttpClient4 client = ApacheHttpClient4.create(config); // set UA/* w w w . j a v a2s. c o m*/ client.getClientHandler().getHttpClient().getParams().setParameter(CoreProtocolPNames.USER_AGENT, "Nexus-Client/" + discoverClientVersion()); // "tweak" HTTPS scheme as requested final TrustStrategy trustStrategy; switch (connectionInfo.getSslCertificateValidation()) { case NONE: trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { return true; } }; break; case LAX: trustStrategy = new TrustSelfSignedStrategy(); break; default: trustStrategy = null; } final X509HostnameVerifier hostnameVerifier; switch (connectionInfo.getSslCertificateHostnameValidation()) { case NONE: hostnameVerifier = new AllowAllHostnameVerifier(); break; case STRICT: hostnameVerifier = new StrictHostnameVerifier(); break; default: hostnameVerifier = new BrowserCompatHostnameVerifier(); } try { final SSLSocketFactory ssf = new SSLSocketFactory(trustStrategy, hostnameVerifier); final Scheme tweakedHttpsScheme = new Scheme("https", 443, ssf); client.getClientHandler().getHttpClient().getConnectionManager().getSchemeRegistry() .register(tweakedHttpsScheme); } catch (Exception e) { Throwables.propagate(e); } // NXCM-4547 JERSEY-1293 Enforce proxy setting on httpclient enforceProxyUri(config, client); if (LOG.isDebugEnabled()) { client.addFilter(new LoggingFilter()); } client.addFilter(new RequestFilters()); return client; }
From source file:com.crosstreelabs.cognitio.gumshoe.transport.HttpTransport.java
private void buildHttpClient() { requestConfig = RequestConfig.custom().setExpectContinueEnabled(false).setCookieSpec(CookieSpecs.DEFAULT) .setRedirectsEnabled(false).setSocketTimeout(5000).setConnectTimeout(5000) .setConnectionRequestTimeout(5000).setStaleConnectionCheckEnabled(true).build(); RegistryBuilder<ConnectionSocketFactory> connRegistryBuilder = RegistryBuilder.create(); connRegistryBuilder.register("http", PlainConnectionSocketFactory.INSTANCE); try { // Fixing: https://code.google.com/p/crawler4j/issues/detail?id=174 // By always trusting the ssl certificate SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustStrategy() { @Override//from w w w .j a v a2 s.c o m public boolean isTrusted(final X509Certificate[] chain, String authType) { return true; } }).build(); SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); connRegistryBuilder.register("https", sslsf); } catch (KeyManagementException | KeyStoreException | NoSuchAlgorithmException e) { LOGGER.warn("Exception thrown while trying to register https"); LOGGER.debug("Stacktrace", e); } Registry<ConnectionSocketFactory> connRegistry = connRegistryBuilder.build(); connectionManager = new PoolingHttpClientConnectionManager(connRegistry); connectionManager.setMaxTotal(5); connectionManager.setDefaultMaxPerRoute(5); HttpClientBuilder clientBuilder = HttpClientBuilder.create(); clientBuilder.setDefaultRequestConfig(requestConfig); clientBuilder.setConnectionManager(connectionManager); clientBuilder.setUserAgent("Cognitio"); httpClient = clientBuilder.build(); }
From source file:net.paissad.waqtsalat.service.utils.HttpUtils.java
private static HttpClient getNewHttpClient() throws WSException { try {// w ww .j av a 2s. co m TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLSocketFactory sf = new CustomSSLFactory(trustStrategy); HttpParams params = new BasicHttpParams(); HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1); HttpProtocolParams.setContentCharset(params, HTTP.UTF_8); SchemeRegistry sr = new SchemeRegistry(); sr.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); sr.register(new Scheme("https", 443, sf)); ClientConnectionManager ccm = new ThreadSafeClientConnManager(sr); DefaultHttpClient client = new DefaultHttpClient(ccm); client.setHttpRequestRetryHandler(new CustomHttpRequestRetryHandler()); client.getParams().setParameter(ClientPNames.HANDLE_REDIRECTS, true); client.getParams().setParameter(ClientPNames.COOKIE_POLICY, CookiePolicy.BEST_MATCH); List<String> authpref = new ArrayList<String>(); // Choose BASIC over DIGEST for proxy authentication authpref.add(AuthPolicy.BASIC); authpref.add(AuthPolicy.DIGEST); client.getParams().setParameter(AuthPNames.PROXY_AUTH_PREF, authpref); client.addRequestInterceptor(new CustomHttpRequestInterceptor()); client.addResponseInterceptor(new CustomHttpResponseInterceptor()); return client; } catch (Exception e) { throw new WSException("Error while creating a HTTP client.", e); } }
From source file:org.envirocar.analyse.AggregationAlgorithm.java
protected HttpClient createClient() throws IOException, KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException { DefaultHttpClient result = new DefaultHttpClient(); SchemeRegistry sr = result.getConnectionManager().getSchemeRegistry(); SSLSocketFactory sslsf = new SSLSocketFactory(new TrustStrategy() { @Override//from w ww . ja v a 2 s . c o m public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }, new AllowAllHostnameVerifier()); Scheme httpsScheme2 = new Scheme("https", 443, sslsf); sr.register(httpsScheme2); return result; }
From source file:com.att.api.rest.RESTClient.java
/** * Creates an http client that can be used for sending http requests. * * <p>/*from w w w . j a v a 2 s .c o m*/ * Sets proxy and certificate settings. * </p> * * @return http client * @throws RESTException if unable to create http client. */ private HttpClient createClient() throws RESTException { DefaultHttpClient client; if (trustAllCerts) { // Trust all host certs. Only enable if on testing! SSLSocketFactory socketFactory = null; try { socketFactory = new SSLSocketFactory(new TrustStrategy() { public boolean isTrusted(final X509Certificate[] chain, String authType) { return true; } }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); } catch (Exception e) { // shouldn't occur, but just in case final String msg = e.getMessage(); throw new RESTException("Unable to create HttpClient. " + msg); } SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); registry.register(new Scheme("https", 443, socketFactory)); ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry); client = new DefaultHttpClient(cm, new DefaultHttpClient().getParams()); } else { client = new DefaultHttpClient(); } client.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); setProxyAttributes(client); return client; }
From source file:com.ibm.streamsx.rest.StreamsConnection.java
/** * This function is used to disable checking the trusted certificate chain * and should never be used in production environments * /*from w w w . j a v a2s. c o m*/ * @param allowInsecure * <ul> * <li>true - disables checking</li> * <li>false - enables checking (default)</li> * </ul> * @return a boolean indicating the state of the connection after this * method was called. * <ul> * <li>true - if checking is disabled</li> * <li>false - if checking is enabled</li> * </ul> */ public boolean allowInsecureHosts(boolean allowInsecure) { try { if ((allowInsecure) && (false == allowInsecureHosts)) { CloseableHttpClient httpClient = HttpClients.custom() .setHostnameVerifier(new AllowAllHostnameVerifier()) .setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() { public boolean isTrusted(X509Certificate[] arg0, String arg1) throws CertificateException { return true; } }).build()).build(); executor = Executor.newInstance(httpClient); allowInsecureHosts = true; } else if ((false == allowInsecure) && (true == allowInsecureHosts)) { executor = Executor.newInstance(); allowInsecureHosts = false; } } catch (NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) { executor = Executor.newInstance(); allowInsecureHosts = false; } if (allowInsecureHosts) { traceLog.info("Insecure Host Connection enabled"); } return allowInsecureHosts; }
From source file:com.enigmabridge.log.distributor.forwarder.splunk.HttpEventCollectorSender.java
private void startHttpClient() { if (httpClient != null) { // http client is already started return;/*from w ww.ja va2s . c o m*/ } // limit max number of async requests in sequential mode, 0 means "use // default limit" int maxConnTotal = sendMode == SendMode.Sequential ? 1 : 0; if (!disableCertificateValidation) { // create an http client that validates certificates httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal).build(); } else { // create strategy that accepts all certificates TrustStrategy acceptingTrustStrategy = new TrustStrategy() { public boolean isTrusted(X509Certificate[] certificate, String type) { return true; } }; SSLContext sslContext = null; try { sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build(); httpClient = HttpAsyncClients.custom().setMaxConnTotal(maxConnTotal) .setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) .setSSLContext(sslContext).build(); } catch (Exception e) { } } httpClient.start(); }
From source file:com.linkedin.drelephant.clients.azkaban.AzkabanWorkflowClient.java
/** * Makes REST API Call for given url parameters and returns the json object * * @param urlParameters//from w ww . j a v a 2s .c o m * @return Json Object in the response body */ private JSONObject fetchJson(List<NameValuePair> urlParameters, String azkabanUrl) { HttpPost httpPost = new HttpPost(azkabanUrl); try { httpPost.setEntity(new UrlEncodedFormEntity(urlParameters, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } httpPost.setHeader("Accept", "*/*"); httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded"); HttpClient httpClient = new DefaultHttpClient(); JSONObject jsonObj = null; try { SSLSocketFactory socketFactory = new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException { return true; } }); Scheme scheme = new Scheme("https", 443, socketFactory); httpClient.getConnectionManager().getSchemeRegistry().register(scheme); HttpResponse response = httpClient.execute(httpPost); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new RuntimeException(response.getStatusLine().toString() + "\nStatus code: " + response.getStatusLine().getStatusCode()); } String result = parseContent(response.getEntity().getContent()); try { jsonObj = new JSONObject(result); if (jsonObj.has("error")) { throw new RuntimeException(jsonObj.get("error").toString()); } } catch (JSONException e) { e.printStackTrace(); } } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (UnrecoverableKeyException e) { e.printStackTrace(); } catch (KeyManagementException e) { e.printStackTrace(); } catch (KeyStoreException e) { e.printStackTrace(); } finally { httpClient.getConnectionManager().shutdown(); } return jsonObj; }
From source file:com.esri.geoevent.test.performance.provision.GeoEventProvisioner.java
private SSLConnectionSocketFactory getSSLSocketFactory() { KeyStore trustStore;// w ww.java 2 s . c o m try { trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(null, null); TrustStrategy trustStrategy = new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { return true; } }; SSLContextBuilder sslContextBuilder = new SSLContextBuilder(); sslContextBuilder.loadTrustMaterial(trustStore, trustStrategy); sslContextBuilder.useTLS(); SSLContext sslContext = sslContextBuilder.build(); SSLConnectionSocketFactory sslSocketFactory = new SSLConnectionSocketFactory(sslContext); return sslSocketFactory; } catch (GeneralSecurityException | IOException e) { System.err.println("SSL Error : " + e.getMessage()); } return null; }