List of usage examples for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory
public SSLSocketFactory(final SSLContext sslContext)
From source file:com.gorillalogic.monkeytalk.ant.RunTask.java
private String sendFormPost(String url, File proj, Map<String, String> additionalParams) throws IOException { HttpClient base = new DefaultHttpClient(); SSLContext ctx = null;//from ww w . java 2s . c o m try { ctx = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException ex) { log("exception in sendFormPost():"); } X509TrustManager tm = new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } @Override public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws java.security.cert.CertificateException { } }; try { ctx.init(null, new TrustManager[] { tm }, null); } catch (KeyManagementException ex) { log("exception in sendFormPost():"); } SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = base.getConnectionManager(); SchemeRegistry sr = ccm.getSchemeRegistry(); sr.register(new Scheme("https", ssf, 443)); HttpClient client = new DefaultHttpClient(ccm, base.getParams()); try { HttpPost post = new HttpPost(url); MultipartEntity multipart = new MultipartEntity(); for (String key : additionalParams.keySet()) multipart.addPart(key, new StringBody(additionalParams.get(key), Charset.forName("UTF-8"))); if (proj != null) { multipart.addPart("uploaded_file", new FileBody(proj)); } post.setEntity(multipart); HttpResponse resp = client.execute(post); HttpEntity out = resp.getEntity(); InputStream in = out.getContent(); return FileUtils.readStream(in); } catch (Exception ex) { throw new IOException("POST failed", ex); } finally { try { client.getConnectionManager().shutdown(); } catch (Exception ex) { // ignore } } }
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 a2 s . c o 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.aliyun.api.gateway.demo.util.HttpUtil.java
private static void sslClient(HttpClient httpClient) { try {//from ww w . j ava 2s .com SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] xcs, String str) { } public void checkServerTrusted(X509Certificate[] xcs, String str) { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = httpClient.getConnectionManager(); SchemeRegistry registry = ccm.getSchemeRegistry(); registry.register(new Scheme("https", 443, ssf)); } catch (KeyManagementException ex) { throw new RuntimeException(ex); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }
From source file:cn.tc.ulife.platform.msg.http.util.HttpUtil.java
private static void sslClient(HttpClient httpClient) { try {//from w ww. jav a2 s. c o m SSLContext ctx = SSLContext.getInstance("TLS"); X509TrustManager tm = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted(X509Certificate[] xcs, String str) { } public void checkServerTrusted(X509Certificate[] xcs, String str) { } }; ctx.init(null, new TrustManager[] { tm }, null); SSLSocketFactory ssf = new SSLSocketFactory(ctx); ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); ClientConnectionManager ccm = httpClient.getConnectionManager(); SchemeRegistry registry = ccm.getSchemeRegistry(); registry.register(new Scheme("https", ssf, 443)); } catch (KeyManagementException ex) { throw new RuntimeException(ex); } catch (NoSuchAlgorithmException ex) { throw new RuntimeException(ex); } }
From source file:org.ellis.yun.search.test.httpclient.HttpClientTest.java
@SuppressWarnings("deprecation") @Test//from w w w . ja v a2 s.c o m public void testSSLConnection() throws Exception { Scheme http = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80); SSLSocketFactory ssf = new SSLSocketFactory(SSLContext.getInstance("TLS")); ssf.setHostnameVerifier(SSLSocketFactory.STRICT_HOSTNAME_VERIFIER); Scheme https = new Scheme("https", ssf, 443); SchemeRegistry sr = new SchemeRegistry(); sr.register(http); sr.register(https); TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] arg0, String arg1) { System.out.println("checkClientTrusted"); } public void checkServerTrusted(java.security.cert.X509Certificate[] arg0, String arg1) { System.out.println("checkServerTrusted"); } public java.security.cert.X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers"); return null; } }; SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslcontext); SSLSocket socket = (SSLSocket) sf.createSocket(); socket.setEnabledCipherSuites(new String[] { "SSL_RSA_WITH_RC4_128_MD5" }); HttpParams params = new BasicHttpParams(); params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 1000); sf.connectSocket(socket, "119.29.234.42", 443, null, -1, params); }
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());// ww w. j a va 2 s. co 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:de.betterform.connector.http.AbstractHTTPConnector.java
private void initSSLScheme(String contextPath) throws Exception { LOGGER.debug("creating sslScheme ..."); LOGGER.debug("KeyStoreSSLContext: " + contextPath); Class contextClass = Class.forName(contextPath); Object context = contextClass.newInstance(); Vector<Scheme> schemes = new Vector<Scheme>(); if (context instanceof KeyStoreSSLContext) { int httpSSLPort = 443; int tomcatSSLPort = 8443; SSLSocketFactory socketFactory = new SSLSocketFactory(((KeyStoreSSLContext) context).getSSLContext()); if (Config.getInstance().getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT_CUSTOMPORT) != null) { try { int customPort = Integer.parseInt(Config.getInstance() .getProperty(AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT_CUSTOMPORT)); LOGGER.trace("CustomPort: " + customPort); Scheme sslScheme = new Scheme("https", customPort, socketFactory); schemes.add(sslScheme);// ww w . j a va 2 s . c om } catch (NumberFormatException nfe) { LOGGER.warn( AbstractHTTPConnector.HTTPCLIENT_SSL_CONTEXT_CUSTOMPORT + " is not parsable as a number. Check your settings in betterform-config.xml!", nfe); } } Scheme sslScheme1 = new Scheme("https", httpSSLPort, socketFactory); schemes.add(sslScheme1); Scheme sslScheme2 = new Scheme("https", tomcatSSLPort, socketFactory); schemes.add(sslScheme2); getContext().put(AbstractHTTPConnector.SSL_CUSTOM_SCHEME, schemes); } }
From source file:org.opensaml.util.http.HttpClientBuilder.java
/** * Creates the default scheme registry for connection. The constructed registry supports http with a default port of * 80 and https with a default port of 443. If {@link #connectionDisregardSslCertificate} is true, than the https * port will accept any certificate presented by the responder. * // ww w .java2 s .c o m * @return the default scheme registry. */ private SchemeRegistry buildSchemeRegistry() { final SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory())); final SSLSocketFactory sslSF; if (!connectionDisregardSslCertificate) { sslSF = SSLSocketFactory.getSocketFactory(); } else { X509TrustManager noTrustManager = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { // accept everything } public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { // accept everything } }; try { SSLContext sslcontext = SSLContext.getInstance("TLS"); sslcontext.init(null, new TrustManager[] { noTrustManager }, null); sslSF = new SSLSocketFactory(sslcontext); } catch (NoSuchAlgorithmException e) { throw new RuntimeException("TLS SSLContext type is required to be supported by the JVM but is not", e); } catch (KeyManagementException e) { throw new RuntimeException("Some how the trust everything trust manager didn't trust everything", e); } } registry.register(new Scheme("https", 443, sslSF)); return registry; }
From source file:org.syncany.plugins.php.PhpTransferManager.java
@SuppressWarnings("deprecation") private CloseableHttpClient getHttpClient() { try {/* ww w .j a va 2 s. c om*/ @SuppressWarnings("deprecation") SSLSocketFactory sf = new SSLSocketFactory(new TrustStrategy() { @Override public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException { if (lastSite != null && !lastSite.equals("")) { Preferences prefs = Preferences.userRoot().node(this.getClass().getName()); int prevr = prefs.getInt(lastSite, -1); if (prevr == -1) { int r = JOptionPane.showConfirmDialog(null, lastSite + "'s SSL certificate is not trusted, do you want to accept it?", "Accept SSL Certificate?", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE); logger.warning(lastSite + " not trusted, user answered " + r); prevr = r; prefs.putInt(lastSite, r); } logger.warning(lastSite + " not trusted, registered user answer: " + prevr); if (prevr == 0) { return true; } else { return false; } } else { return false; } } }); @SuppressWarnings("deprecation") SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", 443, sf)); @SuppressWarnings("deprecation") ClientConnectionManager ccm = new ThreadSafeClientConnManager(registry); return new DefaultHttpClient(ccm); } catch (Exception e) { return new DefaultHttpClient(); } }