List of usage examples for java.net URLConnection setConnectTimeout
public void setConnectTimeout(int timeout)
From source file:com.varaneckas.hawkscope.Version.java
/** * Asynchroniously checks if a newer version of Hawkscope is available * // w ww. ja v a 2s. com * @return */ public static void checkForUpdate() { if (!cfg.checkForUpdates()) { return; } try { log.debug("Checking for updates..."); URLConnection conn = null; final URL versionCheckUrl = new URL(VERSION_CHECK_URL); Proxy proxy = null; if (cfg.isHttpProxyInUse()) { proxy = new Proxy(Type.HTTP, InetSocketAddress.createUnresolved(cfg.getHttpProxyHost(), cfg.getHttpProxyPort())); conn = versionCheckUrl.openConnection(proxy); } else { conn = versionCheckUrl.openConnection(); } conn.setConnectTimeout(Constants.CONNECTION_TIMOUT); conn.setReadTimeout(Constants.CONNECTION_TIMOUT); final InputStream io = conn.getInputStream(); int c = 0; final StringBuilder version = new StringBuilder(); while ((c = io.read()) != -1) { version.append((char) c); } if (log.isDebugEnabled()) { log.debug("Check complete. Latest " + OSUtils.CURRENT_OS + " version: " + version.toString()); } if (VERSION_NUMBER.compareTo(version.toString()) < 0) { log.info("Newer " + OSUtils.CURRENT_OS + " version available (" + version.toString() + "). You should update Hawkscope!"); isUpdateAvailable = true; updateVersion = version.toString(); } else { log.info("You have the latest available version of Hawkscope: " + VERSION_NUMBER); isUpdateAvailable = false; } PluginManager.getInstance().checkPluginUpdates(PLUGIN_VERSION_CHECK_URL, proxy); } catch (final Exception e) { log.info("Failed checking for update: " + e.getMessage()); } }
From source file:org.omegat.util.StaticUtils.java
/** * dowload a file from the internet/*from w w w .j a v a 2 s . co m*/ */ public static String downloadFileToString(String urlString) throws IOException { URLConnection urlConn; InputStream in; URL url = new URL(urlString); urlConn = url.openConnection(); //don't wait forever. 10 seconds should be enough. urlConn.setConnectTimeout(10000); in = urlConn.getInputStream(); try { return IOUtils.toString(in, "UTF-8"); } finally { in.close(); } }
From source file:org.deegree.commons.proxy.ProxySettings.java
/** * This method should be used everywhere instead of <code>URL.openConnection()</code>, as it copes with proxies that * require user authentication.//w w w . j av a 2 s . c o m * * @param url * @param user * @param pass * @return connection * @throws IOException */ public static URLConnection openURLConnection(URL url, String user, String pass) throws IOException { URLConnection conn = url.openConnection(); if (user != null) { // TODO evaluate java.net.Authenticator String userAndPass = Base64.encodeBase64String((user + ":" + pass).getBytes()); conn.setRequestProperty("Proxy-Authorization", "Basic " + userAndPass); } // TODO should this be a method parameter? conn.setConnectTimeout(5000); return conn; }
From source file:com.roadwarrior.vtiger.client.NetworkUtilities.java
/** * Connects to the server, authenticates the provided username and * password./*from w w w . j a v a 2s .c o m*/ * * @param username The user's username * @param password The user's password * @return String The authentication token returned by the server (or null) */ public static String authenticate(String username, String accessKey, String base_url) { String token = null; String hash = null; authenticate_log_text = "authenticate()\n"; AUTH_URI = base_url + "/webservice.php"; authenticate_log_text = authenticate_log_text + "url: " + AUTH_URI + "?operation=getchallenge&username=" + username + "\n"; Log.d(TAG, "AUTH_URI : "); Log.d(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); // =========== get challenge token ============================== ArrayList<NameValuePair> params = new ArrayList<NameValuePair>(); try { URL url; // HTTP GET REQUEST url = new URL(AUTH_URI + "?operation=getchallenge&username=" + username); HttpURLConnection con; con = (HttpURLConnection) url.openConnection(); con.setRequestMethod("GET"); con.setRequestProperty("Content-length", "0"); con.setUseCaches(false); // for some site that redirects based on user agent con.setInstanceFollowRedirects(true); con.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.0.15) Gecko/2009101600 Firefox/3.0.15"); con.setAllowUserInteraction(false); int timeout = 20000; con.setConnectTimeout(timeout); con.setReadTimeout(timeout); con.connect(); int status = con.getResponseCode(); authenticate_log_text = authenticate_log_text + "Request status = " + status + "\n"; switch (status) { case 200: case 201: case 302: BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "body : " + sb.toString(); if (status == 302) { authenticate_log_text = sb.toString(); return null; } JSONObject result = new JSONObject(sb.toString()); Log.d(TAG, result.getString("result")); JSONObject data = new JSONObject(result.getString("result")); token = data.getString("token"); break; case 401: Log.e(TAG, "Server auth error: ");// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "Server auth error"; return null; default: Log.e(TAG, "connection status code " + status);// + readResponse(con.getErrorStream())); authenticate_log_text = authenticate_log_text + "connection status code :" + status; return null; } } catch (ClientProtocolException e) { Log.i(TAG, "getchallenge:http protocol error"); Log.e(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "ClientProtocolException :" + e.getMessage() + "\n"; return null; } catch (IOException e) { Log.e(TAG, "getchallenge: IO Exception"); Log.e(TAG, e.getMessage()); Log.e(TAG, AUTH_URI + "?operation=getchallenge&username=" + username); authenticate_log_text = authenticate_log_text + "getchallenge: IO Exception : " + e.getMessage() + "\n"; return null; } catch (JSONException e) { Log.i(TAG, "json exception"); authenticate_log_text = authenticate_log_text + "JSon exception\n"; // TODO Auto-generated catch block e.printStackTrace(); return null; } // ================= login ================== try { MessageDigest m = MessageDigest.getInstance("MD5"); m.update(token.getBytes()); m.update(accessKey.getBytes()); hash = new BigInteger(1, m.digest()).toString(16); Log.i(TAG, "hash"); Log.i(TAG, hash); } catch (NoSuchAlgorithmException e) { authenticate_log_text = authenticate_log_text + "MD5 => no such algorithm\n"; e.printStackTrace(); } try { String charset; charset = "utf-8"; String query = String.format("operation=login&username=%s&accessKey=%s", URLEncoder.encode(username, charset), URLEncoder.encode(hash, charset)); authenticate_log_text = authenticate_log_text + "login()\n"; URLConnection connection = new URL(AUTH_URI).openConnection(); connection.setDoOutput(true); // Triggers POST. int timeout = 20000; connection.setConnectTimeout(timeout); connection.setReadTimeout(timeout); connection.setAllowUserInteraction(false); connection.setRequestProperty("Accept-Charset", charset); connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + charset); connection.setUseCaches(false); OutputStream output = connection.getOutputStream(); try { output.write(query.getBytes(charset)); } finally { try { output.close(); } catch (IOException logOrIgnore) { } } Log.d(TAG, "Query written"); BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = br.readLine()) != null) { sb.append(line + "\n"); } br.close(); Log.d(TAG, "message post body"); Log.d(TAG, sb.toString()); authenticate_log_text = authenticate_log_text + "post message body :" + sb.toString() + "\n"; JSONObject result = new JSONObject(sb.toString()); String success = result.getString("success"); Log.i(TAG, success); if (success == "true") { Log.i(TAG, result.getString("result")); Log.i(TAG, "sucesssfully logged in is"); JSONObject data = new JSONObject(result.getString("result")); sessionName = data.getString("sessionName"); Log.i(TAG, sessionName); authenticate_log_text = authenticate_log_text + "successfully logged in\n"; return token; } else { // success is false, retrieve error JSONObject data = new JSONObject(result.getString("error")); authenticate_log_text = "can not login :\n" + data.toString(); return null; } //token = data.getString("token"); //Log.i(TAG,token); } catch (ClientProtocolException e) { Log.d(TAG, "login: http protocol error"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "HTTP Protocol error \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (IOException e) { Log.d(TAG, "login: IO Exception"); Log.d(TAG, e.getMessage()); authenticate_log_text = authenticate_log_text + "login: IO Exception \n"; authenticate_log_text = authenticate_log_text + e.getMessage() + "\n"; } catch (JSONException e) { Log.d(TAG, "JSON exception"); // TODO Auto-generated catch block authenticate_log_text = authenticate_log_text + "JSON exception "; authenticate_log_text = authenticate_log_text + e.getMessage(); e.printStackTrace(); } return null; // ======================================================================== }
From source file:de.dal33t.powerfolder.util.ConfigurationLoader.java
/** * Loads a pre-configuration from the URL * * @param from/*from w w w .j a v a 2 s.co m*/ * the URL to load from * @return the loaded properties WITHOUT those in config. * @throws IOException */ private static Properties loadPreConfiguration(URL from, String un, char[] pw) throws IOException { Reject.ifNull(from, "URL is null"); URLConnection con = from.openConnection(); if (StringUtils.isNotBlank(un)) { String s = un + ":" + Util.toString(pw); LoginUtil.clear(pw); String base64 = "Basic " + Base64.encodeBytes(s.getBytes("UTF-8")); con.setRequestProperty("Authorization", base64); } con.setConnectTimeout(1000 * URL_CONNECT_TIMEOUT_SECONDS); con.setReadTimeout(1000 * URL_CONNECT_TIMEOUT_SECONDS); con.connect(); InputStream in = con.getInputStream(); try { return loadPreConfiguration(in); } finally { try { in.close(); } catch (Exception e) { } } }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getBlockchainInfo() { try {/*from w ww. ja v a2 s .c o m*/ //double btcRate = getGoldCoinValueBTC(); Double btcRate = 0.0; Object result = getGoldCoinValueBTC(); if (result == null) return null; else btcRate = (Double) result; final URL URL = new URL("https://blockchain.info/ticker"); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); //Add Bitcoin information rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(String.format("%.8f", btcRate).replace(",", ".")), "pubapi.cryptsy.com")); final JSONObject head = new JSONObject(content.toString()); for (final Iterator<String> i = head.keys(); i.hasNext();) { final String currencyCode = i.next(); final JSONObject o = head.getJSONObject(currencyCode); double gldInCurrency = o.getDouble("15m") * btcRate; final String rate = String.format("%.8f", gldInCurrency); //o.optString("15m", null); if (rate != null) rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(rate.replace(",", ".")), URL.getHost())); } return rates; } finally { if (reader != null) reader.close(); } } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Double getGoldCoinValueLTC() { Date date = new Date(); long now = date.getTime(); if ((now < (lastLitecoinValueCheck + 10 * 60)) && lastLitecoinValue > 0.0) return lastLitecoinValue; //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double ltcRate = 0.0;/*from w w w . j a v a 2 s .c o m*/ String currencyCryptsy = "LTC"; String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=marketdata"; try { // final String currencyCode = currencies[i]; final URL URLCryptsy = new URL(urlCryptsy); final URLConnection connectionCryptsy = URLCryptsy.openConnection(); connectionCryptsy.setConnectTimeout(TIMEOUT_MS); connectionCryptsy.setReadTimeout(TIMEOUT_MS); connectionCryptsy.connect(); final StringBuilder contentCryptsy = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024)); IOUtils.copy(reader, contentCryptsy); final JSONObject head = new JSONObject(contentCryptsy.toString()); JSONObject returnObject = head.getJSONObject("return"); JSONObject markets = returnObject.getJSONObject("markets"); JSONObject GLD = markets.getJSONObject("GLD"); Double lastTrade = GLD.getDouble("lasttradeprice"); //String euros = String.format("%.7f", lastTrade); // Fix things like 3,1250 //euros = euros.replace(",", "."); //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost())); if (currencyCryptsy.equalsIgnoreCase("LTC")) ltcRate = lastTrade; lastLitecoinValue = ltcRate; lastLitecoinValueCheck = now; } finally { if (reader != null) reader.close(); } return ltcRate; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:org.kde.necessitas.ministro.MinistroActivity.java
public static double downloadVersionXmlFile(Context c, boolean checkOnly) { if (!isOnline(c)) return -1; try {/*w w w .j a v a 2 s .c o m*/ DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder = factory.newDocumentBuilder(); Document dom = null; Element root = null; URLConnection connection = getVersionUrl(c).openConnection(); connection.setConnectTimeout(CONNECTION_TIMEOUT); connection.setReadTimeout(READ_TIMEOUT); dom = builder.parse(connection.getInputStream()); root = dom.getDocumentElement(); root.normalize(); double version = Double.valueOf(root.getAttribute("latest")); if (MinistroService.instance().getVersion() >= version) return MinistroService.instance().getVersion(); if (checkOnly) return version; String supportedFeatures = null; if (root.hasAttribute("features")) supportedFeatures = root.getAttribute("features"); connection = getLibsXmlUrl(c, version + deviceSupportedFeatures(supportedFeatures)).openConnection(); File file = new File(MinistroService.instance().getVersionXmlFile()); file.delete(); FileOutputStream outstream = new FileOutputStream(MinistroService.instance().getVersionXmlFile()); InputStream instream = connection.getInputStream(); byte[] tmp = new byte[2048]; int downloaded; while ((downloaded = instream.read(tmp)) != -1) outstream.write(tmp, 0, downloaded); outstream.close(); MinistroService.instance().refreshLibraries(false); return version; } catch (ClientProtocolException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (ParserConfigurationException e) { e.printStackTrace(); } catch (IllegalStateException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return -1; }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getLitecoinChartsOld() { final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the BTC rate around for a bit Double ltcRate = getGoldCoinValueLTC(); Double btcRate = 0.0;// ww w .jav a2s. c o m try { String currencies[] = { "USD", "BTC" };//, "RUR"}; String urls[] = { "https://btc-e.com/api/2/14/ticker", "https://btc-e.com/api/2/10/ticker", "https://btc-e.com/api/2/ltc_rur/ticker" }; for (int i = 0; i < currencies.length; ++i) { final String currencyCode = currencies[i]; final URL URL = new URL(urls[i]); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg") * ltcRate; String euros = String.format("%.7f", avg); // Fix things like 3,1250 euros = euros.replace(",", "."); rates.put(currencyCode, new ExchangeRate(currencyCode, Utils.toNanoCoins(euros), URL.getHost())); if (currencyCode.equalsIgnoreCase("BTC")) btcRate = avg; } finally { if (reader != null) reader.close(); } } // Handle LTC/EUR special since we have to do maths final URL URL = new URL("https://btc-e.com/api/2/btc_eur/ticker"); final URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); final StringBuilder content = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connection.getInputStream(), 1024)); IOUtils.copy(reader, content); final JSONObject head = new JSONObject(content.toString()); JSONObject ticker = head.getJSONObject("ticker"); Double avg = ticker.getDouble("avg"); // This is bitcoins priced in euros. We want GLD! avg *= btcRate; String s_avg = String.format("%.8f", avg).replace(',', '.'); rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), URL.getHost())); //Add LTC information s_avg = String.format("%.8f", ltcRate); rates.put("LTC", new ExchangeRate("LTC", Utils.toNanoCoins(s_avg.replace(",", ".")), URL.getHost())); } finally { if (reader != null) reader.close(); } return rates; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }
From source file:de.schildbach.wallet.goldcoin.ExchangeRatesProvider.java
private static Object getGoldCoinValueBTC() { Date date = new Date(); long now = date.getTime(); if ((now < (lastBitcoinValueCheck + 10 * 60)) && lastBitcoinValue > 0.0) return lastBitcoinValue; //final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the LTC rate around for a bit Double btcRate = 0.0;/* www. j av a 2 s . com*/ String currencyCryptsy = "BTC"; String urlCryptsy2 = "http://pubapi.cryptsy.com/api.php?method=marketdata"; String urlCryptsy = "http://pubapi.cryptsy.com/api.php?method=singlemarketdata&marketid=30"; try { // final String currencyCode = currencies[i]; final URL URLCryptsy = new URL(urlCryptsy); final URLConnection connectionCryptsy = URLCryptsy.openConnection(); connectionCryptsy.setConnectTimeout(TIMEOUT_MS * 2); connectionCryptsy.setReadTimeout(TIMEOUT_MS * 2); connectionCryptsy.connect(); final StringBuilder contentCryptsy = new StringBuilder(); Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(connectionCryptsy.getInputStream(), 1024)); IOUtils.copy(reader, contentCryptsy); final JSONObject head = new JSONObject(contentCryptsy.toString()); JSONObject returnObject = head.getJSONObject("return"); JSONObject markets = returnObject.getJSONObject("markets"); JSONObject GLD = markets.getJSONObject("GLD"); JSONArray recenttrades = GLD.getJSONArray("recenttrades"); double btcTraded = 0.0; double gldTraded = 0.0; for (int i = 0; i < recenttrades.length(); ++i) { JSONObject trade = (JSONObject) recenttrades.get(i); btcTraded += trade.getDouble("total"); gldTraded += trade.getDouble("quantity"); } Double averageTrade = btcTraded / gldTraded; //Double lastTrade = GLD.getDouble("lasttradeprice"); //String euros = String.format("%.7f", averageTrade); // Fix things like 3,1250 //euros = euros.replace(",", "."); //rates.put(currencyCryptsy, new ExchangeRate(currencyCryptsy, Utils.toNanoCoins(euros), URLCryptsy.getHost())); if (currencyCryptsy.equalsIgnoreCase("BTC")) btcRate = averageTrade; lastBitcoinValue = btcRate; lastBitcoinValueCheck = now; } finally { if (reader != null) reader.close(); } return btcRate; } catch (final IOException x) { x.printStackTrace(); } catch (final JSONException x) { x.printStackTrace(); } return null; }