List of usage examples for org.apache.http.conn.ssl SSLSocketFactory SSLSocketFactory
public SSLSocketFactory(final SSLContext sslContext)
From source file:com.servoy.extensions.plugins.http.HttpClient.java
public HttpClient(IClientPluginAccess plugin) { client = new DefaultHttpClient(); client.getParams().setParameter(ClientPNames.ALLOW_CIRCULAR_REDIRECTS, Boolean.TRUE); client.getAuthSchemes().register(AuthPolicy.NTLM, new NTLMSchemeFactory()); client.getAuthSchemes().register(AuthPolicy.SPNEGO, new NegotiateSchemeFactory()); this.plugin = plugin; try {// ww w . java 2s . c om final AllowedCertTrustStrategy allowedCertTrustStrategy = new AllowedCertTrustStrategy(); SSLSocketFactory sf = new SSLSocketFactory(allowedCertTrustStrategy) { @Override public Socket connectSocket(Socket socket, InetSocketAddress remoteAddress, InetSocketAddress localAddress, HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException { if (socket instanceof SSLSocket) { try { Method s = socket.getClass().getMethod("setHost", String.class); s.invoke(socket, remoteAddress.getHostName()); } catch (NoSuchMethodException ex) { } catch (IllegalAccessException ex) { } catch (InvocationTargetException ex) { } catch (IllegalArgumentException ex) { } catch (SecurityException ex) { } } try { return super.connectSocket(socket, remoteAddress, localAddress, params); } catch (SSLPeerUnverifiedException ex) { X509Certificate[] lastCertificates = allowedCertTrustStrategy.getAndClearLastCertificates(); if (lastCertificates != null) { // allow for next time if (HttpClient.this.plugin.getApplicationType() == IClientPluginAccess.CLIENT || HttpClient.this.plugin.getApplicationType() == IClientPluginAccess.RUNTIME) { // show dialog CertificateDialog dialog = new CertificateDialog( ((ISmartRuntimeWindow) HttpClient.this.plugin.getCurrentRuntimeWindow()) .getWindow(), remoteAddress, lastCertificates); if (dialog.shouldAccept()) { allowedCertTrustStrategy.add(lastCertificates); // try it again now with the new chain. return super.connectSocket(socket, remoteAddress, localAddress, params); } } else { Debug.error("Couldn't connect to " + remoteAddress + ", please make sure that the ssl certificates of that site are added to the java keystore." + "Download the keystore in the browser and update the java cacerts file in jre/lib/security: " + "keytool -import -file downloaded.crt -keystore cacerts"); } } throw ex; } finally { // always just clear the last request. allowedCertTrustStrategy.getAndClearLastCertificates(); } } }; Scheme https = new Scheme("https", 443, sf); //$NON-NLS-1$ client.getConnectionManager().getSchemeRegistry().register(https); } catch (Exception e) { Debug.error("Can't register a https scheme", e); //$NON-NLS-1$ } }
From source file:neembuu.vfs.test.FileNameAndSizeFinderService.java
private DefaultHttpClient newClient() { DefaultHttpClient client = new DefaultHttpClient(); GlobalTestSettings.ProxySettings proxySettings = GlobalTestSettings.getGlobalProxySettings(); HttpContext context = new BasicHttpContext(); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(new Scheme("http", new PlainSocketFactory(), 80)); try {/*from www. j a v a 2 s . c o m*/ KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); schemeRegistry.register(new Scheme("https", new SSLSocketFactory(keyStore), 8080)); } catch (Exception a) { a.printStackTrace(System.err); } context.setAttribute(ClientContext.SCHEME_REGISTRY, schemeRegistry); context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, new BasicScheme()/*file.httpClient.getAuthSchemes()*/); context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, client.getCookieSpecs()/*file.httpClient.getCookieSpecs()*/ ); BasicCookieStore basicCookieStore = new BasicCookieStore(); context.setAttribute(ClientContext.COOKIE_STORE, basicCookieStore/*file.httpClient.getCookieStore()*/); context.setAttribute(ClientContext.CREDS_PROVIDER, new BasicCredentialsProvider()/*file.httpClient.getCredentialsProvider()*/); HttpConnection hc = new DefaultHttpClientConnection(); context.setAttribute(ExecutionContext.HTTP_CONNECTION, hc); //System.out.println(file.httpClient.getParams().getParameter("http.useragent")); HttpParams httpParams = new BasicHttpParams(); if (proxySettings != null) { AuthState as = new AuthState(); as.setCredentials(new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password)); as.setAuthScope(AuthScope.ANY); as.setAuthScheme(new BasicScheme()); httpParams.setParameter(ClientContext.PROXY_AUTH_STATE, as); httpParams.setParameter("http.proxy_host", new HttpHost(proxySettings.host, proxySettings.port)); } client = new DefaultHttpClient( new SingleClientConnManager(httpParams/*file.httpClient.getParams()*/, schemeRegistry), httpParams/*file.httpClient.getParams()*/); if (proxySettings != null) { client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(proxySettings.userName, proxySettings.password)); } return client; }
From source file:bear.plugins.java.JenkinsCache.java
public static File download2(String jdkVersion, File jenkinsCache, File tempDestDir, String jenkinsUri, String user, String pass) { try {//w w w .j ava2 s . c o m Optional<JDKFile> optional = load(jenkinsCache, jenkinsUri, jdkVersion); if (!optional.isPresent()) { throw new RuntimeException("could not find: " + jdkVersion); } String uri = optional.get().filepath; // agent.get() // agent.get() SSLContext sslContext = SSLContext.getInstance("TLSv1"); sslContext.init(null, new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { System.out.println("getAcceptedIssuers ============="); return null; } public void checkClientTrusted(X509Certificate[] certs, String authType) { System.out.println("checkClientTrusted ============="); } public void checkServerTrusted(X509Certificate[] certs, String authType) { System.out.println("checkServerTrusted ============="); } } }, new SecureRandom()); SSLSocketFactory sf = new SSLSocketFactory(sslContext); Scheme httpsScheme = new Scheme("https", 443, sf); SchemeRegistry schemeRegistry = new SchemeRegistry(); schemeRegistry.register(httpsScheme); DefaultHttpClient httpClient = new DefaultHttpClient( new PoolingClientConnectionManager(schemeRegistry)); MechanizeAgent agent = new MechanizeAgent(); Cookie cookie2 = agent.cookies().addNewCookie("gpw_e24", ".", "oracle.com"); cookie2.getHttpCookie().setPath("/"); cookie2.getHttpCookie().setSecure(false); CookieStore cookieStore = new BasicCookieStore(); BasicClientCookie cookie = new BasicClientCookie("gpw_e24", "."); cookie.setDomain("oracle.com"); cookie.setPath("/"); cookie.setSecure(true); cookieStore.addCookie(cookie); httpClient.setCookieStore(cookieStore); HttpPost httppost = new HttpPost("https://login.oracle.com"); httppost.setHeader("Authorization", "Basic " + new String(Base64.encodeBase64((user + ":" + pass).getBytes()), "UTF-8")); HttpResponse response = httpClient.execute(httppost); int code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("unable to auth: " + code); } // EntityUtils.consumeQuietly(response.getEntity()); httppost = new HttpPost(uri); response = httpClient.execute(httppost); code = response.getStatusLine().getStatusCode(); if (code != 302) { System.out.println(IOUtils.toString(response.getEntity().getContent())); throw new RuntimeException("to download: " + uri); } File file = new File(tempDestDir, optional.get().name); HttpEntity entity = response.getEntity(); final long length = entity.getContentLength(); final CountingOutputStream os = new CountingOutputStream(new FileOutputStream(file)); System.out.printf("Downloading %s to %s...%n", uri, file); Thread progressThread = new Thread(new Runnable() { double lastProgress; @Override public void run() { while (!Thread.currentThread().isInterrupted()) { long copied = os.getCount(); double progress = copied * 100D / length; if (progress != lastProgress) { System.out.printf("\rProgress: %s%%", LangUtils.toConciseString(progress, 1)); } lastProgress = progress; try { Thread.sleep(500); } catch (InterruptedException e) { break; } } } }, "progressThread"); progressThread.start(); ByteStreams.copy(entity.getContent(), os); progressThread.interrupt(); System.out.println("Download complete."); return file; } catch (Exception e) { throw Exceptions.runtime(e); } }
From source file:io.undertow.testutils.TestHttpClient.java
public void setSSLContext(final SSLContext sslContext) { SchemeRegistry registry = getConnectionManager().getSchemeRegistry(); registry.unregister("https"); if (DefaultServer.getHostAddress(DefaultServer.DEFAULT).equals("localhost")) { registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext))); registry.register(/*from w w w . java2s. c om*/ new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext))); } else { registry.register(new Scheme("https", 443, new SSLSocketFactory(sslContext, NO_OP_VERIFIER))); registry.register(new Scheme("https", DefaultServer.getHostSSLPort("default"), new SSLSocketFactory(sslContext, NO_OP_VERIFIER))); } }
From source file:org.wso2.carbon.apimgt.gateway.handlers.security.thrift.ThriftAuthClient.java
public ThriftAuthClient(String serverIP, String remoteServerPort, String webContextRoot) throws AuthenticationException { try {/* w w w. j a v a 2 s .c om*/ TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) { } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; //skip host name verification SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslContext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //REGISTERS SCHEMES FOR BOTH HTTP AND HTTPS SchemeRegistry registry = new SchemeRegistry(); registry.register(new Scheme("https", sf, Integer.parseInt(remoteServerPort))); PoolingClientConnectionManager manager = new PoolingClientConnectionManager(registry); HttpClient httpClient = new DefaultHttpClient(manager); //If the webContextRoot is null or / if (webContextRoot == null || "/".equals(webContextRoot)) { //Assign it an empty value since it is part of the thriftServiceURL. webContextRoot = ""; } String thriftServiceURL = "https://" + serverIP + ':' + remoteServerPort + webContextRoot + '/' + "thriftAuthenticator"; client = new THttpClient(thriftServiceURL, httpClient); } catch (TTransportException e) { throw new AuthenticationException("Error in creating thrift authentication client..", e); } catch (Exception e) { throw new AuthenticationException("Error in creating thrift authentication client..", e); } }
From source file:org.mobicents.servlet.restcomm.fax.InterfaxService.java
private URI send(final Object message) throws Exception { final FaxRequest request = (FaxRequest) message; final String to = request.to(); final File file = request.file(); // Prepare the request. final DefaultHttpClient client = new DefaultHttpClient(); final HttpContext context = new BasicHttpContext(); final SSLSocketFactory sockets = new SSLSocketFactory(strategy); final Scheme scheme = new Scheme("https", 443, sockets); client.getConnectionManager().getSchemeRegistry().register(scheme); final UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(user, password); final HttpPost post = new HttpPost(url + to); final String mime = URLConnection.guessContentTypeFromName(file.getName()); final FileEntity entity = new FileEntity(file, mime); post.addHeader(new BasicScheme().authenticate(credentials, post, context)); post.setEntity(entity);/*from w w w . j a v a 2 s. co m*/ // Handle the response. final HttpResponse response = client.execute(post, context); final StatusLine status = response.getStatusLine(); final int code = status.getStatusCode(); if (HttpStatus.SC_CREATED == code) { EntityUtils.consume(response.getEntity()); final Header[] headers = response.getHeaders(HttpHeaders.LOCATION); final Header location = headers[0]; final String resource = location.getValue(); return URI.create(resource); } else { final StringBuilder buffer = new StringBuilder(); buffer.append(code).append(" ").append(status.getReasonPhrase()); throw new FaxServiceException(buffer.toString()); } }
From source file:org.jasig.portal.security.provider.saml.SSLSecurityImpl.java
public SSLSocketFactory getSSLSocketFactory() { try {//ww w .j av a 2 s.com //Implementation taken from SSLSocketFactory constructor with added support for a trust-all //trust store if no trustStore is explicitly configured and public keys are available KeyManager[] keymanagers = null; if (keyStore != null) { keymanagers = createKeyManagers(keyStore, keyStorePass); } TrustManager[] trustmanagers = null; if (trustStore != null) { trustmanagers = createTrustManagers(trustStore); } else if (publicKeys != null) { trustmanagers = new TrustManager[] { TrustAllX509TrustManager.INSTANCE }; } final SSLContext sslcontext = SSLContext.getInstance(SSLSocketFactory.TLS); sslcontext.init(keymanagers, trustmanagers, null); if (publicKeys != null) { return new PublicKeyVerifyingSSLSocketFactory(sslcontext, publicKeys); } return new SSLSocketFactory(sslcontext); } catch (Exception ex) { throw new DelegatedAuthenticationRuntimeException( "Error dealing with SSL. See stack trace for details.", ex); } }
From source file:org.wso2.carbon.appmgt.gateway.handlers.security.thrift.ThriftAuthClient.java
public ThriftAuthClient(String serverIP, String remoteServerPort, String webContextRoot) throws AuthenticationException { try {//from www . j a v a2s. c o m TrustManager easyTrustManager = new X509TrustManager() { public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException { } public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } }; //skip host name verification SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, new TrustManager[] { easyTrustManager }, null); SSLSocketFactory sf = new SSLSocketFactory(sslContext); sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); Scheme httpsScheme = new Scheme("https", sf, Integer.parseInt(remoteServerPort)); DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getConnectionManager().getSchemeRegistry().register(httpsScheme); //If the webContextRoot is null or / if (webContextRoot == null || "/".equals(webContextRoot)) { //Assign it an empty value since it is part of the thriftServiceURL. webContextRoot = ""; } String thriftServiceURL = "https://" + serverIP + ":" + remoteServerPort + webContextRoot + "/" + "thriftAuthenticator"; client = new THttpClient(thriftServiceURL, httpClient); } catch (TTransportException e) { throw new AuthenticationException("Error in creating thrift authentication client.."); } catch (Exception e) { throw new AuthenticationException("Error in creating thrift authentication client.."); } }
From source file:com.longle1.facedetection.TimedAsyncHttpResponseHandler.java
public void executePut(String putURL, RequestParams params, JSONObject json) { try {/* www . jav a 2 s . c o m*/ AsyncHttpClient client = new AsyncHttpClient(); StringEntity se = null; try { se = new StringEntity(json.toString()); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return; } se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json")); // Add SSL KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType()); trustStore.load(mContext.getResources().openRawResource(R.raw.truststore), "changeit".toCharArray()); SSLSocketFactory sf = new SSLSocketFactory(trustStore); client.setSSLSocketFactory(sf); client.setTimeout(30000); client.put(null, putURL + "?" + params.toString(), se, null, this); } catch (Exception e) { e.printStackTrace(); } Log.i("executePut", "done"); }