List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier
HostnameVerifier
From source file:io.hops.hopsworks.common.util.WebCommunication.java
private Client createClient() throws NoSuchAlgorithmException, KeyManagementException { if (DISABLE_CERTIFICATE_VALIDATION) { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }/*w ww . j a v a 2s .c o m*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Ignore differences between given hostname and certificate hostname HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String hostAddress, SSLSession session) { return true; } }; // Install the all-trusting trust manager SSLContext sc = SSLContext.getInstance("TLSv1.2"); sc.init(null, trustAllCerts, new SecureRandom()); ClientBuilder clientBuilder = ClientBuilder.newBuilder().hostnameVerifier(hv).sslContext(sc); return clientBuilder.build(); } else { return ClientBuilder.newClient(); } }
From source file:com.clustercontrol.agent.Agent.java
/** * /*from w w w .j av a 2 s. 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:org.jenkinsci.plugins.codefresh.CFApi.java
private void secureContext(boolean selfSignedCert) { this.https = true; trustAllCerts = new TrustManager[] { new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return null; }/* w ww.j ava2 s. co m*/ public void checkClientTrusted(X509Certificate[] certs, String authType) { } public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { SSLContext sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); this.sf = sc.getSocketFactory(); HttpsURLConnection.setDefaultSSLSocketFactory(this.sf); } catch (Exception e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } if (selfSignedCert) { HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession sslSession) { return true; } }); } }
From source file:org.eclipse.emf.emfstore.internal.client.model.connectionmanager.KeyStoreManager.java
/** * Returns a SSL Context. This is need for encryption, used by the * SSLSocketFactory./*from w w w. ja va2s. c o m*/ * * @return SSL Context * @throws ESCertificateException * in case of failure retrieving the context */ public SSLContext getSSLContext() throws ESCertificateException { try { loadKeyStore(); final KeyManagerFactory managerFactory = KeyManagerFactory.getInstance("SunX509"); //$NON-NLS-1$ managerFactory.init(keyStore, KEYSTOREPASSWORD.toCharArray()); final TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance("SunX509"); //$NON-NLS-1$ trustManagerFactory.init(keyStore); final SSLContext sslContext = SSLContext.getInstance("TLS"); //$NON-NLS-1$ sslContext.init(managerFactory.getKeyManagers(), trustManagerFactory.getTrustManagers(), null); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); return sslContext; } catch (final NoSuchAlgorithmException e) { throw new ESCertificateException(Messages.KeyStoreManager_29, e); } catch (final UnrecoverableKeyException e) { throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$ } catch (final KeyStoreException e) { throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$ } catch (final KeyManagementException e) { throw new ESCertificateException("Loading certificate failed!", e); //$NON-NLS-1$ } }
From source file:com.arm.connector.bridge.transport.HttpTransport.java
@SuppressWarnings("empty-statement") private String doHTTP(String verb, String url_str, String username, String password, String data, String content_type, String auth_domain, boolean doInput, boolean doOutput, boolean doSSL, boolean use_api_token, String api_token) { String result = ""; String line = ""; URLConnection connection = null; SSLContext sc = null;/*from w w w. j a v a2 s.c om*/ try { URL url = new URL(url_str); // Http Connection and verb if (doSSL) { // Create a trust manager that does not validate certificate chains TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() { @Override public X509Certificate[] getAcceptedIssuers() { return null; } @Override public void checkClientTrusted(X509Certificate[] certs, String authType) { } @Override public void checkServerTrusted(X509Certificate[] certs, String authType) { } } }; // Install the all-trusting trust manager try { sc = SSLContext.getInstance("TLS"); sc.init(null, trustAllCerts, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } catch (NoSuchAlgorithmException | KeyManagementException e) { // do nothing ; } // open the SSL connction connection = (HttpsURLConnection) (url.openConnection()); ((HttpsURLConnection) connection).setRequestMethod(verb); ((HttpsURLConnection) connection).setSSLSocketFactory(sc.getSocketFactory()); ((HttpsURLConnection) connection).setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(String hostname, SSLSession session) { return true; } }); } else { connection = (HttpURLConnection) (url.openConnection()); ((HttpURLConnection) connection).setRequestMethod(verb); } connection.setDoInput(doInput); if (doOutput && data != null && data.length() > 0) { connection.setDoOutput(doOutput); } else { connection.setDoOutput(false); } // enable basic auth if requested if (use_api_token == false && username != null && username.length() > 0 && password != null && password.length() > 0) { String encoding = Base64.encodeBase64String((username + ":" + password).getBytes()); connection.setRequestProperty("Authorization", this.m_basic_auth_qualifier + " " + encoding); //this.errorLogger().info("Basic Authorization: " + username + ":" + password + ": " + encoding); } // enable ApiTokenAuth auth if requested if (use_api_token == true && api_token != null && api_token.length() > 0) { // use qualification for the authorization header... connection.setRequestProperty("Authorization", this.m_auth_qualifier + " " + api_token); //this.errorLogger().info("ApiTokenAuth Authorization: " + api_token); // Always reset to the established default this.resetAuthorizationQualifier(); } // ETag support if requested if (this.m_etag_value != null && this.m_etag_value.length() > 0) { // set the ETag header value connection.setRequestProperty("ETag", this.m_etag_value); //this.errorLogger().info("ETag Value: " + this.m_etag_value); // Always reset to the established default this.resetETagValue(); } // If-Match support if requested if (this.m_if_match_header_value != null && this.m_if_match_header_value.length() > 0) { // set the If-Match header value connection.setRequestProperty("If-Match", this.m_if_match_header_value); //this.errorLogger().info("If-Match Value: " + this.m_if_match_header_value); // Always reset to the established default this.resetIfMatchValue(); } // specify content type if requested if (content_type != null && content_type.length() > 0) { connection.setRequestProperty("Content-Type", content_type); connection.setRequestProperty("Accept", "*/*"); } // add Connection: keep-alive (does not work...) //connection.setRequestProperty("Connection", "keep-alive"); // special gorp for HTTP DELETE if (verb != null && verb.equalsIgnoreCase("delete")) { connection.setRequestProperty("Access-Control-Allow-Methods", "OPTIONS, DELETE"); } // specify domain if requested if (auth_domain != null && auth_domain.length() > 0) { connection.setRequestProperty("Domain", auth_domain); } // DEBUG dump the headers //if (doSSL) // this.errorLogger().info("HTTP: Headers: " + ((HttpsURLConnection)connection).getRequestProperties()); //else // this.errorLogger().info("HTTP: Headers: " + ((HttpURLConnection)connection).getRequestProperties()); // specify data if requested - assumes it properly escaped if necessary if (doOutput && data != null && data.length() > 0) { try (OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream())) { out.write(data); } } // setup the output if requested if (doInput) { try { try (InputStream content = (InputStream) connection.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(content))) { while ((line = in.readLine()) != null) { result += line; } } } catch (java.io.FileNotFoundException ex) { this.errorLogger().info("HTTP(" + verb + ") empty response (OK)."); result = ""; } } else { // no result expected result = ""; } // save off the HTTP response code... if (doSSL) this.saveResponseCode(((HttpsURLConnection) connection).getResponseCode()); else this.saveResponseCode(((HttpURLConnection) connection).getResponseCode()); // DEBUG //if (doSSL) // this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpsURLConnection)connection).getResponseCode()); //else // this.errorLogger().info("HTTP(" + verb +") URL: " + url_str + " Data: " + data + " Response code: " + ((HttpURLConnection)connection).getResponseCode()); } catch (IOException ex) { this.errorLogger().warning("Caught Exception in doHTTP(" + verb + "): " + ex.getMessage()); result = null; } // return the result return result; }
From source file:org.dcm4chee.xds2.src.tool.pnrsnd.PnRSnd.java
private void configTLS() { final HostnameVerifier origHostnameVerifier = HttpsURLConnection.getDefaultHostnameVerifier(); final String allowedUrlHost = props.getProperty("allowedUrlHost"); HostnameVerifier hv = new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { if (!origHostnameVerifier.verify(urlHostName, session)) { if (isAllowedUrlHost(urlHostName)) { log.warn("Warning: URL Host: " + urlHostName + " vs. " + session.getPeerHost()); } else { return false; }//w w w. j a va2s. c o m } return true; } private boolean isAllowedUrlHost(String urlHostName) { if (allowedUrlHost == null || "CERT".equals(allowedUrlHost)) return false; if (allowedUrlHost.equals("*")) return true; return allowedUrlHost.equals(urlHostName); } }; HttpsURLConnection.setDefaultHostnameVerifier(hv); }
From source file:it.jnrpe.plugin.CheckHttp.java
private void checkCertificateExpiryDate(URL url, List<Metric> metrics) throws Exception { SSLContext ctx = SSLContext.getInstance("TLS"); ctx.init(new KeyManager[0], new TrustManager[] { new DefaultTrustManager() }, new SecureRandom()); SSLContext.setDefault(ctx);/*from w w w . j ava 2 s. c o m*/ HttpsURLConnection conn = (HttpsURLConnection) url.openConnection(); conn.setHostnameVerifier(new HostnameVerifier() { public boolean verify(final String arg0, final SSLSession arg1) { return true; } }); List<Date> expiryDates = new ArrayList<Date>(); conn.getResponseCode(); Certificate[] certs = conn.getServerCertificates(); for (Certificate cert : certs) { X509Certificate x509 = (X509Certificate) cert; Date expiry = x509.getNotAfter(); expiryDates.add(expiry); } conn.disconnect(); Date today = new Date(); for (Date date : expiryDates) { int diffInDays = (int) ((date.getTime() - today.getTime()) / (1000 * 60 * 60 * 24)); metrics.add(new Metric("certificate", "", new BigDecimal(diffInDays), null, null)); } }
From source file:com.dh.perfectoffer.event.framework.net.network.NetworkConnectionImpl.java
private static HostnameVerifier getAllHostsValidVerifier() { if (sAllHostsValidVerifier == null) { sAllHostsValidVerifier = new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; }/*from ww w .jav a 2 s. c o m*/ }; } return sAllHostsValidVerifier; }
From source file:busradar.madison.StopDialog.java
@Override public void show() { new Thread() { @Override//w ww .j a va 2s.c o m public void run() { for (final RouteURL r : routes) { G.activity.runOnUiThread(new Runnable() { public void run() { cur_loading_text .setText(String.format("Loading route %s...", G.route_points[r.route].name)); } }); final ArrayList<RouteTime> curtimes = new ArrayList<RouteTime>(); try { System.err.printf("BusRadar URL %s\n", TRANSITTRACKER_URL + r.url); URL url = new URL(TRANSITTRACKER_URL + r.url); URLConnection url_conn = url.openConnection(); if (url_conn instanceof HttpsURLConnection) { ((HttpsURLConnection) url_conn).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String hostname, SSLSession session) { return true; } }); } InputStream is = url_conn.getInputStream(); Scanner scan = new Scanner(is, "UTF-8"); //String outstr_cur = "Route " + r.route + "\n"; if (scan.findWithinHorizon(num_vehicles_re, 0) != null) { while (scan.findWithinHorizon(time_re, 0) != null) { RouteTime time = new RouteTime(); time.route = r.route; time.time = scan.match().group(1).replace(".", ""); time.dir = scan.match().group(2); //time.date = DateFormat.getTimeInstance(DateFormat.SHORT).parse(time.time); SimpleDateFormat f = new SimpleDateFormat("h:mm aa", Locale.US); time.date = f.parse(time.time); r.status = RouteURL.DONE; //outstr_cur += String.format("%s to %s\n", time.time, time.dir); curtimes.add(time); } while (scan.findWithinHorizon(time_re_backup, 0) != null) { RouteTime time = new RouteTime(); time.route = r.route; time.time = scan.match().group(1).replace(".", ""); //time.dir = scan.match().group(2); //time.date = DateFormat.getTimeInstance(DateFormat.SHORT).parse(time.time); SimpleDateFormat f = new SimpleDateFormat("h:mm aa", Locale.US); time.date = f.parse(time.time); r.status = RouteURL.DONE; //outstr_cur += String.format("%s to %s\n", time.time, time.dir); curtimes.add(time); } } // else if (scan.findWithinHorizon(no_busses_re, 0) != null) { // r.status = RouteURL.NO_MORE_TODAY; // } // else if (scan.findWithinHorizon(no_timepoints_re, 0) != null) { // r.status = RouteURL.NO_TIMEPOINTS; // } // else { // r.status = RouteURL.ERROR; // System.out.printf("BusRadar: Could not get stop info for %s\n", r.url); // // throw new Exception("Error parsing TransitTracker webpage."); // } else { r.status = RouteURL.NO_STOPS_UNKONWN; } //r.text = outstr_cur; G.activity.runOnUiThread(new Runnable() { public void run() { times.addAll(curtimes); StopDialog.this.update_times(); } }); } // catch (final IOException ioe) { // log_problem(ioe); // G.activity.runOnUiThread(new Runnable() { // public void run() { // final Context ctx = StopDialog.this.getContext(); // // StopDialog.this.setContentView(new RelativeLayout(ctx) {{ // addView(new TextView(ctx) {{ // setText(Html.fromHtml("Error downloading data. Is the data connection enabled?"+ // "<p>Report problems to <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a><p>"+ioe)); // setPadding(5, 5, 5, 5); // this.setMovementMethod(LinkMovementMethod.getInstance()); // }}, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)); // }}); // } // }); // return; // } catch (Exception e) { log_problem(e); String custom_msg = ""; final String turl = TRANSITTRACKER_URL + r.url; if ((e instanceof SocketException) || (e instanceof UnknownHostException)) { // data connection doesn't work custom_msg = "Error downloading data. Is the data connection enabled?" + "<p>Report problems to <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a><p>" + TextUtils.htmlEncode(e.toString()); } else { String rurl = String.format( "http://www.cityofmadison.com/metro/BusStopDepartures/StopID/%04d.pdf", stopid); custom_msg = "Trouble retrieving real-time arrival estimates from <a href='" + turl + "'>this</a> TransitTracker webpage, which is displayed below. " + "Meanwhile, try PDF timetable <a href='" + rurl + "'>here</a>. " + "Contact us at <a href='mailto:support@busradarapp.com'>support@busradarapp.com</a> to report the problem.<p>" + TextUtils.htmlEncode(e.toString()); } final String msg = custom_msg; G.activity.runOnUiThread(new Runnable() { public void run() { final Context ctx = StopDialog.this.getContext(); StopDialog.this.setContentView(new RelativeLayout(ctx) { { addView(new TextView(ctx) { { setId(1); setText(Html.fromHtml(msg)); setPadding(5, 5, 5, 5); this.setMovementMethod(LinkMovementMethod.getInstance()); } }, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT)); addView(new WebView(ctx) { { setWebViewClient(new WebViewClient()); loadUrl(turl); } }, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT) { { addRule(RelativeLayout.BELOW, 1); } }); } }); } }); return; } } G.activity.runOnUiThread(new Runnable() { public void run() { cur_loading_text.setText(""); } }); } }.start(); super.show(); }
From source file:hudson.cli.CLI.java
public static int _main(String[] _args) throws Exception { List<String> args = Arrays.asList(_args); PrivateKeyProvider provider = new PrivateKeyProvider(); boolean sshAuthRequestedExplicitly = false; String httpProxy = null;//w ww .j a v a 2 s. c o m String url = System.getenv("JENKINS_URL"); if (url == null) url = System.getenv("HUDSON_URL"); boolean tryLoadPKey = true; Mode mode = null; String user = null; String auth = null; String userIdEnv = System.getenv("JENKINS_USER_ID"); String tokenEnv = System.getenv("JENKINS_API_TOKEN"); boolean strictHostKey = false; while (!args.isEmpty()) { String head = args.get(0); if (head.equals("-version")) { System.out.println("Version: " + computeVersion()); return 0; } if (head.equals("-http")) { if (mode != null) { printUsage("-http clashes with previously defined mode " + mode); return -1; } mode = Mode.HTTP; args = args.subList(1, args.size()); continue; } if (head.equals("-ssh")) { if (mode != null) { printUsage("-ssh clashes with previously defined mode " + mode); return -1; } mode = Mode.SSH; args = args.subList(1, args.size()); continue; } if (head.equals("-remoting")) { if (mode != null) { printUsage("-remoting clashes with previously defined mode " + mode); return -1; } mode = Mode.REMOTING; args = args.subList(1, args.size()); continue; } if (head.equals("-s") && args.size() >= 2) { url = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-noCertificateCheck")) { LOGGER.info("Skipping HTTPS certificate checks altogether. Note that this is not secure at all."); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new TrustManager[] { new NoCheckTrustManager() }, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); // bypass host name check, too. HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { public boolean verify(String s, SSLSession sslSession) { return true; } }); args = args.subList(1, args.size()); continue; } if (head.equals("-noKeyAuth")) { tryLoadPKey = false; args = args.subList(1, args.size()); continue; } if (head.equals("-i") && args.size() >= 2) { File f = new File(args.get(1)); if (!f.exists()) { printUsage(Messages.CLI_NoSuchFileExists(f)); return -1; } provider.readFrom(f); args = args.subList(2, args.size()); sshAuthRequestedExplicitly = true; continue; } if (head.equals("-strictHostKey")) { strictHostKey = true; args = args.subList(1, args.size()); continue; } if (head.equals("-user") && args.size() >= 2) { user = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-auth") && args.size() >= 2) { auth = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-p") && args.size() >= 2) { httpProxy = args.get(1); args = args.subList(2, args.size()); continue; } if (head.equals("-logger") && args.size() >= 2) { Level level = parse(args.get(1)); for (Handler h : Logger.getLogger("").getHandlers()) { h.setLevel(level); } for (Logger logger : new Logger[] { LOGGER, FullDuplexHttpStream.LOGGER, PlainCLIProtocol.LOGGER, Logger.getLogger("org.apache.sshd") }) { // perhaps also Channel logger.setLevel(level); } args = args.subList(2, args.size()); continue; } break; } if (url == null) { printUsage(Messages.CLI_NoURL()); return -1; } if (auth == null) { // -auth option not set if (StringUtils.isNotBlank(userIdEnv) && StringUtils.isNotBlank(tokenEnv)) { auth = StringUtils.defaultString(userIdEnv).concat(":").concat(StringUtils.defaultString(tokenEnv)); } else if (StringUtils.isNotBlank(userIdEnv) || StringUtils.isNotBlank(tokenEnv)) { printUsage(Messages.CLI_BadAuth()); return -1; } // Otherwise, none credentials were set } if (!url.endsWith("/")) { url += '/'; } if (args.isEmpty()) args = Arrays.asList("help"); // default to help if (tryLoadPKey && !provider.hasKeys()) provider.readFromDefaultLocations(); if (mode == null) { mode = Mode.HTTP; } LOGGER.log(FINE, "using connection mode {0}", mode); if (user != null && auth != null) { LOGGER.warning("-user and -auth are mutually exclusive"); } if (mode == Mode.SSH) { if (user == null) { // TODO SshCliAuthenticator already autodetects the user based on public key; why cannot AsynchronousCommand.getCurrentUser do the same? LOGGER.warning("-user required when using -ssh"); return -1; } return SSHCLI.sshConnection(url, user, args, provider, strictHostKey); } if (strictHostKey) { LOGGER.warning("-strictHostKey meaningful only with -ssh"); } if (user != null) { LOGGER.warning("Warning: -user ignored unless using -ssh"); } CLIConnectionFactory factory = new CLIConnectionFactory().url(url).httpsProxyTunnel(httpProxy); String userInfo = new URL(url).getUserInfo(); if (userInfo != null) { factory = factory.basicAuth(userInfo); } else if (auth != null) { factory = factory.basicAuth( auth.startsWith("@") ? FileUtils.readFileToString(new File(auth.substring(1))).trim() : auth); } if (mode == Mode.HTTP) { return plainHttpConnection(url, args, factory); } CLI cli = factory.connect(); try { if (provider.hasKeys()) { try { // TODO: server verification cli.authenticate(provider.getKeys()); } catch (IllegalStateException e) { if (sshAuthRequestedExplicitly) { LOGGER.warning("The server doesn't support public key authentication"); return -1; } } catch (UnsupportedOperationException e) { if (sshAuthRequestedExplicitly) { LOGGER.warning("The server doesn't support public key authentication"); return -1; } } catch (GeneralSecurityException e) { if (sshAuthRequestedExplicitly) { LOGGER.log(WARNING, null, e); return -1; } LOGGER.warning("Failed to authenticate with your SSH keys. Proceeding as anonymous"); LOGGER.log(FINE, null, e); } } // execute the command // Arrays.asList is not serializable --- see 6835580 args = new ArrayList<String>(args); return cli.execute(args, System.in, System.out, System.err); } finally { cli.close(); } }