List of usage examples for javax.net.ssl SSLContext getSocketFactory
public final SSLSocketFactory getSocketFactory()
From source file:com.clustercontrol.agent.Agent.java
/** * // ww w . java2s . c o m */ public Agent(String propFileName) throws Exception { //------------ //-- ?? //------------ //??? AgentProperties.init(propFileName); // ?IP???? getAgentInfo(); m_log.info(getAgentStr()); // log4j??? String log4jFileName = System.getProperty("hinemos.agent.conf.dir") + File.separator + "log4j.properties"; m_log.info("log4j.properties = " + log4jFileName); m_log4jFileName = log4jFileName; int connectTimeout = DEFAULT_CONNECT_TIMEOUT; int requestTimeout = DEFAULT_REQUEST_TIMEOUT; // String proxyHost = DEFAULT_PROXY_HOST; int proxyPort = DEFAULT_PROXY_PORT; String proxyUser = DEFAULT_PROXY_USER; String proxyPassword = DEFAULT_PROXY_PASSWORD; // ???hostnameVerifier?HTTPS???? try { HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, javax.net.ssl.SSLSession session) { return true; } }; // Create the trust manager. javax.net.ssl.TrustManager[] trustAllCerts = new javax.net.ssl.TrustManager[1]; class AllTrustManager implements javax.net.ssl.TrustManager, javax.net.ssl.X509TrustManager { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkServerTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } public void checkClientTrusted(java.security.cert.X509Certificate[] certs, String authType) throws java.security.cert.CertificateException { return; } } javax.net.ssl.TrustManager tm = new AllTrustManager(); trustAllCerts[0] = tm; // Create the SSL context javax.net.ssl.SSLContext sc = javax.net.ssl.SSLContext.getInstance("SSL"); // Create the session context javax.net.ssl.SSLSessionContext sslsc = sc.getServerSessionContext(); // Initialize the contexts; the session context takes the // trust manager. sslsc.setSessionTimeout(0); sc.init(null, trustAllCerts, null); // Use the default socket factory to create the socket for // the secure // connection javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); // Set the default host name verifier to enable the connection. HttpsURLConnection.setDefaultHostnameVerifier(hv); } catch (Throwable e) { m_log.warn("hostname verifier (all trust) disable : " + e.getMessage(), e); } try { String strConnect = AgentProperties.getProperty("connect.timeout"); if (strConnect != null) { connectTimeout = Integer.parseInt(strConnect); } String strRequest = AgentProperties.getProperty("request.timeout"); if (strRequest != null) { requestTimeout = Integer.parseInt(strRequest); } String strProxyHost = AgentProperties.getProperty("http.proxy.host"); if (strProxyHost != null) { proxyHost = strProxyHost; } String strProxyPort = AgentProperties.getProperty("http.proxy.port"); if (strProxyPort != null) { proxyPort = Integer.parseInt(strProxyPort); } String strProxyUser = AgentProperties.getProperty("http.proxy.user"); if (strProxyUser != null) { proxyUser = strProxyUser; } String strProxyPassword = AgentProperties.getProperty("http.proxy.password"); if (strProxyPassword != null) { proxyPassword = strProxyPassword; } } catch (Exception e) { m_log.warn(e.getMessage()); } if (!"".equals(proxyHost)) { System.setProperty("http.proxyHost", proxyHost); System.setProperty("http.proxyPort", Integer.toString(proxyPort)); BasicAuth basicAuth = new BasicAuth(proxyUser, proxyPassword); Authenticator.setDefault(basicAuth); m_log.info("proxy.host=" + System.getProperty("http.proxyHost") + ", proxy.port=" + System.getProperty("http.proxyPort") + ", proxy.user=" + proxyUser); } // ?? ${ManagerIP} ????????????? // ??PING????????IP????FacilityID?????? String managerAddress = AgentProperties.getProperty("managerAddress"); URL url = new URL(managerAddress); boolean replacePropFileSuccess = true; String errMsg = ""; if (REPLACE_VALUE_MANAGER_IP.equals((url.getHost()))) { try { // ???PING?????PING??????? Map<String, String> discoveryInfoMap = new HashMap<String, String>(); while (true) { m_log.info("waiting for manager connection..."); String recvMsg = receiveManagerDiscoveryInfo(); // ????key=value,key=value ??????Map?? try { discoveryInfoMap.clear(); String[] commaSplittedRecvMsgArray = recvMsg.split(","); for (String keyvalueset : commaSplittedRecvMsgArray) { String key = keyvalueset.split("=")[0]; String value = keyvalueset.split("=")[1]; discoveryInfoMap.put(key, value); } } catch (Exception e) { m_log.error("can't parse receive message : " + e.toString()); continue; } if (discoveryInfoMap.containsKey("agentFacilityId") && discoveryInfoMap.containsKey("managerIp")) { break; } else { m_log.error("receive message is invalid"); } } // Agent.properties????????????? { String managerIp = discoveryInfoMap.get("managerIp"); String key = "managerAddress"; String value = url.getProtocol() + "://" + managerIp + ":" + url.getPort() + "/HinemosWS/"; m_log.info("Rewrite property. key : " + key + ", value : " + value); PropertiesFileUtil.replacePropertyFile(propFileName, key, managerAddress, value); AgentProperties.setProperty(key, value); } // Agent.properties?ID?????????? { String key = "facilityId"; String value = discoveryInfoMap.get("agentFacilityId"); m_log.info("Rewrite property. key : " + key + ", value : " + value); PropertiesFileUtil.replacePropertyFile(propFileName, key, "", value); AgentProperties.setProperty(key, value); } // log4j.properties?????Windows?? { String managerIp = discoveryInfoMap.get("managerIp"); String key = "log4j.appender.syslog.SyslogHost"; PropertiesFileUtil.replacePropertyFile(log4jFileName, "log4j.appender.syslog.SyslogHost", REPLACE_VALUE_MANAGER_IP, managerIp); if (REPLACE_VALUE_MANAGER_IP.equals(AgentProperties.getProperty(key))) { m_log.info("Rewrite property. key : " + key + ", value : " + managerIp); PropertiesFileUtil.replacePropertyFile(log4jFileName, key, REPLACE_VALUE_MANAGER_IP, managerIp); } } } catch (HinemosUnknown e) { // ???????????? errMsg = e.getMessage(); m_log.warn(errMsg, e); replacePropFileSuccess = false; } catch (Exception e) { m_log.warn(e.getMessage(), e); throw e; } } try { EndpointManager.init(AgentProperties.getProperty("user"), AgentProperties.getProperty("password"), AgentProperties.getProperty("managerAddress"), connectTimeout, requestTimeout); } catch (Exception e) { m_log.error("EndpointManager.init error : " + e.getMessage(), e); m_log.error("current-dir=" + (new File(".")).getAbsoluteFile().getParent()); throw e; } if (!replacePropFileSuccess) { OutputBasicInfo output = new OutputBasicInfo(); output.setPluginId("AGT_UPDATE_CONFFILE"); output.setPriority(PriorityConstant.TYPE_WARNING); output.setApplication(MessageConstant.AGENT.getMessage()); String[] args = { errMsg }; output.setMessage(MessageConstant.MESSAGE_AGENT_REPLACE_FILE_FAULURE_NOTIFY_MSG.getMessage()); output.setMessageOrg( MessageConstant.MESSAGE_AGENT_REPLACE_FILE_FAULURE_NOTIFY_ORIGMSG.getMessage(args)); output.setGenerationDate(HinemosTime.getDateInstance().getTime()); output.setMonitorId("SYS"); output.setFacilityId(""); // ??? output.setScopeText(""); // ??? m_sendQueue.put(output); } Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { terminate(); m_log.info("Hinemos agent stopped"); } }); }
From source file:self.philbrown.droidQuery.Ajax.java
protected TaskResponse doInBackground(Void... arg0) { if (this.isCancelled) return null; //if synchronous, block on the background thread until ready. Then call beforeSend, etc, before resuming. if (!beforeSendIsAsync) { try {/*from w w w.j a v a 2 s.co m*/ mutex.acquire(); } catch (InterruptedException e) { Log.w("AjaxTask", "Synchronization Error. Running Task Async"); } final Thread asyncThread = Thread.currentThread(); isLocked = true; mHandler.post(new Runnable() { @Override public void run() { if (options.beforeSend() != null) { if (options.context() != null) options.beforeSend().invoke($.with(options.context()), options); else options.beforeSend().invoke(null, options); } if (options.isAborted()) { cancel(true); return; } if (options.global()) { synchronized (globalTasks) { if (globalTasks.isEmpty()) { $.ajaxStart(); } globalTasks.add(Ajax.this); } $.ajaxSend(); } else { synchronized (localTasks) { localTasks.add(Ajax.this); } } isLocked = false; LockSupport.unpark(asyncThread); } }); if (isLocked) LockSupport.park(); } //here is where to use the mutex //handle cached responses Object cachedResponse = AjaxCache.sharedCache().getCachedResponse(options); //handle ajax caching option if (cachedResponse != null && options.cache()) { Success s = new Success(cachedResponse); s.reason = "cached response"; s.allHeaders = null; return s; } if (connection == null) { try { String type = options.type(); URL url = new URL(options.url()); if (type == null) { type = "GET"; } if (type.equalsIgnoreCase("CUSTOM")) { try { connection = options.customConnection(); } catch (Exception e) { connection = null; } if (connection == null) { Log.w("droidQuery.ajax", "CUSTOM type set, but AjaxOptions.customRequest is invalid. Defaulting to GET."); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); } } else { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(type); if (type.equalsIgnoreCase("POST") || type.equalsIgnoreCase("PUT")) { connection.setDoOutput(true); } } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); Error e = new Error(null); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = 0; e.reason = "Bad Configuration"; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = new Headers(); e.error = error; return e; } } Map<String, Object> args = new HashMap<String, Object>(); args.put("options", options); args.put("request", null); args.put("connection", connection); EventCenter.trigger("ajaxPrefilter", args, null); if (options.headers() != null) { if (options.headers().authorization() != null) { options.headers() .authorization(options.headers().authorization() + " " + options.getEncodedCredentials()); } else if (options.username() != null) { //guessing that authentication is basic options.headers().authorization("Basic " + options.getEncodedCredentials()); } for (Entry<String, String> entry : options.headers().map().entrySet()) { connection.setRequestProperty(entry.getKey(), entry.getValue()); } } if (options.data() != null) { try { OutputStream os = connection.getOutputStream(); os.write(options.data().toString().getBytes()); os.close(); } catch (Throwable t) { Log.w("Ajax", "Could not post data"); } } if (options.timeout() != 0) { connection.setConnectTimeout(options.timeout()); connection.setReadTimeout(options.timeout()); } if (options.trustedCertificate() != null) { Certificate ca = options.trustedCertificate(); String keyStoreType = KeyStore.getDefaultType(); KeyStore keyStore = null; try { keyStore = KeyStore.getInstance(keyStoreType); keyStore.load(null, null); keyStore.setCertificateEntry("ca", ca); } catch (KeyStoreException e) { if (options.debug()) e.printStackTrace(); } catch (NoSuchAlgorithmException e) { if (options.debug()) e.printStackTrace(); } catch (CertificateException e) { if (options.debug()) e.printStackTrace(); } catch (IOException e) { if (options.debug()) e.printStackTrace(); } if (keyStore == null) { Log.w("Ajax", "Could not configure trusted certificate"); } else { try { //Create a TrustManager that trusts the CAs in our KeyStore String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm); tmf.init(keyStore); //Create an SSLContext that uses our TrustManager SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tmf.getTrustManagers(), null); ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } catch (KeyManagementException e) { if (options.debug()) e.printStackTrace(); } catch (NoSuchAlgorithmException e) { if (options.debug()) e.printStackTrace(); } catch (KeyStoreException e) { if (options.debug()) e.printStackTrace(); } } } try { if (options.cookies() != null) { CookieManager cm = new CookieManager(); CookieStore cookies = cm.getCookieStore(); URI uri = URI.create(options.url()); for (Entry<String, String> entry : options.cookies().entrySet()) { HttpCookie cookie = new HttpCookie(entry.getKey(), entry.getValue()); cookies.add(uri, cookie); } connection.setRequestProperty("Cookie", TextUtils.join(",", cookies.getCookies())); } connection.connect(); final int statusCode = connection.getResponseCode(); final String message = connection.getResponseMessage(); if (options.dataFilter() != null) { if (options.context() != null) options.dataFilter().invoke($.with(options.context()), connection, options.dataType()); else options.dataFilter().invoke(null, connection, options.dataType()); } final Function function = options.statusCode().get(statusCode); if (function != null) { mHandler.post(new Runnable() { @Override public void run() { if (options.context() != null) function.invoke($.with(options.context()), statusCode, options.clone()); else function.invoke(null, statusCode, options.clone()); } }); } //handle dataType String dataType = options.dataType(); if (dataType == null) dataType = "text"; if (options.debug()) Log.i("Ajax", "dataType = " + dataType); Object parsedResponse = null; InputStream stream = null; try { if (dataType.equalsIgnoreCase("text") || dataType.equalsIgnoreCase("html")) { if (options.debug()) Log.i("Ajax", "parsing text"); stream = AjaxUtil.getInputStream(connection); parsedResponse = parseText(stream); } else if (dataType.equalsIgnoreCase("xml")) { if (options.debug()) Log.i("Ajax", "parsing xml"); if (options.customXMLParser() != null) { stream = AjaxUtil.getInputStream(connection); if (options.SAXContentHandler() != null) options.customXMLParser().parse(stream, options.SAXContentHandler()); else options.customXMLParser().parse(stream, new DefaultHandler()); parsedResponse = "Response handled by custom SAX parser"; } else if (options.SAXContentHandler() != null) { stream = AjaxUtil.getInputStream(connection); SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setFeature("http://xml.org/sax/features/namespaces", false); factory.setFeature("http://xml.org/sax/features/namespace-prefixes", true); SAXParser parser = factory.newSAXParser(); XMLReader reader = parser.getXMLReader(); reader.setContentHandler(options.SAXContentHandler()); reader.parse(new InputSource(stream)); parsedResponse = "Response handled by custom SAX content handler"; } else { parsedResponse = parseXML(connection); } } else if (dataType.equalsIgnoreCase("json")) { if (options.debug()) Log.i("Ajax", "parsing json"); parsedResponse = parseJSON(connection); } else if (dataType.equalsIgnoreCase("script")) { if (options.debug()) Log.i("Ajax", "parsing script"); parsedResponse = parseScript(connection); } else if (dataType.equalsIgnoreCase("image")) { if (options.debug()) Log.i("Ajax", "parsing image"); stream = AjaxUtil.getInputStream(connection); parsedResponse = parseImage(stream); } else if (dataType.equalsIgnoreCase("raw")) { if (options.debug()) Log.i("Ajax", "parsing raw data"); parsedResponse = parseRawContent(connection); } } catch (ClientProtocolException cpe) { if (options.debug()) cpe.printStackTrace(); Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = statusCode; e.reason = message; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; return e; } catch (Exception ioe) { if (options.debug()) ioe.printStackTrace(); Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = statusCode; e.reason = message; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; return e; } finally { connection.disconnect(); try { if (stream != null) { stream.close(); } } catch (IOException e) { } } if (statusCode >= 300) { //an error occurred Error e = new Error(parsedResponse); Log.e("Ajax Test", parsedResponse.toString()); //AjaxError error = new AjaxError(); //error.request = request; //error.options = options; e.status = e.status; e.reason = e.reason; //error.status = e.status; //error.reason = e.reason; //error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); //e.error = error; if (options.debug()) Log.i("Ajax", "Error " + e.status + ": " + e.reason); return e; } else { //handle ajax ifModified option List<String> lastModifiedHeaders = connection.getHeaderFields().get("last-modified"); if (lastModifiedHeaders.size() >= 1) { try { String h = lastModifiedHeaders.get(0); SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz", Locale.US); Date lastModified = format.parse(h); if (options.ifModified() && lastModified != null) { Date lastModifiedDate; synchronized (lastModifiedUrls) { lastModifiedDate = lastModifiedUrls.get(options.url()); } if (lastModifiedDate != null && lastModifiedDate.compareTo(lastModified) == 0) { //request response has not been modified. //Causes an error instead of a success. Error e = new Error(parsedResponse); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; e.status = e.status; e.reason = e.reason; error.status = e.status; error.reason = e.reason; error.response = e.response; e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); e.error = error; Function func = options.statusCode().get(304); if (func != null) { if (options.context() != null) func.invoke($.with(options.context())); else func.invoke(null); } return e; } else { synchronized (lastModifiedUrls) { lastModifiedUrls.put(options.url(), lastModified); } } } } catch (Throwable t) { Log.e("Ajax", "Could not parse Last-Modified Header", t); } } //Now handle a successful request Success s = new Success(parsedResponse); s.reason = message; s.allHeaders = Headers.createHeaders(connection.getHeaderFields()); return s; } } catch (Throwable t) { if (options.debug()) t.printStackTrace(); if (t instanceof java.net.SocketTimeoutException) { Error e = new Error(null); AjaxError error = new AjaxError(); error.connection = connection; error.options = options; error.response = e.response; e.status = 0; String reason = t.getMessage(); if (reason == null) reason = "Socket Timeout"; e.reason = reason; error.status = e.status; error.reason = e.reason; if (connection != null) e.allHeaders = Headers.createHeaders(connection.getHeaderFields()); else e.allHeaders = new Headers(); e.error = error; return e; } return null; } }
From source file:org.kontalk.client.KontalkConnection.java
@SuppressLint("AllowAllHostnameVerifier") private static void setupSSL(XMPPTCPConnectionConfiguration.Builder builder, boolean direct, PrivateKey privateKey, X509Certificate bridgeCert, boolean acceptAnyCertificate, KeyStore trustStore) { try {// w w w . j a va 2 s. c o m SSLContext ctx = SSLContext.getInstance("TLS"); KeyManager[] km = null; if (privateKey != null && bridgeCert != null) { // in-memory keystore KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType()); keystore.load(null, null); keystore.setKeyEntry("private", privateKey, null, new Certificate[] { bridgeCert }); // key managers KeyManagerFactory kmFactory = KeyManagerFactory .getInstance(KeyManagerFactory.getDefaultAlgorithm()); kmFactory.init(keystore, null); km = kmFactory.getKeyManagers(); // disable PLAIN mechanism if not upgrading from legacy if (!LegacyAuthentication.isUpgrading()) { // blacklist PLAIN mechanism SASLAuthentication.blacklistSASLMechanism("PLAIN"); } } // trust managers TrustManager[] tm; if (acceptAnyCertificate) { tm = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @SuppressLint("TrustAllX509TrustManager") @Override public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException { } @SuppressLint("TrustAllX509TrustManager") @Override public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException { } } }; builder.setHostnameVerifier(new AllowAllHostnameVerifier()); } else { // builtin keystore TrustManagerFactory tmFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmFactory.init(trustStore); tm = tmFactory.getTrustManagers(); } ctx.init(km, tm, null); builder.setCustomSSLContext(ctx); if (direct) builder.setSocketFactory(ctx.getSocketFactory()); // SASL EXTERNAL is already enabled in Smack } catch (Exception e) { Log.w(TAG, "unable to setup SSL connection", e); } }
From source file:me.mneri.rice.Connection.java
public void start() { if (mState != State.CLOSED) return;//from w w w . j av a 2 s . c o m mState = State.STARTED; emit(new Event(START, this)); new Thread(() -> { try { if (mSecure) { SSLContext sslContext = SSLContext.getInstance("TLS"); String algorithm = TrustManagerFactory.getDefaultAlgorithm(); TrustManagerFactory tmFactory = TrustManagerFactory.getInstance(algorithm); tmFactory.init((KeyStore) null); sslContext.init(null, tmFactory.getTrustManagers(), null); SSLSocketFactory sslFactory = sslContext.getSocketFactory(); SSLSocket sslSocket = (SSLSocket) sslFactory.createSocket(mHost, mPort); sslSocket.startHandshake(); mSocket = sslSocket; } else { mSocket = new Socket(mHost, mPort); } mSocket.setSoTimeout(mSoTimeout); mInputThread = new InputThread(mSocket.getInputStream(), mEncoding, new InputThreadObserver()); mInputThread.start(); OutputInterfaceFactory outFactory = OutputInterfaceFactory.instance(); OutputStreamWriter outWriter = new OutputStreamWriter(mSocket.getOutputStream(), mEncoding); mOutputInterface = outFactory.createInterface(outWriter); mState = State.CONNECTED; emit(new Event(CONNECT, this)); cap("LS"); if (!TextUtils.isEmpty(mPass)) pass(mPass); nick(mWantedNick); user(mUser, mLoginMode, "*", mReal); } catch (Exception e) { onDisconnection(); } }).start(); }
From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java
public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException { SSLContext sslContext = null; try {/* ww w.j a va 2s.c o m*/ sslContext = SSLContext.getInstance("TLS"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose); }
From source file:org.globus.myproxy.MyProxy.java
/** * Bootstraps trustroot information from the MyProxy server. * * @exception MyProxyException// w w w . j av a2 s.co m * If an error occurred during the operation. */ public void bootstrapTrust() throws MyProxyException { try { SSLContext sc = SSLContext.getInstance("SSL"); MyTrustManager myTrustManager = new MyTrustManager(); TrustManager[] trustAllCerts = new TrustManager[] { myTrustManager }; sc.init(null, trustAllCerts, new java.security.SecureRandom()); SSLSocketFactory sf = sc.getSocketFactory(); SSLSocket socket = (SSLSocket) sf.createSocket(this.host, this.port); socket.setEnabledProtocols(new String[] { "SSLv3" }); socket.startHandshake(); socket.close(); X509Certificate[] acceptedIssuers = myTrustManager.getAcceptedIssuers(); if (acceptedIssuers == null) { throw new MyProxyException("Failed to determine MyProxy server trust roots in bootstrapTrust."); } for (int idx = 0; idx < acceptedIssuers.length; idx++) { File x509Dir = new File(org.globus.myproxy.MyProxy.getTrustRootPath()); if (!x509Dir.exists()) { StringBuffer newSubject = new StringBuffer(); String[] subjArr = acceptedIssuers[idx].getSubjectDN().getName().split(", "); for (int i = (subjArr.length - 1); i > -1; i--) { newSubject.append("/"); newSubject.append(subjArr[i]); } String subject = newSubject.toString(); File tmpDir = new File(getTrustRootPath() + "-" + System.currentTimeMillis()); if (tmpDir.mkdir() == true) { String hash = opensslHash(acceptedIssuers[idx]); String filename = tmpDir.getPath() + tmpDir.separator + hash + ".0"; FileOutputStream os = new FileOutputStream(new File(filename)); CertificateIOUtil.writeCertificate(os, acceptedIssuers[idx]); os.close(); if (logger.isDebugEnabled()) { logger.debug("wrote trusted certificate to " + filename); } filename = tmpDir.getPath() + tmpDir.separator + hash + ".signing_policy"; os = new FileOutputStream(new File(filename)); Writer wr = new OutputStreamWriter(os, Charset.forName("UTF-8")); wr.write("access_id_CA X509 '"); wr.write(subject); wr.write("'\npos_rights globus CA:sign\ncond_subjects globus \"*\"\n"); wr.flush(); wr.close(); os.close(); if (logger.isDebugEnabled()) { logger.debug("wrote trusted certificate policy to " + filename); } // success. commit the bootstrapped directory. if (tmpDir.renameTo(x509Dir) == true) { if (logger.isDebugEnabled()) { logger.debug("renamed " + tmpDir.getPath() + " to " + x509Dir.getPath()); } } else { throw new MyProxyException( "Unable to rename " + tmpDir.getPath() + " to " + x509Dir.getPath()); } } else { throw new MyProxyException("Cannot create temporary directory: " + tmpDir.getName()); } } } } catch (Exception e) { throw new MyProxyException("MyProxy bootstrapTrust failed.", e); } }
From source file:com.openshift.restclient.ClientBuilder.java
/** * Build a client //ww w. j av a 2s .co m * * @return * @throws KeyManagementException */ public IClient build() { try { TrustManagerFactory trustManagerFactory = initTrustManagerFactory(certificateAlias, certificate, certificateCollection); X509TrustManager trustManager = getCurrentTrustManager(trustManagerFactory); SSLContext sslContext = SSLUtils.getSSLContext(trustManager); ResponseCodeInterceptor responseCodeInterceptor = new ResponseCodeInterceptor(); OpenShiftAuthenticator authenticator = new OpenShiftAuthenticator(); Dispatcher dispatcher = new Dispatcher(); //hiding these for now to since not certain //if we need to really expose them. dispatcher.setMaxRequests(maxRequests); dispatcher.setMaxRequestsPerHost(maxRequestsPerHost); String[] pieces = { this.userAgentPrefix, "openshift-restclient-java", Version.userAgent() }; String userAgent = StringUtils.join(pieces, "/"); OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(responseCodeInterceptor) .addNetworkInterceptor(new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { Request agent = chain.request().newBuilder().header("User-Agent", userAgent).build(); return chain.proceed(agent); } }).authenticator(authenticator).dispatcher(dispatcher).readTimeout(readTimeout, readTimeoutUnit) .writeTimeout(writeTimeout, writeTimeoutUnit).connectTimeout(connectTimeout, connectTimeoutUnit) .sslSocketFactory(sslContext.getSocketFactory(), trustManager); if (!this.sslCertCallbackWithDefaultHostnameVerifier) builder.hostnameVerifier(sslCertificateCallback); if (proxyAuthenticator != null) { builder.proxyAuthenticator(proxyAuthenticator); } OkHttpClient okClient = builder.build(); IResourceFactory factory = defaultIfNull(resourceFactory, new ResourceFactory(null)); AuthorizationContext authContext = new AuthorizationContext(token, userName, password); DefaultClient client = new DefaultClient(new URL(this.baseUrl), okClient, factory, null, authContext); authContext.setClient(client); responseCodeInterceptor.setClient(client); authenticator.setClient(client); authenticator.setOkClient(okClient); return client; } catch (KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) { throw new OpenShiftException(e, "Unable to initialize client"); } }
From source file:org.exoplatform.services.videocall.AuthService.java
public String authenticate(VideoCallModel videoCallModel, String profile_id) { VideoCallService videoCallService = new VideoCallService(); if (videoCallModel == null) { caFile = videoCallService.getPemCertInputStream(); p12File = videoCallService.getP12CertInputStream(); videoCallModel = videoCallService.getVideoCallProfile(); } else {/*w w w . jav a2 s.com*/ caFile = videoCallModel.getPemCert(); p12File = videoCallModel.getP12Cert(); } if (videoCallModel != null) { domain_id = videoCallModel.getDomainId(); clientId = videoCallModel.getAuthId(); clientSecret = videoCallModel.getAuthSecret(); passphrase = videoCallModel.getCustomerCertificatePassphrase(); } String responseContent = null; if (StringUtils.isEmpty(passphrase)) return null; if (caFile == null || p12File == null) return null; try { String userId = ConversationState.getCurrent().getIdentity().getUserId(); SSLContext ctx = SSLContext.getInstance("SSL"); URL url = null; try { StringBuilder urlBuilder = new StringBuilder(); urlBuilder.append(authUrl).append("?client_id=" + clientId).append("&client_secret=" + clientSecret) .append("&uid=weemo" + userId) .append("&identifier_client=" + URLEncoder.encode(domain_id, "UTF-8")) .append("&id_profile=" + URLEncoder.encode(profile_id, "UTF-8")); url = new URL(urlBuilder.toString()); } catch (MalformedURLException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not create valid URL with base", e); } } HttpsURLConnection connection = null; try { connection = (HttpsURLConnection) url.openConnection(); } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not connect", e); } } TrustManager[] trustManagers = getTrustManagers(caFile, passphrase); KeyManager[] keyManagers = getKeyManagers("PKCS12", p12File, passphrase); ctx.init(keyManagers, trustManagers, new SecureRandom()); try { connection.setSSLSocketFactory(ctx.getSocketFactory()); connection.setRequestMethod("GET"); connection.setDoOutput(true); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); } catch (Exception e) { if (LOG.isErrorEnabled()) { LOG.error("Could not configure request for POST", e); } } try { connection.connect(); } catch (IOException e) { if (LOG.isErrorEnabled()) { LOG.error("Could not connect to weemo", e); } } BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sbuilder = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sbuilder.append(line + "\n"); } br.close(); responseContent = sbuilder.toString(); // Set new token key String tokenKey = ""; if (!StringUtils.isEmpty(responseContent)) { JSONObject json = new JSONObject(responseContent); tokenKey = json.get("token").toString(); } else { tokenKey = ""; } videoCallService.setTokenKey(tokenKey); } catch (Exception ex) { LOG.error("Have problem during authenticating process.", ex); videoCallService.setTokenKey(""); } return responseContent; }
From source file:com.cyberway.issue.crawler.fetcher.FetchHTTP.java
public void initialTasks() { super.initialTasks(); this.getController().addCrawlStatusListener(this); configureHttp();// w ww . j a va 2 s .c o m // load cookies from a file if specified in the order file. loadCookies(); // I tried to get the default KeyManagers but doesn't work unless you // point at a physical keystore. Passing null seems to do the right // thing so we'll go w/ that. try { SSLContext context = SSLContext.getInstance("SSL"); context.init(null, new TrustManager[] { new ConfigurableX509TrustManager((String) getAttribute(ATTR_TRUST)) }, null); this.sslfactory = context.getSocketFactory(); } catch (Exception e) { logger.log(Level.WARNING, "Failed configure of ssl context " + e.getMessage(), e); } }