List of usage examples for java.net URLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:ch.njol.skript.Updater.java
/** * Gets the changelogs and release dates of the newest versions * //from ww w.j a v a 2 s.c om * @param sender */ final static void getChangelogs(final CommandSender sender) { InputStream in = null; InputStreamReader r = null; try { final URLConnection conn = new URL(RSSURL).openConnection(); conn.setRequestProperty("User-Agent", "Skript/v" + Skript.getVersion() + " (by Njol)"); // Bukkit returns a 403 (forbidden) if no user agent is set in = conn.getInputStream(); r = new InputStreamReader(in, conn.getContentEncoding() == null ? "UTF-8" : conn.getContentEncoding()); final XMLEventReader reader = XMLInputFactory.newInstance().createXMLEventReader(r); infos.clear(); VersionInfo current = null; outer: while (reader.hasNext()) { XMLEvent e = reader.nextEvent(); if (e.isStartElement()) { final String element = e.asStartElement().getName().getLocalPart(); if (element.equalsIgnoreCase("title")) { final String name = reader.nextEvent().asCharacters().getData().trim(); for (final VersionInfo i : infos) { if (name.equals(i.name)) { current = i; continue outer; } } current = null; } else if (element.equalsIgnoreCase("description")) { if (current == null) continue; final StringBuilder cl = new StringBuilder(); while ((e = reader.nextEvent()).isCharacters()) cl.append(e.asCharacters().getData()); current.changelog = "- " + StringEscapeUtils.unescapeHtml("" + cl).replace("<br>", "") .replace("<p>", "").replace("</p>", "").replaceAll("\n(?!\n)", "\n- "); } else if (element.equalsIgnoreCase("pubDate")) { if (current == null) continue; synchronized (RFC2822) { // to make FindBugs shut up current.date = new Date( RFC2822.parse(reader.nextEvent().asCharacters().getData()).getTime()); } } } } } catch (final IOException e) { stateLock.writeLock().lock(); try { state = UpdateState.CHECK_ERROR; error.set(ExceptionUtils.toString(e)); Skript.error(sender, m_check_error.toString()); } finally { stateLock.writeLock().unlock(); } } catch (final Exception e) { Skript.error(sender, m_internal_error.toString()); Skript.exception(e, "Unexpected error while checking for a new version of Skript"); stateLock.writeLock().lock(); try { state = UpdateState.CHECK_ERROR; error.set(e.getClass().getSimpleName() + ": " + e.getLocalizedMessage()); } finally { stateLock.writeLock().unlock(); } } finally { if (in != null) { try { in.close(); } catch (final IOException e) { } } if (r != null) { try { r.close(); } catch (final IOException e) { } } } }
From source file:com.dynamobi.network.DynamoNetworkUdr.java
/** * Fetches the master metadata.json file on a given repository and returns the * data as a JSONObject.//from w ww .j a va2s . c om */ private static JSONObject downloadMetadata(String repo) throws SQLException { if (repo == null) return null; try { // Grab master metadata.json URL u = new URL(repo + "/metadata.json"); URLConnection uc = u.openConnection(); uc.setConnectTimeout(1000); // generous max-of-1-second to connect uc.setReadTimeout(1000); uc.connect(); InputStreamReader in = new InputStreamReader(uc.getInputStream()); BufferedReader buff = new BufferedReader(in); StringBuffer sb = new StringBuffer(); String line = null; do { line = buff.readLine(); if (line != null) sb.append(line); } while (line != null); String data = sb.toString(); // Parse it JSONParser parser = new JSONParser(); JSONObject ob = (JSONObject) parser.parse(data); return ob; } catch (SocketTimeoutException e) { throw new SQLException(URL_TIMEOUT); } catch (MalformedURLException e) { throw new SQLException("Bad URL."); } catch (IOException e) { throw new SQLException(URL_TIMEOUT); } catch (ParseException e) { throw new SQLException("Could not parse data from URL."); } }
From source file:mas.MAS_VLDB.java
/** * @param args the command line arguments */// w w w. j a v a 2s . com // for old version public static void getData(int startIdx, int endIdx) { try { Properties prop = new Properties(); prop.setProperty("AppId", "1df63064-efad-4bbd-a797-1131499b7728"); prop.setProperty("ResultObjects", "publication"); prop.setProperty("DomainID", "22"); prop.setProperty("SubDomainID", "2"); prop.setProperty("YearStart", "2001"); prop.setProperty("YearEnd", "2010"); prop.setProperty("StartIdx", startIdx + ""); prop.setProperty("EndIdx", endIdx + ""); String url_org = "http://academic.research.microsoft.com/json.svc/search"; String url_str = generateURL(url_org, prop); URL url = new URL(url_str); URLConnection yc = url.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(yc.getInputStream())); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println(inputLine); } in.close(); } catch (MalformedURLException ex) { Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex); } catch (IOException ex) { Logger.getLogger(MAS_VLDB.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.clavain.alerts.Methods.java
public static boolean sendTTSMessage(String message, String mobile_nr) { boolean retval = false; try {/*from www . j a v a 2 s . c om*/ if (p.getProperty("tts.provider").equals("smsflatrate")) { String key = p.getProperty("smsflatrate.key"); String gw = p.getProperty("smsflatrate.ttsgw"); String msg = URLEncoder.encode(message); URL url = new URL("http://smsflatrate.net/schnittstelle.php?key=" + key + "&to=" + mobile_nr + "&voice=Dave&repeat=2&rate=1&type=" + gw + "&text=" + msg); URLConnection conn = url.openConnection(); // open the stream and put it into BufferedReader BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream())); String inputLine; String resp = ""; while ((inputLine = br.readLine()) != null) { resp = inputLine; } //conn.getContent(); if (resp.trim().equals("100")) { retval = true; } } else if (p.getProperty("tts.provider").equals("script")) { List<String> commands = new ArrayList<String>(); // add global timeout script commands.add(p.getProperty("tts.script")); commands.add(mobile_nr); commands.add(message); ProcessBuilder pb = new ProcessBuilder(commands).redirectErrorStream(true); logger.info("tts.script - Running: " + commands); Process p = pb.start(); Integer rv = p.waitFor(); } } catch (Exception ex) { retval = false; logger.error("sendTTSMessage Error: " + ex.getLocalizedMessage()); } return retval; }
From source file:net.pms.configuration.DownloadPlugins.java
public static ArrayList<DownloadPlugins> downloadList() { ArrayList<DownloadPlugins> res = new ArrayList<>(); if (!configuration.getExternalNetwork()) { // Do not try to get the plugin list if there is no // external network. return res; }// ww w . ja va2 s . c o m try { URL u = new URL(PLUGIN_LIST_URL); URLConnection connection = u.openConnection(); connection.setConnectTimeout(5000); connection.setReadTimeout(5000); BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream())); parse_list(res, in, false); File test = new File(configuration.getPluginDirectory() + File.separator + PLUGIN_TEST_FILE); if (test.exists()) { in = new BufferedReader(new InputStreamReader(new FileInputStream(test))); parse_list(res, in, true); } } catch (IOException e) { } return res; }
From source file:com.feathercoin.wallet.feathercoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getFeathercoinCharts() { final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the BTC rate around for a bit Double btcRate = 0.0;//w w w . ja va2s . c o m try { /* String currencies[] = {"USD", "BTC", "RUR"}; String urls[] = {"https://btc-e.com/api/2/ftc_btc/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"); String euros = String.format("%.4f", 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 FTC/USD special since we have to do maths URL URL = null; try { URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); 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 feathercoins priced in bitcoins btcRate = avg; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } // Handle FTC/USD special since we have to do maths URL = null; URL = new URL("https://btc-e.com/api/2/btc_usd/ticker"); connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); content = new StringBuilder(); 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 dollars. We want FTC! avg *= btcRate; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } // Handle FTC/BTC special since we have to do maths URL = new URL("https://btc-e.com/api/2/btc_eur/ticker"); connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); content = new StringBuilder(); 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 FTC! avg *= btcRate; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), 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:com.impetus.kundera.loader.PersistenceXMLLoader.java
/** * Reads the persistence xml content into an object graph and validates it * against the related xsd schema.//from w w w . j av a 2 s . c om * * @param pathToPersistenceXml * path to the persistence.xml file * @return parsed persistence xml as object graph * @throws InvalidConfigurationException * if the file could not be parsed or is not valid against the * schema */ private static Document getDocument(URL pathToPersistenceXml) throws InvalidConfigurationException { InputStream is = null; Document xmlRootNode = null; try { if (pathToPersistenceXml != null) { URLConnection conn = pathToPersistenceXml.openConnection(); conn.setUseCaches(false); // avoid JAR locking on Windows and // Tomcat. is = conn.getInputStream(); } if (is == null) { throw new IOException("Failed to obtain InputStream from url: " + pathToPersistenceXml); } xmlRootNode = parseDocument(is); validateDocumentAgainstSchema(xmlRootNode); } catch (IOException e) { throw new InvalidConfigurationException(e); } finally { if (is != null) { try { is.close(); } catch (IOException ex) { log.warn("Input stream could not be closed after parsing persistence.xml, caused by: {}", ex); } } } return xmlRootNode; }
From source file:de.schildbach.wallet.worldcoin.ExchangeRatesProvider.java
private static Map<String, ExchangeRate> getworldcoinCharts() { final Map<String, ExchangeRate> rates = new TreeMap<String, ExchangeRate>(); // Keep the BTC rate around for a bit Double btcRate = 0.0;//from ww w . j a v a 2s. c o m try { /* String currencies[] = {"USD", "BTC", "RUR"}; String urls[] = {"https://btc-e.com/api/2/ftc_btc/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"); String euros = String.format("%.4f", 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 WDC/USD special since we have to do maths URL URL = null; try { URL = new URL("https://btc-e.com/api/2/ftc_btc/ticker"); } catch (MalformedURLException e) { e.printStackTrace(); } URLConnection connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); 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 worldcoins priced in bitcoins btcRate = avg; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("BTC", new ExchangeRate("BTC", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } // Handle WDC/USD special since we have to do maths URL = null; URL = new URL("https://btc-e.com/api/2/btc_usd/ticker"); connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); content = new StringBuilder(); 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 dollars. We want WDC! avg *= btcRate; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("USD", new ExchangeRate("USD", Utils.toNanoCoins(s_avg), URL.getHost())); } finally { if (reader != null) reader.close(); } // Handle WDC/BTC special since we have to do maths URL = new URL("https://btc-e.com/api/2/btc_eur/ticker"); connection = URL.openConnection(); connection.setConnectTimeout(TIMEOUT_MS); connection.setReadTimeout(TIMEOUT_MS); connection.connect(); content = new StringBuilder(); 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 FTC! avg *= btcRate; String s_avg = String.format("%.4f", avg).replace(',', '.'); rates.put("EUR", new ExchangeRate("EUR", Utils.toNanoCoins(s_avg), 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:io.bitsquare.common.util.Utilities.java
public static String readTextFileFromServer(String url, String userAgent) throws IOException { URLConnection connection = URI.create(url).toURL().openConnection(); connection.setDoOutput(true);//from w ww. jav a 2 s . c o m connection.setUseCaches(false); connection.setConnectTimeout((int) TimeUnit.SECONDS.toMillis(10)); connection.addRequestProperty("User-Agent", userAgent); connection.connect(); try (InputStream inputStream = connection.getInputStream()) { return CharStreams.toString(new InputStreamReader(inputStream, Charsets.UTF_8)); } catch (IOException e) { e.printStackTrace(); throw e; } }
From source file:com.ibuildapp.romanblack.CataloguePlugin.utils.Utils.java
/** * download file url and save it//w w w.ja va 2 s . co m * * @param url */ public static String downloadFile(String url) { int BYTE_ARRAY_SIZE = 1024; int CONNECTION_TIMEOUT = 30000; int READ_TIMEOUT = 30000; // downloading cover image and saving it into file try { URL imageUrl = new URL(URLDecoder.decode(url)); URLConnection conn = imageUrl.openConnection(); conn.setConnectTimeout(CONNECTION_TIMEOUT); conn.setReadTimeout(READ_TIMEOUT); BufferedInputStream bis = new BufferedInputStream(conn.getInputStream()); File resFile = new File( Statics.moduleCachePath + File.separator + com.appbuilder.sdk.android.Utils.md5(url)); if (!resFile.exists()) { resFile.createNewFile(); } FileOutputStream fos = new FileOutputStream(resFile); int current = 0; byte[] buf = new byte[BYTE_ARRAY_SIZE]; Arrays.fill(buf, (byte) 0); while ((current = bis.read(buf, 0, BYTE_ARRAY_SIZE)) != -1) { fos.write(buf, 0, current); Arrays.fill(buf, (byte) 0); } bis.close(); fos.flush(); fos.close(); Log.d("", ""); return resFile.getAbsolutePath(); } catch (SocketTimeoutException e) { return null; } catch (IllegalArgumentException e) { return null; } catch (Exception e) { return null; } }