List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
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//from w w w .j av a 2 s. 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.sakaiproject.lessonbuildertool.tool.beans.SimplePageBean.java
public String getTypeOfUrl(String url) { String mimeType = "text/html"; // try to find the mime type of the remote resource // this is only likely to be a problem if someone is pointing to // a url within Sakai. We think in realistic cases those that are // files will be handled as files, so anything that comes where // will be HTML. That's the default if this fails. URLConnection conn = null;/*w ww . j a va 2 s .c om*/ try { conn = new URL(new URL(ServerConfigurationService.getServerUrl()), url).openConnection(); conn.setConnectTimeout(10000); conn.setReadTimeout(10000); // generate cookie based on code in RequestFilter.java //String suffix = System.getProperty("sakai.serverId"); //if (suffix == null || suffix.equals("")) // suffix = "sakai"; //Session s = sessionManager.getCurrentSession(); //conn.setRequestProperty("Cookie", "JSESSIONID=" + s.getId() + "." + suffix); conn.connect(); String t = conn.getContentType(); if (t != null && !t.equals("")) { int i = t.indexOf(";"); if (i >= 0) t = t.substring(0, i); t = t.trim(); mimeType = t; } } catch (Exception e) { log.error("getTypeOfUrl connection error " + e); } finally { if (conn != null) { try { conn.getInputStream().close(); } catch (Exception e) { log.error("getTypeOfUrl unable to close " + e); } } } return mimeType; }
From source file:com.cloud.hypervisor.xen.resource.CitrixResourceBase.java
protected Answer executeProxyLoadScan(final Command cmd, final long proxyVmId, final String proxyVmName, final String proxyManagementIp, final int cmdPort) { String result = null;/*w ww . j a v a 2 s. c om*/ final StringBuffer sb = new StringBuffer(); sb.append("http://").append(proxyManagementIp).append(":" + cmdPort).append("/cmd/getstatus"); boolean success = true; try { final URL url = new URL(sb.toString()); final URLConnection conn = url.openConnection(); // setting TIMEOUTs to avoid possible waiting until death situations conn.setConnectTimeout(5000); conn.setReadTimeout(5000); final InputStream is = conn.getInputStream(); final BufferedReader reader = new BufferedReader(new InputStreamReader(is)); final StringBuilder sb2 = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb2.append(line + "\n"); } result = sb2.toString(); } catch (final IOException e) { success = false; } finally { try { is.close(); } catch (final IOException e) { s_logger.warn("Exception when closing , console proxy address : " + proxyManagementIp); success = false; } } } catch (final IOException e) { s_logger.warn( "Unable to open console proxy command port url, console proxy address : " + proxyManagementIp); success = false; } return new ConsoleProxyLoadAnswer(cmd, proxyVmId, proxyVmName, success, result); }
From source file:com.clark.func.Functions.java
/** * Copies bytes from the URL <code>source</code> to a file * <code>destination</code>. The directories up to <code>destination</code> * will be created if they don't already exist. <code>destination</code> * will be overwritten if it already exists. * // w ww.ja v a2 s . com * @param source * the <code>URL</code> to copy bytes from, must not be * <code>null</code> * @param destination * the non-directory <code>File</code> to write bytes to * (possibly overwriting), must not be <code>null</code> * @param connectionTimeout * the number of milliseconds until this method will timeout if * no connection could be established to the <code>source</code> * @param readTimeout * the number of milliseconds until this method will timeout if * no data could be read from the <code>source</code> * @throws IOException * if <code>source</code> URL cannot be opened * @throws IOException * if <code>destination</code> is a directory * @throws IOException * if <code>destination</code> cannot be written * @throws IOException * if <code>destination</code> needs creating but can't be * @throws IOException * if an IO error occurs during copying * @since Commons IO 2.0 */ public static void copyURLToFile(URL source, File destination, int connectionTimeout, int readTimeout) throws IOException { URLConnection connection = source.openConnection(); connection.setConnectTimeout(connectionTimeout); connection.setReadTimeout(readTimeout); InputStream input = connection.getInputStream(); copyInputStreamToFile(input, destination); }