List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:org.apache.hadoop.mapreduce.task.reduce.Fetcher.java
/** * The connection establishment is attempted multiple times and is given up * only on the last failure. Instead of connecting with a timeout of * X, we try connecting with a timeout of x < X but multiple times. *//*www .ja v a2 s . c o m*/ private void connect(URLConnection connection, int connectionTimeout) throws IOException { int unit = 0; if (connectionTimeout < 0) { throw new IOException("Invalid timeout " + "[timeout = " + connectionTimeout + " ms]"); } else if (connectionTimeout > 0) { unit = Math.min(UNIT_CONNECT_TIMEOUT, connectionTimeout); } long startTime = Time.monotonicNow(); long lastTime = startTime; int attempts = 0; // set the connect timeout to the unit-connect-timeout connection.setConnectTimeout(unit); while (true) { try { attempts++; connection.connect(); break; } catch (IOException ioe) { long currentTime = Time.monotonicNow(); long retryTime = currentTime - startTime; long leftTime = connectionTimeout - retryTime; long timeSinceLastIteration = currentTime - lastTime; // throw an exception if we have waited for timeout amount of time // note that the updated value if timeout is used here if (leftTime <= 0) { int retryTimeInSeconds = (int) retryTime / 1000; LOG.error("Connection retry failed with " + attempts + " attempts in " + retryTimeInSeconds + " seconds"); throw ioe; } // reset the connect timeout for the last try if (leftTime < unit) { unit = (int) leftTime; // reset the connect time out for the final connect connection.setConnectTimeout(unit); } if (timeSinceLastIteration < unit) { try { // sleep the left time of unit sleep(unit - timeSinceLastIteration); } catch (InterruptedException e) { LOG.warn("Sleep in connection retry get interrupted."); if (stopped) { return; } } } // update the total remaining connect-timeout lastTime = Time.monotonicNow(); } } }
From source file:org.sunnycode.zkws.socketio.impl.IOConnection.java
/** * Handshake.//from w ww.j a v a 2 s . c o m * */ private void handshake() { URL url; String response; URLConnection connection; try { setState(STATE_HANDSHAKE); url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1); connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(connectTimeout); /* Setting the request headers */ for (Entry<Object, Object> entry : headers.entrySet()) { connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } InputStream stream = connection.getInputStream(); Scanner in = new Scanner(stream); response = in.nextLine(); String[] data = response.split(":"); sessionId = data[0]; heartbeatTimeout = Long.parseLong(data[1]) * 1000; closingTimeout = Long.parseLong(data[2]) * 1000; protocols = Arrays.asList(data[3].split(",")); } catch (Exception e) { error(new SocketIOException("Error while handshaking", e)); } }
From source file:net.solarnetwork.node.support.HttpClientSupport.java
/** * Get a URLConnection for a specific URL and HTTP method. * /* w w w.j a v a2s. co m*/ * <p> * If the httpMethod equals {@code POST} then the connection's * {@code doOutput} property will be set to <em>true</em>, otherwise it will * be set to <em>false</em>. The {@code doInput} property is always set to * <em>true</em>. * </p> * * <p> * This method also sets up the request property * {@code Accept-Encoding: gzip,deflate} so the response can be compressed. * The {@link #getInputSourceFromURLConnection(URLConnection)} automatically * handles compressed responses. * </p> * * <p> * If the {@link #getSslService()} property is configured and the URL * represents an HTTPS connection, then that factory will be used to for the * connection. * </p> * * @param url * the URL to connect to * @param httpMethod * the HTTP method * @param accept * the HTTP Accept header value * @return the URLConnection * @throws IOException * if any IO error occurs */ protected URLConnection getURLConnection(String url, String httpMethod, String accept) throws IOException { URL connUrl = new URL(url); URLConnection conn = connUrl.openConnection(); if (conn instanceof HttpURLConnection) { HttpURLConnection hConn = (HttpURLConnection) conn; hConn.setRequestMethod(httpMethod); } if (sslService != null && conn instanceof HttpsURLConnection) { SSLService service = sslService.service(); if (service != null) { SSLSocketFactory factory = service.getSolarInSocketFactory(); if (factory != null) { HttpsURLConnection hConn = (HttpsURLConnection) conn; hConn.setSSLSocketFactory(factory); } } } conn.setRequestProperty("Accept", accept); conn.setRequestProperty("Accept-Encoding", "gzip,deflate"); conn.setDoInput(true); conn.setDoOutput(HTTP_METHOD_POST.equalsIgnoreCase(httpMethod)); conn.setConnectTimeout(this.connectionTimeout); conn.setReadTimeout(connectionTimeout); return conn; }
From source file:com.example.socketio.lib.IOConnection.java
/** * Handshake.// w w w . j av a 2 s .c om * */ private void handshake() { URL url; String response; URLConnection connection; try { setState(STATE_HANDSHAKE); url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1); connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(connectTimeout); /* Setting the request headers */ for (Entry<Object, Object> entry : headers.entrySet()) { connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } InputStream stream = connection.getInputStream(); Scanner in = new Scanner(stream); response = in.nextLine(); String[] data = response.split(":"); sessionId = data[0]; heartbeatTimeout = Long.parseLong(data[1]) * 1000; closingTimeout = Long.parseLong(data[2]) * 1000; protocols = Arrays.asList(data[3].split(",")); } catch (Exception e) { error(new SocketIOException("Error while handshaking", e)); SendErrorMessageWithBroadcast(SocketIOAction.SOCKETIO_ERRORMESSAGE_ERRORHANDSHAKING); } }
From source file:org.kmallan.azureus.rssfeed.Scheduler.java
public synchronized void runFeed(final UrlBean urlBean) { String url = urlBean.getLocation(); String title, link, description; ListGroup listBeans = urlBean.getGroup(); DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); docFactory.setIgnoringComments(true); docFactory.setIgnoringElementContentWhitespace(true); DocumentBuilder docBuild;// w ww.ja va 2 s. c o m Document feed; File xmlTmp = null; try { docBuild = docFactory.newDocumentBuilder(); Downloader downloader = new Downloader(); downloader.addListener(new DownloaderListener() { public boolean completed = false, error = false; public void downloaderUpdate(int state, int percent, int amount, String err) { if (completed || error) return; String status = new String("Pending"); switch (state) { case Downloader.DOWNLOADER_NON_INIT: status = "Pending"; break; case Downloader.DOWNLOADER_INIT: status = "Connecting"; break; case Downloader.DOWNLOADER_START: status = "Download Starting"; break; case Downloader.DOWNLOADER_DOWNLOADING: status = "Downloading"; break; case Downloader.DOWNLOADER_FINISHED: status = "Download Finished"; completed = true; break; case Downloader.DOWNLOADER_NOTMODIFIED: status = "Not modified"; completed = true; break; case Downloader.DOWNLOADER_ERROR: status = "Error"; error = true; break; } urlBean.setStatus(status); if (percent > 0) urlBean.setPercent(percent); if (amount > 0) urlBean.setAmount(amount); if (!err.equalsIgnoreCase("")) urlBean.setError(err); if (view.isOpen() && view.display != null && !view.display.isDisposed()) view.display.asyncExec(new Runnable() { public void run() { if (view.listTable == null || view.listTable.isDisposed()) return; ListTreeItem listGroup = view.treeViewManager.getItem(urlBean); listGroup.setText(1, urlBean.getStatus() + " " + (!urlBean.getError() .equalsIgnoreCase("") && urlBean.getStatus() == "Error" ? "- " + urlBean.getError() : (urlBean.getStatus() == "Downloading" ? (urlBean.getPercent() > 0 ? Integer.toString(urlBean.getPercent()) + "%" : (urlBean.getAmount() > 0 ? Double.toString(Math.floor( new Integer(urlBean.getAmount()).doubleValue() / (double) 1024 * (double) 100) / (double) 100) + "KB" : "")) : ""))); if (!urlBean.getError().equalsIgnoreCase("")) listGroup.setForeground(new Color(view.display, 255, 0, 0)); else listGroup.resetForeground(); } }); } }); downloader.init(url, "text/xml, text/html, text/plain, application/x-httpd-php", null, (urlBean.getUseCookie() ? urlBean.getCookie() : null), urlBean.getLastModifed(), urlBean.getLastEtag()); if (downloader.getState() == Downloader.DOWNLOADER_ERROR) return; if (downloader.getState() == Downloader.DOWNLOADER_NOTMODIFIED) { // no change, add the old items again for (Iterator iter = listBeans.getPreviousItems().iterator(); iter.hasNext();) { addTableElement(urlBean, listBeans, (ListBean) iter.next()); } addBacklogElements(urlBean); downloader.notModified(); // use the last seen TTL value if available if (urlBean.getObeyTTL() && listBeans.getPreviousDelay() > 0) listBeans.setDelay(listBeans.getPreviousDelay()); return; } Plugin.debugOut( urlBean.getName() + " Last-Modified: " + downloader.lastModified + " ETag: " + downloader.etag); urlBean.setLastModifed(downloader.lastModified); urlBean.setLastEtag(downloader.etag); xmlTmp = new File(Plugin.getPluginDirectoryName(), "tmp-" + urlBean.getID() + ".xml"); xmlTmp.createNewFile(); FileOutputStream fileout = new FileOutputStream(xmlTmp, false); byte[] buf = new byte[2048]; int read = 0; do { if (downloader.getState() == Downloader.DOWNLOADER_CANCELED) break; read = downloader.read(buf); if (read > 0) { System.err.print("."); fileout.write(buf, 0, read); } else if (read == 0) { System.err.print("?"); try { long numMillisecondsToSleep = 100; Thread.sleep(numMillisecondsToSleep); } catch (InterruptedException e) { } } } while (read >= 0); fileout.flush(); fileout.close(); docBuild.setEntityResolver(new EntityResolver() { public InputSource resolveEntity(String publicId, String systemId) { // System.out.println( publicId + ", " + systemId ); // handle bad DTD external refs if (Plugin.getProxyOption() == Plugin.PROXY_TRY_PLUGIN) { return new InputSource( new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes())); } try { URL url = new URL(systemId); String host = url.getHost(); InetAddress.getByName(host); // try connecting too as connection-refused will also bork XML parsing InputStream is = null; try { URLConnection con = url.openConnection(); con.setConnectTimeout(15 * 1000); con.setReadTimeout(15 * 1000); is = con.getInputStream(); byte[] buffer = new byte[32]; int pos = 0; while (pos < buffer.length) { int len = is.read(buffer, pos, buffer.length - pos); if (len <= 0) { break; } pos += len; } String str = new String(buffer, "UTF-8").trim().toLowerCase(Locale.US); if (!str.contains("<?xml")) { // not straightforward to check for naked DTDs, could be lots of <!-- commentry preamble which of course can occur // in HTML too buffer = new byte[32000]; pos = 0; while (pos < buffer.length) { int len = is.read(buffer, pos, buffer.length - pos); if (len <= 0) { break; } pos += len; } str += new String(buffer, "UTF-8").trim().toLowerCase(Locale.US); if (str.contains("<html") && str.contains("<head")) { throw (new Exception("Bad DTD")); } } } catch (Throwable e) { return new InputSource( new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes())); } finally { if (is != null) { try { is.close(); } catch (Throwable e) { } } } return (null); } catch (UnknownHostException e) { return new InputSource( new ByteArrayInputStream("<?xml version='1.0' encoding='UTF-8'?>".getBytes())); } catch (Throwable e) { return (null); } } }); try { feed = docBuild.parse(xmlTmp); } catch (Exception e) { feed = null; String msg = Debug.getNestedExceptionMessage(e); if ((msg.contains("entity") && msg.contains("was referenced")) || msg.contains("entity reference")) { FileInputStream fis = new FileInputStream(xmlTmp); try { feed = docBuild.parse(new EntityFudger(fis)); } catch (Throwable f) { } finally { fis.close(); } } if (feed == null) { if (e instanceof ParserConfigurationException) { throw ((ParserConfigurationException) e); } else if (e instanceof SAXException) { throw ((SAXException) e); } else if (e instanceof IOException) { throw ((IOException) e); } else { throw (new IOException(msg)); } } } xmlTmp.delete(); downloader.done(); if (downloader.getState() == Downloader.DOWNLOADER_ERROR) return; } catch (ParserConfigurationException e) { if (xmlTmp != null) xmlTmp.delete(); urlBean.setError("Malformed RSS XML: " + e.getMessage()); return; } catch (SAXException e) { if (xmlTmp != null) xmlTmp.delete(); urlBean.setError("Malformed RSS XML: " + e.getMessage()); return; } catch (IOException e) { if (xmlTmp != null) xmlTmp.delete(); urlBean.setError("IO Exception: " + e.getMessage()); return; } if (urlBean.getObeyTTL()) { NodeList feedTTL = feed.getElementsByTagName("ttl"); if (feedTTL.getLength() == 1) { int newDelay = Integer.parseInt(getText(feedTTL.item(0))) * 60; if (newDelay > 0) urlBean.getGroup().setDelay(newDelay, true); } } // Parse the channel's "item"s NodeList feedItems = feed.getElementsByTagName("item"); int feedItemLen = feedItems.getLength(); for (int iLoop = 0; iLoop < feedItemLen; iLoop++) { Node item = feedItems.item(iLoop); NodeList params = item.getChildNodes(); int paramsLen = params.getLength(); title = link = description = ""; for (int i = 0; i < paramsLen; i++) { Node param = params.item(i); if (param.getNodeType() == Node.ELEMENT_NODE) { if (param.getNodeName().equalsIgnoreCase("title")) { title = getText(param); } else if (param.getNodeName().equalsIgnoreCase("enclosure") && param.hasAttributes()) { if ((((param.getAttributes()).getNamedItem("type")).getNodeValue()) .equalsIgnoreCase("application/x-bittorrent")) { link = ((param.getAttributes()).getNamedItem("url")).getNodeValue(); } } else if (param.getNodeName().equalsIgnoreCase("link") && link.length() == 0) { link = getText(param); } else if (param.getNodeName().equalsIgnoreCase("description")) { description = getText(param); if (description != null && description.trim().startsWith("<")) { // strip html tags and entity references from description HtmlAnalyzer parser = new HtmlAnalyzer(); try { new ParserDelegator().parse(new StringReader(description), parser, true); description = parser.getPlainText(); } catch (IOException e) { } } description += "\n"; } } } if (link.length() == 0) continue; if (link.indexOf("://") < 0 && !link.toLowerCase().startsWith("magnet")) { try { link = HtmlAnalyzer.resolveRelativeURL(urlBean.getLocation(), link); } catch (MalformedURLException e) { Plugin.debugOut("Bad link URL: " + link + " -> " + e.getMessage()); continue; } } int state = ListBean.NO_DOWNLOAD; String titleTest = title.toLowerCase(); String linkTest = link.toLowerCase(); FilterBean curFilter = null; for (int i = 0; i < view.rssfeedConfig.getFilterCount(); i++) { curFilter = view.rssfeedConfig.getFilter(i); if (curFilter == null) continue; if (curFilter.matches(urlBean.getID(), titleTest, linkTest)) { if (curFilter.getMode().equalsIgnoreCase("Pass")) { state = ListBean.DOWNLOAD_INCL; } else { state = ListBean.DOWNLOAD_EXCL; } break; } } Episode e = null; Movie m = null; final FilterBean filterBean = curFilter; if (filterBean != null) { if ("TVShow".equalsIgnoreCase(filterBean.getType())) { try { e = FilterBean.getSeason(titleTest); } catch (Exception ee) { } try { if (e == null) { e = FilterBean.getSeason(linkTest); } } catch (Exception ee) { } } else if ("Movie".equalsIgnoreCase(filterBean.getType())) { m = FilterBean.getMovie(titleTest); if (m == null) { m = FilterBean.getMovie(linkTest); } Plugin.debugOut("Download is a movie: " + m); } } if (state == ListBean.DOWNLOAD_INCL) { Plugin.debugOut("testing for download: " + linkTest); if (filterBean.getUseSmartHistory()) { for (int i = 0; i < view.rssfeedConfig.getHistoryCount(); i++) { HistoryBean histBean = view.rssfeedConfig.getHistory(i); if (linkTest.equalsIgnoreCase(histBean.getLocation())) { Plugin.debugOut("found location match: " + histBean); state = ListBean.DOWNLOAD_HIST; break; } if (e != null && histBean.getSeasonStart() >= 0 && filterBean.getUseSmartHistory()) { final String showTitle = histBean.getTitle(); // Old history beans may not have set showTitle so keep using the old way of matching if (showTitle == null ? (histBean.getFiltID() == filterBean.getID()) : showTitle.equalsIgnoreCase(e.showTitle)) { // "Proper" episode is not skipped unless history is also proper if (histBean.isProper() || !e.isProper()) { int seasonStart = histBean.getSeasonStart(); int episodeStart = histBean.getEpisodeStart(); int seasonEnd = histBean.getSeasonEnd(); int episodeEnd = histBean.getEpisodeEnd(); Plugin.debugOut(e + " vs s" + seasonStart + "e" + episodeStart + " - s" + seasonEnd + "e" + episodeEnd); if (e.inRange(seasonStart, episodeStart, seasonEnd, episodeEnd)) { Plugin.debugOut("found filter and episode match: " + e); state = ListBean.DOWNLOAD_HIST; break; } } } } else if (m != null && m.getTitle().equals(histBean.getTitle()) && m.getYear() == histBean.getYear()) { if (histBean.isProper() || !m.isProper()) { Plugin.debugOut("found movie match: " + m); state = ListBean.DOWNLOAD_HIST; } } } } else Plugin.debugOut("Filter doesn't use smart history: " + filterBean); } final ListBean listBean = addTableElement(urlBean, listBeans, title, link, description, state); if (state == ListBean.DOWNLOAD_INCL) { // Add the feed final String curLink = link; boolean success = view.torrentDownloader.addTorrent(curLink, urlBean, filterBean, listBean); if (success && filterBean.getType().equalsIgnoreCase("Other") && filterBean.getDisableAfter()) filterBean.setEnabled(false); if (view.isOpen() && view.display != null && !view.display.isDisposed()) view.display.asyncExec(new Runnable() { public void run() { ListTreeItem listItem = view.treeViewManager.getItem(listBean); if (listItem != null) listItem.update(); } }); } } }
From source file:jp.ne.sakura.kkkon.java.net.inetaddress.testapp.android.NetworkConnectionCheckerTestApp.java
/** Called when the activity is first created. */ @Override//from w ww .j ava 2s . c om public void onCreate(Bundle savedInstanceState) { final Context context = this.getApplicationContext(); { NetworkConnectionChecker.initialize(); } super.onCreate(savedInstanceState); /* Create a TextView and set its content. * the text is retrieved by calling a native * function. */ LinearLayout layout = new LinearLayout(this); layout.setOrientation(LinearLayout.VERTICAL); TextView tv = new TextView(this); tv.setText("reachable="); layout.addView(tv); this.textView = tv; Button btn1 = new Button(this); btn1.setText("invoke Exception"); btn1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final int count = 2; int[] array = new int[count]; int value = array[count]; // invoke IndexOutOfBOundsException } }); layout.addView(btn1); { Button btn = new Button(this); btn.setText("disp isReachable"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final boolean isReachable = NetworkConnectionChecker.isReachable(); Toast toast = Toast.makeText(context, "IsReachable=" + isReachable, Toast.LENGTH_LONG); toast.show(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("upload http AsyncTask"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { AsyncTask<String, Void, Boolean> asyncTask = new AsyncTask<String, Void, Boolean>() { @Override protected Boolean doInBackground(String... paramss) { Boolean result = true; Log.d(TAG, "upload AsyncTask tid=" + android.os.Process.myTid()); try { //$(BRAND)/$(PRODUCT)/$(DEVICE)/$(BOARD):$(VERSION.RELEASE)/$(ID)/$(VERSION.INCREMENTAL):$(TYPE)/$(TAGS) Log.d(TAG, "fng=" + Build.FINGERPRINT); final List<NameValuePair> list = new ArrayList<NameValuePair>(16); list.add(new BasicNameValuePair("fng", Build.FINGERPRINT)); HttpPost httpPost = new HttpPost(paramss[0]); //httpPost.getParams().setParameter( CoreConnectionPNames.SO_TIMEOUT, new Integer(5*1000) ); httpPost.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8)); DefaultHttpClient httpClient = new DefaultHttpClient(); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(5 * 1000)); httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(5 * 1000)); Log.d(TAG, "socket.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.SO_TIMEOUT, -1)); Log.d(TAG, "connection.timeout=" + httpClient.getParams() .getIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, -1)); // <uses-permission android:name="android.permission.INTERNET"/> // got android.os.NetworkOnMainThreadException, run at UI Main Thread HttpResponse response = httpClient.execute(httpPost); Log.d(TAG, "response=" + response.getStatusLine().getStatusCode()); } catch (Exception e) { Log.d(TAG, "got Exception. msg=" + e.getMessage(), e); result = false; } Log.d(TAG, "upload finish"); return result; } }; asyncTask.execute("http://kkkon.sakura.ne.jp/android/bug"); asyncTask.isCancelled(); } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(0.0.0.0)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { destHost = InetAddress.getByName("0.0.0.0"); if (null != destHost) { try { if (destHost.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + destHost.toString() + " reachable"); } else { Log.d(TAG, "destHost=" + destHost.toString() + " not reachable"); } } catch (IOException e) { } } } catch (UnknownHostException e) { } Log.d(TAG, "destHost=" + destHost); } }); thread.start(); try { thread.join(1000); } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(www.google.com)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { Log.d(TAG, "start"); try { InetAddress dest = InetAddress.getByName("www.google.com"); if (null == dest) { dest = destHost; } if (null != dest) { final String[] uris = new String[] { "http://www.google.com/", "https://www.google.com/" }; for (final String destURI : uris) { URI uri = null; try { uri = new URI(destURI); } catch (URISyntaxException e) { //Log.d( TAG, e.toString() ); } if (null != uri) { URL url = null; try { url = uri.toURL(); } catch (MalformedURLException ex) { Log.d(TAG, "got exception:" + ex.toString(), ex); } URLConnection conn = null; if (null != url) { Log.d(TAG, "openConnection before"); try { conn = url.openConnection(); if (null != conn) { conn.setConnectTimeout(3 * 1000); conn.setReadTimeout(3 * 1000); } } catch (IOException e) { //Log.d( TAG, "got Exception" + e.toString(), e ); } Log.d(TAG, "openConnection after"); if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; int responceCode = -1; try { Log.d(TAG, "getResponceCode before"); responceCode = httpConn.getResponseCode(); Log.d(TAG, "getResponceCode after"); } catch (IOException ex) { Log.d(TAG, "got exception:" + ex.toString(), ex); } Log.d(TAG, "responceCode=" + responceCode); if (0 < responceCode) { isReachable = true; destHost = dest; } Log.d(TAG, " HTTP ContentLength=" + httpConn.getContentLength()); httpConn.disconnect(); Log.d(TAG, " HTTP ContentLength=" + httpConn.getContentLength()); } } } // if uri if (isReachable) { //break; } } // for uris } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } Log.d(TAG, "end"); } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp)"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { Log.d(TAG, "start"); try { InetAddress dest = InetAddress.getByName("kkkon.sakura.ne.jp"); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); } destHost = dest; } catch (IOException e) { } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } Log.d(TAG, "end"); } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } { Button btn = new Button(this); btn.setText("pre DNS query(kkkon.sakura.ne.jp) support proxy"); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { isReachable = false; Thread thread = new Thread(new Runnable() { public void run() { try { String target = null; { ProxySelector proxySelector = ProxySelector.getDefault(); Log.d(TAG, "proxySelector=" + proxySelector); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { Log.d(TAG, e.toString()); } List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { Log.d(TAG, " proxy=" + proxy); if (null != proxy) { if (Proxy.Type.HTTP == proxy.type()) { final SocketAddress sa = proxy.address(); if (sa instanceof InetSocketAddress) { final InetSocketAddress isa = (InetSocketAddress) sa; target = isa.getHostName(); break; } } } } } } } if (null == target) { target = "kkkon.sakura.ne.jp"; } InetAddress dest = InetAddress.getByName(target); if (null == dest) { dest = destHost; } if (null != dest) { try { if (dest.isReachable(5 * 1000)) { Log.d(TAG, "destHost=" + dest.toString() + " reachable"); isReachable = true; } else { Log.d(TAG, "destHost=" + dest.toString() + " not reachable"); { ProxySelector proxySelector = ProxySelector.getDefault(); //Log.d( TAG, "proxySelector=" + proxySelector ); if (null != proxySelector) { URI uri = null; try { uri = new URI("http://www.google.com/"); } catch (URISyntaxException e) { //Log.d( TAG, e.toString() ); } if (null != uri) { List<Proxy> proxies = proxySelector.select(uri); if (null != proxies) { for (final Proxy proxy : proxies) { //Log.d( TAG, " proxy=" + proxy ); if (null != proxy) { if (Proxy.Type.HTTP == proxy.type()) { URL url = uri.toURL(); URLConnection conn = null; if (null != url) { try { conn = url.openConnection(proxy); if (null != conn) { conn.setConnectTimeout( 3 * 1000); conn.setReadTimeout(3 * 1000); } } catch (IOException e) { Log.d(TAG, "got Exception" + e.toString(), e); } if (conn instanceof HttpURLConnection) { HttpURLConnection httpConn = (HttpURLConnection) conn; if (0 < httpConn .getResponseCode()) { isReachable = true; } Log.d(TAG, " HTTP ContentLength=" + httpConn .getContentLength()); Log.d(TAG, " HTTP res=" + httpConn .getResponseCode()); //httpConn.setInstanceFollowRedirects( false ); //httpConn.setRequestMethod( "HEAD" ); //conn.connect(); httpConn.disconnect(); Log.d(TAG, " HTTP ContentLength=" + httpConn .getContentLength()); Log.d(TAG, " HTTP res=" + httpConn .getResponseCode()); } } } } } } } } } } destHost = dest; } catch (IOException e) { Log.d(TAG, "got Excpetion " + e.toString()); } } else { } } catch (UnknownHostException e) { Log.d(TAG, "dns error" + e.toString()); destHost = null; } { if (null != destHost) { Log.d(TAG, "destHost=" + destHost); } } } }); thread.start(); try { thread.join(); { final String addr = (null == destHost) ? ("") : (destHost.toString()); final String reachable = (isReachable) ? ("reachable") : ("not reachable"); Toast toast = Toast.makeText(context, "DNS result=\n" + addr + "\n " + reachable, Toast.LENGTH_LONG); toast.show(); } } catch (InterruptedException e) { } } }); layout.addView(btn); } setContentView(layout); }
From source file:com.xeiam.xchange.streaming.socketio.IOConnection.java
/** * Handshake./*from w w w . ja v a 2s. com*/ */ private void handshake() { URL url; String response; URLConnection connection; try { setState(STATE_HANDSHAKE); url = new URL(this.url.getProtocol() + "://" + this.url.getAuthority() + SOCKET_IO_1 + (this.url.getQuery() == null ? "" : "?" + this.url.getQuery())); connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslSocketFactory); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(connectTimeout); /* Setting the request headers */ for (Entry<Object, Object> entry : headers.entrySet()) { connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } log.debug("> " + connection.toString()); InputStream stream = connection.getInputStream(); Scanner in = new Scanner(stream); response = in.nextLine(); log.debug("< " + response); String[] data = response.split(":"); sessionId = data[0]; heartbeatTimeout = Long.parseLong(data[1]) * 1000; closingTimeout = Long.parseLong(data[2]) * 1000; protocols = Arrays.asList(data[3].split(",")); } catch (Exception e) { error(new SocketIOException("Error while handshaking", e)); } }
From source file:org.sakaiproject.calendar.impl.BaseExternalCalendarSubscriptionService.java
ExternalSubscription loadCalendarSubscriptionFromUrl(String url, String context, String calendarName, String forcedEventType) { ExternalSubscription subscription = new BaseExternalSubscription(calendarName, url, context, null, INSTITUTIONAL_CONTEXT.equals(context)); ExternalCalendarSubscription calendar = null; List<CalendarEvent> events = null; BufferedInputStream stream = null; try {//from ww w . j a v a 2 s .c o m URL _url = new URL(url); if (calendarName == null) calendarName = _url.getFile(); // connect URLConnection conn = _url.openConnection(); // Must set user agent so we can detect loops. conn.addRequestProperty("User-Agent", m_calendarService.getUserAgent()); conn.setConnectTimeout(TIMEOUT); conn.setReadTimeout(TIMEOUT); // Now make the connection. conn.connect(); stream = new BufferedInputStream(conn.getInputStream()); // import events = m_importerService.doImport(CalendarImporterService.ICALENDAR_IMPORT, stream, columnMap, null); String subscriptionId = getIdFromSubscriptionUrl(url); String reference = calendarSubscriptionReference(context, subscriptionId); calendar = new ExternalCalendarSubscription(reference); for (CalendarEvent event : events) { String eventType = event.getType(); if (forcedEventType != null) eventType = forcedEventType; calendar.addEvent(event.getRange(), event.getDisplayName(), event.getDescription(), eventType, event.getLocation(), event.getRecurrenceRule(), null); } calendar.setName(calendarName); subscription.setCalendar(calendar); subscription.setInstitutional(getInstitutionalSubscription(url) != null); m_log.info("Loaded calendar subscription: " + subscription.toString()); } catch (ImportException e) { m_log.info("Error loading calendar subscription '" + calendarName + "' (will NOT retry again): " + url); String subscriptionId = getIdFromSubscriptionUrl(url); String reference = calendarSubscriptionReference(context, subscriptionId); calendar = new ExternalCalendarSubscription(reference); calendar.setName(calendarName); // By setting the calendar to be an empty one we make sure that we don't attempt to re-retrieve it // When 2 hours are up it will get refreshed through. subscription.setCalendar(calendar); } catch (PermissionException e) { // This will never be called (for now) e.printStackTrace(); } catch (MalformedURLException e) { m_log.info("Mal-formed URL in calendar subscription '" + calendarName + "': " + url); } catch (IOException e) { m_log.info("Unable to read calendar subscription '" + calendarName + "' from URL (I/O Error): " + url); } catch (Exception e) { m_log.info("Unknown error occurred while reading calendar subscription '" + calendarName + "' from URL: " + url); } finally { if (stream != null) { // Also closes the underlying InputStream try { stream.close(); } catch (IOException e) { // Ignore } } } return subscription; }
From source file:de.mmbbs.io.socket.IOConnection.java
/** * Handshake.//from w ww.ja v a2s .c om * */ private void handshake() { URL url; String response = ""; URLConnection connection; try { setState(STATE_HANDSHAKE); url = new URL(IOConnection.this.url.toString() + SOCKET_IO_1 + "?EIO=2&transport=polling"); logger.info("URL: " + url.toString()); connection = url.openConnection(); if (connection instanceof HttpsURLConnection) { ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory()); } connection.setConnectTimeout(connectTimeout); connection.setReadTimeout(connectTimeout); /* Setting the request headers */ for (Entry<Object, Object> entry : headers.entrySet()) { connection.setRequestProperty((String) entry.getKey(), (String) entry.getValue()); } BufferedReader inB = new BufferedReader(new InputStreamReader(connection.getInputStream())); String inputLine; while ((inputLine = inB.readLine()) != null) { response += inputLine; } inB.close(); // InputStream stream = connection.getInputStream(); // Scanner in = new Scanner(stream); // while (in.hasNext()) // { // response += in.next(); // } // in.close(); Pattern pattern = Pattern.compile("\\w+:\\w+:\\w+:\\w+"); Matcher matcher = pattern.matcher(response); if (matcher.find()) { logger.info("Response: " + response); this.version = VersionSocketIO.V09x; logger.info("Version: V09x"); String[] data = response.split(":"); sessionId = data[0]; heartbeatTimeout = Long.parseLong(data[1]) * 1000; closingTimeout = Long.parseLong(data[2]) * 1000; protocols = Arrays.asList(data[3].split(",")); } else { response = response.substring(response.indexOf('{')); response = response.substring(0, response.lastIndexOf('}') + 1); logger.info("Response: " + response); this.version = VersionSocketIO.V10x; logger.info("Version: V10x"); try { JSONObject data = null; data = new JSONObject(response); sessionId = data.getString("sid"); heartbeatTimeout = data.getLong("pingInterval"); closingTimeout = data.getLong("pingTimeout"); // JSONArray arr = data.getJSONArray("upgrades"); // for (int i = 0; i < arr.length(); i++) { // protocols.add(arr.getString(i)); // } protocols = new ArrayList<String>(); protocols.add("websocket"); } catch (JSONException e) { logger.warning("Malformated JSON received"); } } } catch (Exception e) { error(new SocketIOException("Error while handshaking", e)); } }
From source file:com.adito.extensions.store.ExtensionStore.java
/** * @param id//from w ww.j a v a 2 s .co m * @param version * @return URLConnection * @throws IOException */ public URLConnection downloadExtension(String id, String version) throws IOException { URL downloadURL = getDownloadURL(id, version); if (downloadURL != null) { if (log.isInfoEnabled()) log.info("Downloading extension from " + downloadURL.toExternalForm()); URLConnection con = downloadURL.openConnection(); con.setConnectTimeout(CONNECT_TIMEOUT); con.setReadTimeout(READ_TIMEOUT); con.connect(); return con; } else { throw new IOException("No valid download location for " + id); } }