List of usage examples for java.net URLConnection getInputStream
public InputStream getInputStream() throws IOException
From source file:com.ebay.jetstream.application.dataflows.VisualDataFlow.java
public ByteBuffer getAsByteArray(URL url) throws IOException { URLConnection connection = url.openConnection(); InputStream in = connection.getInputStream(); int contentLength = connection.getContentLength(); ByteArrayOutputStream tmpOut; if (contentLength != -1) { tmpOut = new ByteArrayOutputStream(contentLength); } else {//from w w w .j av a 2 s.co m tmpOut = new ByteArrayOutputStream(16384); } byte[] buf = new byte[BUF]; while (true) { int len = in.read(buf); if (len == -1) { break; } tmpOut.write(buf, 0, len); } in.close(); tmpOut.close(); byte[] array = tmpOut.toByteArray(); return ByteBuffer.wrap(array); }
From source file:ee.ria.xroad.common.conf.globalconf.ConfigurationLocation.java
/** * @return the input stream acquired by connecting to the download url. * @throws Exception if an error occurs//from w ww. ja v a 2s.c o m */ public InputStream getInputStream() throws Exception { try { URLConnection connection = getDownloadURLConnection(downloadURL); return connection.getInputStream(); } catch (IOException e) { throw new CodedException(X_HTTP_ERROR, e); } }
From source file:com.nominanuda.web.mvc.URLStreamer.java
public HttpResponse handle(HttpRequest request) throws IOException { URL url = getURL(request);//from w w w .j a va2 s .c om URLConnection conn = url.openConnection(); conn.connect(); int len = conn.getContentLength(); InputStream is = conn.getInputStream(); String ce = conn.getContentEncoding(); String ct = determineContentType(url, conn); if (len < 0) { byte[] content = ioHelper.readAndClose(is); is = new ByteArrayInputStream(content); len = content.length; } StatusLine statusline = httpCoreHelper.statusLine(SC_OK); HttpResponse resp = new BasicHttpResponse(statusline); resp.setEntity(new InputStreamEntity(is, len)); httpCoreHelper.setContentType(resp, ct); httpCoreHelper.setContentLength(resp, len);//TODO not needed ?? if (ce != null) { httpCoreHelper.setContentEncoding(resp, ce); } return resp; }
From source file:com.gammalabs.wifianalyzer.vendor.model.RemoteCall.java
@Override protected RemoteResult doInBackground(String... params) { if (params == null || params.length < 1 || StringUtils.isBlank(params[0])) { return RemoteResult.EMPTY; }/* ww w .j a v a 2s .co m*/ String macAddress = params[0]; String request = String.format(MAC_VENDOR_LOOKUP, macAddress.substring(0, macAddress.length() / 2)); BufferedReader bufferedReader = null; try { URLConnection urlConnection = getURLConnection(request); bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream())); StringBuilder response = new StringBuilder(); String line; while ((line = bufferedReader.readLine()) != null) { response.append(line); } String vendorName = VendorNameUtils.cleanVendorName(response.toString().trim()); if (StringUtils.isNotBlank(vendorName)) { return new RemoteResult(macAddress, vendorName); } return RemoteResult.EMPTY; } catch (Exception e) { return RemoteResult.EMPTY; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { // ignore } } } }
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;/*w w w. j a va2s . c o m*/ 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; }
From source file:com.momoplan.pet.framework.manager.controller.GetServerController.java
@RequestMapping("/best.html") public void best(String license, HttpServletResponse response) throws Exception { long s = System.currentTimeMillis(); response.setCharacterEncoding("UTF-8"); String license_key = "license:" + license; logger.debug("license_key=" + license_key); //TODO check license String license_info = Config.publicConfig.get(license_key); logger.debug("license_info=" + license_info); logger.debug("nodeServiceUrl=" + nodeServiceUrl); URL u = new URL(nodeServiceUrl); URLConnection conn = u.openConnection(); InputStream is = conn.getInputStream(); byte[] buff = new byte[4096]; int t = 0;// www . j av a 2 s . c om ByteArrayOutputStream bos = new ByteArrayOutputStream(); while ((t = is.read(buff)) != -1) { bos.write(buff, 0, t); } String nodes = new String(bos.toByteArray()); is.close(); bos.close(); JSONObject json = new JSONObject(nodes); boolean success = json.getBoolean("success"); JSONObject rtnJson = new JSONObject(); rtnJson.put("success", success); if (success) { try { JSONArray arr = json.getJSONArray("entity"); int len = arr.length(); Map<String, Object> tmp = new HashMap<String, Object>(); tmp.put("node", ""); tmp.put("totalCount", Integer.MAX_VALUE); for (int i = 0; i < len; i++) { JSONObject node = arr.getJSONObject(i); Integer c = node.getInt("totalCount"); if (c < (Integer) tmp.get("totalCount")) { tmp.put("node", node.getString("node")); tmp.put("totalCount", c); } } logger.debug(tmp.toString()); String nodeKey = (String) tmp.get("node"); String ipHost = Config.publicConfig.get(nodeKey); String[] hostArr = ipHost.split(":"); JSONObject entity = new JSONObject(); entity.put("ip", hostArr[0]); entity.put("port", hostArr[1]); rtnJson.put("entity", entity); } catch (Exception e) { logger.error("XXXXXX", e); rtnJson.put("entity", defNode); } } else { rtnJson.put("entity", json.get("entity")); } logger.debug(nodes); long e = System.currentTimeMillis(); logger.info("license_key=" + license_key + ";license_info=" + license_info + ";rtn=" + rtnJson.toString() + " -- " + (e - s) + "ms"); response.getWriter().write(rtnJson.toString()); }
From source file:com.puppycrawl.tools.checkstyle.api.LocalizedMessageTest.java
@Test public void testBundleReloadUrlNotNull() throws IOException { ClassLoader classloader = mock(ClassLoader.class); final URLConnection mockConnection = Mockito.mock(URLConnection.class); when(mockConnection.getInputStream()).thenReturn(new ByteArrayInputStream(EMPTY_BYTE_ARRAY)); URL url = getMockUrl(mockConnection); String resource = "com/puppycrawl/tools/checkstyle/checks/coding/messages_en.properties"; when(classloader.getResource(resource)).thenReturn(url); LocalizedMessage.UTF8Control control = new LocalizedMessage.UTF8Control(); control.newBundle("com.puppycrawl.tools.checkstyle.checks.coding.messages", Locale.ENGLISH, "java.class", classloader, true);/*from w ww. j a v a2 s.c o m*/ }
From source file:mashapeautoloader.MashapeAutoloader.java
/** * @param libraryName/*from w w w .ja v a2 s . co m*/ * * Returns false if something wrong, otherwise true (API interface * already exists or just well downloaded) */ private static boolean downloadLib(String libraryName) { URL url; URLConnection urlConn; // check (or make) for apiStore directory File apiStoreDir = new File(apiStore); if (!apiStoreDir.isDirectory()) apiStoreDir.mkdir(); String javaFilePath = apiStore + libraryName + ".java"; File javaFile = new File(javaFilePath); // check if the API interface exists if (javaFile.exists()) return true; try { // download the API interface's archive url = new URL(MASHAPE_DOWNLOAD_ROOT + libraryName); urlConn = url.openConnection(); HttpURLConnection httpConn = (HttpURLConnection) urlConn; httpConn.setInstanceFollowRedirects(false); urlConn.setDoInput(true); urlConn.setDoOutput(false); urlConn.setUseCaches(false); // extract the archive stream ZipInputStream zip = new ZipInputStream(urlConn.getInputStream()); String expectedEntryName = libraryName + ".java"; while (true) { ZipEntry nextEntry = zip.getNextEntry(); if (nextEntry == null) return false; String name = nextEntry.getName(); if (name.equals(expectedEntryName)) { // save .java locally FileOutputStream javaFileStream = new FileOutputStream(javaFilePath); byte[] buf = new byte[1024]; int n; while ((n = zip.read(buf, 0, 1024)) > -1) javaFileStream.write(buf, 0, n); // compile it into .class file JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); int result = compiler.run(null, null, null, javaFilePath); System.out.println(result); return result == 0; } } } catch (Exception ex) { throw new RuntimeException(ex); } }
From source file:net.sf.zekr.engine.network.NetworkController.java
public InputStream openSteam(String uri, int timeout) throws URISyntaxException, IOException { URL url = new URL(uri); URLConnection conn = url.openConnection(getProxy(uri)); conn.setReadTimeout(timeout);//from w w w.j ava 2s. co m conn.setUseCaches(true); return conn.getInputStream(); }
From source file:com.datos.vfs.provider.url.UrlFileObject.java
/** * Determines the type of the file.// w w w. j a v a 2 s. c o m */ @Override protected FileType doGetType() throws Exception { try { // Attempt to connect & check status final URLConnection conn = url.openConnection(); final InputStream in = conn.getInputStream(); try { if (conn instanceof HttpURLConnection) { final int status = ((HttpURLConnection) conn).getResponseCode(); // 200 is good, maybe add more later... if (HttpURLConnection.HTTP_OK != status) { return FileType.IMAGINARY; } } return FileType.FILE; } finally { in.close(); } } catch (final FileNotFoundException e) { return FileType.IMAGINARY; } }