List of usage examples for javax.net.ssl HostnameVerifier HostnameVerifier
HostnameVerifier
From source file:com.cisco.dvbu.ps.deploytool.services.RegressionManagerUtils.java
/** * /*from w ww. j av a2 s. c o m*/ * also @see com.compositesw.ps.deploytool.dao.RegressionPubTestDAO#executeWs(com.compositesw.ps.deploytool.dao.RegressionPubTestDAO.Item, String, String) */ public static int executeWs(RegressionItem item, String outputFile, CompositeServer cisServerConfig, RegressionTestType regressionConfig, String delimiter, String printOutputType) throws CompositeException { // Set the command and action name String command = "executeWs"; String actionName = "REGRESSION_TEST"; // Check the input parameter values: if (cisServerConfig == null || regressionConfig == null) { throw new CompositeException( "XML Configuration objects are not initialized when trying to run Regression test."); } URLConnection urlConn = null; BufferedReader rd = null; OutputStreamWriter wr = null; int rows = 0; String host = cisServerConfig.getHostname(); int wsPort = cisServerConfig.getPort(); // port in servers.xml defines WS port boolean useHttps = cisServerConfig.isUseHttps(); // Execute the webservice try { // Don't execute if -noop (NO_OPERATION) has been set otherwise execute under normal operation. if (CommonUtils.isExecOperation()) { boolean encrypt = item.encrypt; // Override the encrypt flag when useHttps is set from an overall PDTool over SSL (https) setting. if (useHttps && !encrypt) { encrypt = true; RegressionManagerUtils.printOutputStr(printOutputType, "summary", "The regression input file encrypt=false has been overridden by useHttps=true for path=" + item.path, ""); } String urlString = "http://" + host + ":" + wsPort + item.path; if (encrypt) { urlString = "https://" + host + ":" + (wsPort + 2) + item.path; } RegressionManagerUtils.printOutputStr(printOutputType, "summary", "urlString=" + urlString, ""); URL url = new URL(urlString); urlConn = url.openConnection(); if (encrypt) { // disable hostname verification ((HttpsURLConnection) urlConn).setHostnameVerifier(new HostnameVerifier() { public boolean verify(String urlHostName, SSLSession session) { return true; } }); } // 2014-02-09 (mtinius) - added basic authorization to allow for connections with new users String credentials = cisServerConfig.getUser() + ":" + CommonUtils.decrypt(cisServerConfig.getPassword()); String encoded = Base64EncodeDecode.encodeString(credentials); urlConn.setRequestProperty("Authorization", "Basic " + encoded); urlConn.setRequestProperty("SOAPAction", item.action); urlConn.setRequestProperty("Content-Type", item.contentType); urlConn.setDoOutput(true); wr = new OutputStreamWriter(urlConn.getOutputStream()); wr.write(item.input); wr.flush(); // Get the response rd = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = rd.readLine()) != null) { rows++; buf.append(line); if (outputFile != null) CommonUtils.appendContentToFile(outputFile, line); } line = buf.toString(); RegressionManagerUtils.printOutputStr(printOutputType, "results", line, ""); if (line.indexOf("<fault") >= 0 || line.indexOf(":fault") >= 0) { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } throw new IllegalStateException("Fault encountered."); } if (line.trim().length() == 0) { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } throw new IllegalStateException("No response document."); } urlConn.getInputStream().close(); // urlConn.getOutputStream().flush(); wr.close(); rd.close(); RegressionManagerUtils.printOutputStr(printOutputType, "results", "\nCompleted executeWs()", ""); } else { logger.info("\n\nWARNING - NO_OPERATION: COMMAND [" + command + "], ACTION [" + actionName + "] WAS NOT PERFORMED.\n"); } return rows; } catch (IOException e) { try { HttpURLConnection httpConn = (HttpURLConnection) urlConn; BufferedReader brd = new BufferedReader(new InputStreamReader(httpConn.getErrorStream())); String line; StringBuffer buf = new StringBuffer(); while ((line = brd.readLine()) != null) { buf.append(line + "\n"); } brd.close(); String error = buf.toString(); throw new ApplicationException("executeWs(): " + error, e); } catch (Exception err) { String error = e.getMessage() + "\n" + "DETAILED_MESSAGE=[" + err.getMessage() + "]"; //debug: System.out.println("*************** ERROR ENCOUNTERED IN executeWs THREAD FOR TYPE:webservice *****************"); throw new ApplicationException("executeWs(): " + error, err); } } finally { try { if (rd != null) { rd.close(); } if (wr != null) { wr.close(); } } catch (Exception e) { rd = null; wr = null; throw new CompositeException( "executeWs(): unable to close BufferedReader (rd) and OutputStreamWriter (wr): " + e.getMessage()); } } }
From source file:org.openymsg.network.Session.java
private String[] yahooAuth16Stage1(final String seed) throws LoginRefusedException, IOException, NoSuchAlgorithmException { String authLink = "https://" + this.yahooLoginHost + "/config/pwtoken_get?src=ymsgr&ts=&login=" + this.loginID.getId() + "&passwd=" + URLEncoder.encode(this.password, "UTF-8") + "&chal=" + URLEncoder.encode(seed, "UTF-8"); URL u = new URL(authLink); URLConnection uc = u.openConnection(); uc.setConnectTimeout(LOGIN_HTTP_TIMEOUT); if (uc instanceof HttpsURLConnection) { HttpsURLConnection httpUc = (HttpsURLConnection) uc; // used to simulate failures // if (triesBeforeFailure++ % 3 == 0) { // throw new SocketException("Test failure"); // } if (!this.yahooLoginHost.equalsIgnoreCase(LOGIN_YAHOO_COM)) httpUc.setHostnameVerifier(new HostnameVerifier() { @Override/*ww w. j a v a 2s . c o m*/ public boolean verify(final String hostname, final SSLSession session) { Principal principal = null; try { principal = session.getPeerPrincipal(); } catch (SSLPeerUnverifiedException e) { } String localName = "no set"; if (principal != null) localName = principal.getName(); log.debug("Hostname verify: " + hostname + "localName: " + localName); return true; } }); int responseCode = httpUc.getResponseCode(); this.setSessionStatus(SessionState.STAGE1); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = uc.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int read = -1; byte[] buff = new byte[256]; while ((read = in.read(buff)) != -1) out.write(buff, 0, read); in.close(); StringTokenizer toks = new StringTokenizer(out.toString(), "\r\n"); if (toks.countTokens() <= 0) // errrorrrr throw new LoginRefusedException( "Login Failed, wrong response in stage 1:" + httpUc.getResponseMessage()); int responseNo = -1; try { responseNo = Integer.valueOf(toks.nextToken()); } catch (NumberFormatException e) { throw new LoginRefusedException( "Login Failed, wrong response in stage 1:" + httpUc.getResponseMessage()); } if (responseNo != 0 || !toks.hasMoreTokens()) switch (responseNo) { case 1235: throw new LoginRefusedException("Login Failed, Invalid username", AuthenticationState.BADUSERNAME); case 1212: throw new LoginRefusedException("Login Failed, Wrong password", AuthenticationState.BAD); case 1213: throw new LoginRefusedException("Login locked: Too many failed login attempts", AuthenticationState.LOCKED); case 1236: throw new LoginRefusedException("Login locked", AuthenticationState.LOCKED); case 100: throw new LoginRefusedException("Username or password missing", AuthenticationState.BAD); default: throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD); } String ymsgr = toks.nextToken(); if (ymsgr.indexOf("ymsgr=") == -1 && toks.hasMoreTokens()) ymsgr = toks.nextToken(); ymsgr = ymsgr.replaceAll("ymsgr=", ""); return yahooAuth16Stage2(ymsgr, seed); } else { log.error("Failed opening login url: " + authLink + " return code: " + responseCode); throw new LoginRefusedException( "Login Failed, Login url: " + authLink + " return code: " + responseCode); } } else { Class<? extends URLConnection> ucType = null; if (uc != null) ucType = uc.getClass(); log.error("Failed opening login url: " + authLink + " returns: " + ucType); throw new LoginRefusedException("Login Failed, Unable to submit login url"); } //throw new LoginRefusedException("Login Failed, unable to retrieve stage 1 url"); }
From source file:org.openymsg.network.Session.java
private String[] yahooAuth16Stage2(final String token, final String seed) throws LoginRefusedException, IOException, NoSuchAlgorithmException { String loginLink = "https://" + this.yahooLoginHost + "/config/pwtoken_login?src=ymsgr&ts=&token=" + token; URL u = new URL(loginLink); URLConnection uc = u.openConnection(); uc.setConnectTimeout(LOGIN_HTTP_TIMEOUT); if (uc instanceof HttpsURLConnection) { trustEveryone();/*from w w w . j a v a 2 s.c o m*/ HttpsURLConnection httpUc = (HttpsURLConnection) uc; if (!this.yahooLoginHost.equalsIgnoreCase(LOGIN_YAHOO_COM)) httpUc.setHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(final String hostname, final SSLSession session) { return true; } }); int responseCode = httpUc.getResponseCode(); this.setSessionStatus(SessionState.STAGE2); if (responseCode == HttpURLConnection.HTTP_OK) { InputStream in = uc.getInputStream(); ByteArrayOutputStream out = new ByteArrayOutputStream(); int read = -1; byte[] buff = new byte[256]; while ((read = in.read(buff)) != -1) out.write(buff, 0, read); int responseNo = -1; String crumb = null; String cookieY = null; String cookieT = null; StringTokenizer toks = new StringTokenizer(out.toString(), "\r\n"); if (toks.countTokens() <= 0) // errrorrrr throw new LoginRefusedException( "Login Failed, wrong response in stage 2:" + httpUc.getResponseMessage()); try { responseNo = Integer.valueOf(toks.nextToken()); } catch (NumberFormatException e) { throw new LoginRefusedException( "Login Failed, wrong response in stage 2:" + httpUc.getResponseMessage()); } if (responseNo != 0 || !toks.hasMoreTokens()) throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD); while (toks.hasMoreTokens()) { String t = toks.nextToken(); if (t.startsWith("crumb=")) crumb = t.replaceAll("crumb=", ""); else if (t.startsWith("Y=")) cookieY = t.replaceAll("Y=", ""); else if (t.startsWith("T=")) cookieT = t.replaceAll("T=", ""); } if (crumb == null || cookieT == null || cookieY == null) throw new LoginRefusedException("Login Failed, Unkown error", AuthenticationState.BAD); // Iterator<String> iter = // ((HttpURLConnection) uc).getHeaderFields().get("Set-Cookie").iterator(); // while (iter.hasNext()) // { // String string = iter.next(); // System.out.println("\t" + string); // } this.cookieY = cookieY; this.cookieT = cookieT; return yahooAuth16Stage3(crumb + seed, cookieY, cookieT); } } throw new LoginRefusedException("Login Failed, unable to retrieve stage 2 url"); }
From source file:com.photon.phresco.framework.commons.FrameworkUtil.java
public static int getHttpsResponse(String url) throws PhrescoException { URL httpsUrl;/*from ww w. j a v a2s. co m*/ try { SSLContext ssl_ctx = SSLContext.getInstance("SSL"); TrustManager[] trust_mgr = get_trust_mgr(); ssl_ctx.init(null, trust_mgr, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(ssl_ctx.getSocketFactory()); httpsUrl = new URL(url); HttpsURLConnection con = (HttpsURLConnection) httpsUrl.openConnection(); con.setHostnameVerifier(new HostnameVerifier() { // Guard against "bad hostname" errors during handshake. public boolean verify(String host, SSLSession sess) { return true; } }); return con.getResponseCode(); } catch (MalformedURLException e) { throw new PhrescoException(e); } catch (IOException e) { throw new PhrescoException(e); } catch (NoSuchAlgorithmException e) { throw new PhrescoException(e); } catch (KeyManagementException e) { throw new PhrescoException(e); } }
From source file:org.openymsg.network.Session.java
private void trustEveryone() { try {/*from w ww. j ava2 s .com*/ HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() { @Override public boolean verify(final String hostname, final SSLSession session) { return true; } }); SSLContext context = SSLContext.getInstance("TLS"); context.init(null, new X509TrustManager[] { new X509TrustManager() { @Override public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } @Override public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { } @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }, new SecureRandom()); HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory()); } catch (Exception e) { // should never happen e.printStackTrace(); } }