List of usage examples for javax.net.ssl TrustManagerFactory getDefaultAlgorithm
public static final String getDefaultAlgorithm()
From source file:org.kuali.kra.s2s.service.impl.S2SConnectorServiceBase.java
/** * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client * @param tlsConfig//from www .ja v a2s . co m * @param alias * @param mulitCampusEnabled * @throws S2SException */ protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias, boolean mulitCampusEnabled) throws S2SException { KeyStore keyStore = s2sCertificateReader.getKeyStore(); KeyManagerFactory keyManagerFactory; try { keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); if (alias != null && mulitCampusEnabled) { KeyStore keyStoreAlias; keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType()); Certificate[] certificates = keyStore.getCertificateChain(alias); Key key = keyStore.getKey(alias, s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray()); keyStoreAlias.load(null, null); keyStoreAlias.setKeyEntry(alias, key, s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray(), certificates); keyManagerFactory.init(keyStoreAlias, s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray()); } else { keyManagerFactory.init(keyStore, s2SUtilService.getProperty(s2sCertificateReader.getKeyStorePassword()).toCharArray()); } KeyManager[] km = keyManagerFactory.getKeyManagers(); tlsConfig.setKeyManagers(km); KeyStore trustStore = s2sCertificateReader.getTrustStore(); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); TrustManager[] tm = trustManagerFactory.getTrustManagers(); tlsConfig.setTrustManagers(tm); } catch (NoSuchAlgorithmException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (KeyStoreException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (UnrecoverableKeyException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (CertificateException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } catch (IOException e) { LOG.error(e); throw new S2SException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } }
From source file:org.projectforge.core.ConfigXml.java
private SSLSocketFactory createSSLSocketFactory(final InputStream is, final String passphrase) throws Exception { final KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(is, passphrase.toCharArray()); is.close();/*from w w w. j a v a 2s .co m*/ final TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); final X509TrustManager defaultTrustManager = (X509TrustManager) tmf.getTrustManagers()[0]; final SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { defaultTrustManager }, null); return context.getSocketFactory(); }
From source file:org.kuali.coeus.propdev.impl.s2s.connect.S2SConnectorServiceBase.java
/** * This method is to confgiure KeyStore and Truststore for Grants.Gov webservice client * @param tlsConfig/* w w w .java 2s.co m*/ * @param alias * @param mulitCampusEnabled * @throws S2sCommunicationException */ protected void configureKeyStoreAndTrustStore(TLSClientParameters tlsConfig, String alias, boolean mulitCampusEnabled) throws S2sCommunicationException { KeyStore keyStore = s2sCertificateReader.getKeyStore(); KeyManagerFactory keyManagerFactory; try { keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm()); if (alias != null && mulitCampusEnabled) { KeyStore keyStoreAlias; keyStoreAlias = KeyStore.getInstance(s2sCertificateReader.getJksType()); Certificate[] certificates = keyStore.getCertificateChain(alias); Key key = keyStore.getKey(alias, s2SConfigurationService .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray()); keyStoreAlias.load(null, null); keyStoreAlias.setKeyEntry( alias, key, s2SConfigurationService .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray(), certificates); keyManagerFactory.init(keyStoreAlias, s2SConfigurationService .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray()); } else { keyManagerFactory.init(keyStore, s2SConfigurationService .getValueAsString(s2sCertificateReader.getKeyStorePassword()).toCharArray()); } KeyManager[] km = keyManagerFactory.getKeyManagers(); tlsConfig.setKeyManagers(km); KeyStore trustStore = s2sCertificateReader.getTrustStore(); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); TrustManager[] tm = trustManagerFactory.getTrustManagers(); tlsConfig.setTrustManagers(tm); } catch (NoSuchAlgorithmException | KeyStoreException | UnrecoverableKeyException | CertificateException | IOException e) { LOG.error(e.getMessage(), e); throw new S2sCommunicationException(KeyConstants.ERROR_KEYSTORE_CONFIG, e.getMessage()); } }
From source file:io.fabric8.kubernetes.api.KubernetesFactory.java
private void configureCaCert(WebClient webClient) { try (InputStream pemInputStream = getInputStreamFromDataOrFile(caCertData, caCertFile)) { CertificateFactory certFactory = CertificateFactory.getInstance("X509"); X509Certificate cert = (X509Certificate) certFactory.generateCertificate(pemInputStream); KeyStore trustStore = KeyStore.getInstance("JKS"); trustStore.load(null);/* w ww . ja v a 2s .co m*/ String alias = cert.getSubjectX500Principal().getName(); trustStore.setCertificateEntry(alias, cert); TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(trustStore); HTTPConduit conduit = WebClient.getConfig(webClient).getHttpConduit(); TLSClientParameters params = conduit.getTlsClientParameters(); if (params == null) { params = new TLSClientParameters(); conduit.setTlsClientParameters(params); } TrustManager[] existingTrustManagers = params.getTrustManagers(); TrustManager[] trustManagers; if (existingTrustManagers == null || ArrayUtils.isEmpty(existingTrustManagers)) { trustManagers = trustManagerFactory.getTrustManagers(); } else { trustManagers = (TrustManager[]) ArrayUtils.addAll(existingTrustManagers, trustManagerFactory.getTrustManagers()); } params.setTrustManagers(trustManagers); } catch (Exception e) { log.error("Could not create trust manager for " + caCertFile, e); } }
From source file:com.cisco.oss.foundation.http.netlifx.apache.ApacheNetflixHttpClient.java
protected void configureClient() { clientConfig = new DefaultClientConfigImpl(); clientConfig.loadProperties(getApiName()); setLoadBalancer(loadBalancer);/*from w w w . j a va2s . co m*/ // clientConfig.set(CommonClientConfigKey.NIWSServerListClassName, DiscoveryEnabledNIWSServerList.class.getName()); // clientConfig.set(IClientConfigKey.Keys.DeploymentContextBasedVipAddresses, metadata.getServiceName()); // clientConfig.set(CommonClientConfigKey.NFLoadBalancerRuleClassName, RoundRobinRule.class.getName()); // clientConfig.set(CommonClientConfigKey.NFLoadBalancerPingClassName, NIWSDiscoveryPing.class.getName()); // clientConfig.set(CommonClientConfigKey.VipAddressResolverClassName, SimpleVipAddressResolver.class.getName()); if (DiscoveryManager.getInstance().getDiscoveryClient() == null && startEurekaClient) { EurekaInstanceConfig eurekaInstanceConfig = new MyDataCenterInstanceConfig(getApiName()); EurekaClientConfig eurekaClientConfig = new DefaultEurekaClientConfig(getApiName() + "."); DiscoveryManager.getInstance().initComponent(eurekaInstanceConfig, eurekaClientConfig); } loadBalancer.initWithNiwsConfig(clientConfig); // if (HystrixPlugins.getInstance().getMetricsPublisher() == null) { // HystrixPlugins.getInstance().registerMetricsPublisher(HystrixMetricsPublisherDefault.getInstance()); // } RequestConfig.Builder requestBuilder = RequestConfig.custom(); requestBuilder = requestBuilder.setConnectTimeout(metadata.getConnectTimeout()); requestBuilder = requestBuilder.setSocketTimeout(metadata.getReadTimeout()); requestBuilder = requestBuilder.setStaleConnectionCheckEnabled(metadata.isStaleConnectionCheckEnabled()); RequestConfig requestConfig = requestBuilder.build(); boolean addSslSupport = StringUtils.isNotEmpty(metadata.getKeyStorePath()) && StringUtils.isNotEmpty(metadata.getKeyStorePassword()); boolean addTrustSupport = StringUtils.isNotEmpty(metadata.getTrustStorePath()) && StringUtils.isNotEmpty(metadata.getTrustStorePassword()); autoCloseable = metadata.isAutoCloseable(); autoEncodeUri = metadata.isAutoEncodeUri(); followRedirects = metadata.isFollowRedirects(); HttpClientBuilder httpClientBuilder = HttpClientBuilder.create(); SSLContext sslContext = null; try { String keystoreType = "JKS"; if (addSslSupport && addTrustSupport) { KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()) .loadTrustMaterial(trustStore, null).build(); } else if (addSslSupport) { TrustManagerFactory tmf = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); KeyStore keyStore = KeyStore.getInstance(keystoreType); keyStore.load(new FileInputStream(metadata.getKeyStorePath()), metadata.getKeyStorePassword().toCharArray()); tmf.init(keyStore); sslContext = SSLContexts.custom().useProtocol("SSL") .loadKeyMaterial(keyStore, metadata.getKeyStorePassword().toCharArray()).build(); sslContext.init(null, tmf.getTrustManagers(), null); SSLConnectionSocketFactory sf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier); httpClientBuilder.setSSLSocketFactory(sf); } else if (addTrustSupport) { KeyStore trustStore = KeyStore.getInstance(keystoreType); trustStore.load(new FileInputStream(metadata.getTrustStorePath()), metadata.getTrustStorePassword().toCharArray()); sslContext = SSLContexts.custom().useProtocol("TLS").loadTrustMaterial(trustStore, null).build(); } if (addSslSupport | addTrustSupport) { SSLContext.setDefault(sslContext); httpClientBuilder.setSslcontext(sslContext); } } catch (Exception e) { LOGGER.error("can't set TLS Support. Error is: {}", e, e); } httpClientBuilder.setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()).setDefaultRequestConfig(requestConfig) .evictExpiredConnections().evictIdleConnections(metadata.getIdleTimeout(), TimeUnit.MILLISECONDS) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())); HttpAsyncClientBuilder httpAsyncClientBuilder = HttpAsyncClients.custom(); httpAsyncClientBuilder.setDefaultRequestConfig(requestConfig) .setMaxConnPerRoute(metadata.getMaxConnectionsPerAddress()) .setMaxConnTotal(metadata.getMaxConnectionsTotal()) .setKeepAliveStrategy(new InfraConnectionKeepAliveStrategy(metadata.getIdleTimeout())) .setSSLContext(sslContext); if (metadata.isDisableCookies()) { httpClientBuilder.disableCookieManagement(); httpAsyncClientBuilder.disableCookieManagement(); } if (hostnameVerifier != null) { httpClientBuilder.setSSLHostnameVerifier(hostnameVerifier); httpAsyncClientBuilder.setSSLHostnameVerifier(hostnameVerifier); } if (!followRedirects) { httpClientBuilder.disableRedirectHandling(); } httpClient = httpClientBuilder.build(); httpAsyncClient = httpAsyncClientBuilder.build(); httpAsyncClient.start(); }
From source file:org.hyperic.hq.hqapi1.HQConnection.java
private TrustManagerFactory getTrustManagerFactory(final KeyStore keystore) throws KeyStoreException, IOException { try {//from w ww.j a va 2 s.co m TrustManagerFactory trustManagerFactory = TrustManagerFactory .getInstance(TrustManagerFactory.getDefaultAlgorithm()); trustManagerFactory.init(keystore); return trustManagerFactory; } catch (NoSuchAlgorithmException e) { // no support for algorithm, if this happens we're kind of screwed // we're using the default so it should never happen throw new KeyStoreException(e); } }
From source file:cvut.fel.mobilevoting.murinrad.communications.Connection.java
/** * http://www.coderanch.com/t/207318/sockets/java/do-hold-Java-default-SSL a * getter method for outputting the defauld certificate validator * //from w w w . java 2 s . c o m * @return */ private X509TrustManager getDefaultTrust() { TrustManagerFactory trustManagerFactory = null; try { trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); } catch (NoSuchAlgorithmException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } try { trustManagerFactory.init((KeyStore) null); } catch (KeyStoreException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println("JVM Default Trust Managers:"); for (TrustManager trustManager : trustManagerFactory.getTrustManagers()) { System.out.println(trustManager); if (trustManager instanceof X509TrustManager) { X509TrustManager x509TrustManager = (X509TrustManager) trustManager; return x509TrustManager; } } return null; }
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 ww w .j av a 2s . c o 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.apache.geode.management.internal.cli.commands.ConnectCommand.java
private KeyManager[] getKeyManagers(SSLConfig sslConfig) throws Exception { FileInputStream keyStoreStream = null; KeyManagerFactory keyManagerFactory = null; try {//from w w w .j a v a 2 s .c o m if (StringUtils.isNotBlank(sslConfig.getKeystore())) { KeyStore clientKeys = KeyStore.getInstance(sslConfig.getKeystoreType()); keyStoreStream = new FileInputStream(sslConfig.getKeystore()); clientKeys.load(keyStoreStream, sslConfig.getKeystorePassword().toCharArray()); keyManagerFactory = KeyManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); keyManagerFactory.init(clientKeys, sslConfig.getKeystorePassword().toCharArray()); } } finally { if (keyStoreStream != null) { keyStoreStream.close(); } } return keyManagerFactory != null ? keyManagerFactory.getKeyManagers() : null; }
From source file:net.i2p.util.I2PSSLSocketFactory.java
/** * Loads certs from/*from w w w . j ava 2s .c o m*/ * the ~/.i2p/certificates/ and $I2P/certificates/ directories. */ private static SSLSocketFactory initSSLContext(I2PAppContext context, boolean loadSystemCerts, String relativeCertPath) throws GeneralSecurityException { Log log = context.logManager().getLog(I2PSSLSocketFactory.class); KeyStore ks; if (loadSystemCerts) { ks = KeyStoreUtil.loadSystemKeyStore(); if (ks == null) throw new GeneralSecurityException("Key Store init error"); } else { try { ks = KeyStore.getInstance(KeyStore.getDefaultType()); ks.load(null, "".toCharArray()); } catch (IOException ioe) { throw new GeneralSecurityException("Key Store init error", ioe); } } File dir = new File(context.getConfigDir(), relativeCertPath); int adds = KeyStoreUtil.addCerts(dir, ks); int totalAdds = adds; if (adds > 0) { if (log.shouldLog(Log.INFO)) log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath()); } File dir2 = new File(context.getBaseDir(), relativeCertPath); if (!dir.getAbsolutePath().equals(dir2.getAbsolutePath())) { adds = KeyStoreUtil.addCerts(dir2, ks); totalAdds += adds; if (adds > 0) { if (log.shouldLog(Log.INFO)) log.info("Loaded " + adds + " trusted certificates from " + dir.getAbsolutePath()); } } if (totalAdds > 0 || loadSystemCerts) { if (log.shouldLog(Log.INFO)) log.info("Loaded total of " + totalAdds + " new trusted certificates"); } else { String msg = "No trusted certificates loaded (looked in " + dir.getAbsolutePath() + (dir.getAbsolutePath().equals(dir2.getAbsolutePath()) ? "" : (" and " + dir2.getAbsolutePath())) + ", SSL connections will fail. " + "Copy the cert in " + relativeCertPath + " from the router to the directory."; // don't continue, since we didn't load the system keystore, we have nothing. throw new GeneralSecurityException(msg); } SSLContext sslc = SSLContext.getInstance("TLS"); TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); tmf.init(ks); sslc.init(null, tmf.getTrustManagers(), context.random()); return sslc.getSocketFactory(); }