List of usage examples for java.io InputStreamReader read
public int read(java.nio.CharBuffer target) throws IOException
From source file:com.vuze.android.remote.rpc.RestJsonClient.java
public static Map<?, ?> connect(String id, String url, Map<?, ?> jsonPost, Header[] headers, UsernamePasswordCredentials creds, boolean sendGzip) throws RPCException { long readTime = 0; long connSetupTime = 0; long connTime = 0; int bytesRead = 0; if (DEBUG_DETAILED) { Log.d(TAG, id + "] Execute " + url); }//from w w w. java 2s. c o m long now = System.currentTimeMillis(); long then; Map<?, ?> json = Collections.EMPTY_MAP; try { URI uri = new URI(url); int port = uri.getPort(); BasicHttpParams basicHttpParams = new BasicHttpParams(); HttpProtocolParams.setUserAgent(basicHttpParams, "Vuze Android Remote"); DefaultHttpClient httpclient; if ("https".equals(uri.getScheme())) { httpclient = MySSLSocketFactory.getNewHttpClient(port); } else { httpclient = new DefaultHttpClient(basicHttpParams); } //AndroidHttpClient.newInstance("Vuze Android Remote"); // This doesn't set the "Authorization" header!? httpclient.getCredentialsProvider().setCredentials(new AuthScope(null, -1), creds); // Prepare a request object HttpRequestBase httpRequest = jsonPost == null ? new HttpGet(uri) : new HttpPost(uri); // IllegalArgumentException if (creds != null) { byte[] toEncode = (creds.getUserName() + ":" + creds.getPassword()).getBytes(); String encoding = Base64Encode.encodeToString(toEncode, 0, toEncode.length); httpRequest.setHeader("Authorization", "Basic " + encoding); } if (jsonPost != null) { HttpPost post = (HttpPost) httpRequest; String postString = JSONUtils.encodeToJSON(jsonPost); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "] Post: " + postString); } AbstractHttpEntity entity = (sendGzip && Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getCompressedEntity(postString) : new StringEntity(postString); post.setEntity(entity); post.setHeader("Accept", "application/json"); post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=UTF-8"); } if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) { setupRequestFroyo(httpRequest); } if (headers != null) { for (Header header : headers) { httpRequest.setHeader(header); } } // Execute the request HttpResponse response; then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connSetupTime = (then - now); now = then; } httpclient.setHttpRequestRetryHandler(new HttpRequestRetryHandler() { @Override public boolean retryRequest(IOException e, int i, HttpContext httpContext) { if (i < 2) { return true; } return false; } }); response = httpclient.execute(httpRequest); then = System.currentTimeMillis(); if (AndroidUtils.DEBUG_RPC) { connTime = (then - now); now = then; } HttpEntity entity = response.getEntity(); // XXX STATUSCODE! StatusLine statusLine = response.getStatusLine(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "StatusCode: " + statusLine.getStatusCode()); } if (entity != null) { long contentLength = entity.getContentLength(); if (contentLength >= Integer.MAX_VALUE - 2) { throw new RPCException("JSON response too large"); } // A Simple JSON Response Read InputStream instream = (Build.VERSION.SDK_INT >= Build.VERSION_CODES.FROYO) ? getUngzippedContent(entity) : entity.getContent(); InputStreamReader isr = new InputStreamReader(instream, "utf8"); StringBuilder sb = null; BufferedReader br = null; // JSONReader is 10x slower, plus I get more OOM errors.. :( // final boolean useStringBuffer = contentLength > (4 * 1024 * 1024) ? false // : DEFAULT_USE_STRINGBUFFER; final boolean useStringBuffer = DEFAULT_USE_STRINGBUFFER; if (useStringBuffer) { // Setting capacity saves StringBuffer from going through many // enlargeBuffers, and hopefully allows toString to not make a copy sb = new StringBuilder(contentLength > 512 ? (int) contentLength + 2 : 512); } else { if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, "Using BR. ContentLength = " + contentLength); } br = new BufferedReader(isr, 8192); br.mark(32767); } try { // 9775 files on Nexus 7 (~2,258,731 bytes) // fastjson 1.1.46 (String) : 527- 624ms // fastjson 1.1.39 (String) : 924-1054ms // fastjson 1.1.39 (StringBuilder): 1227-1463ms // fastjson 1.1.39 (BR) : 2233-2260ms // fastjson 1.1.39 (isr) : 2312ms // GSON 2.2.4 (String) : 1539-1760ms // GSON 2.2.4 (BufferedReader) : 2646-3060ms // JSON-SMART 1.3.1 (String) : 572- 744ms (OOMs more often than fastjson) if (useStringBuffer) { char c[] = new char[8192]; while (true) { int read = isr.read(c); if (read < 0) { break; } sb.append(c, 0, read); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); if (DEBUG_DETAILED) { if (sb.length() > 2000) { Log.d(TAG, id + "] " + sb.substring(0, 2000) + "..."); } else { Log.d(TAG, id + "] " + sb.toString()); } } bytesRead = sb.length(); readTime = (then - now); now = then; } json = JSONUtils.decodeJSON(sb.toString()); //json = JSONUtilsGSON.decodeJSON(sb.toString()); } else { //json = JSONUtils.decodeJSON(isr); json = JSONUtils.decodeJSON(br); //json = JSONUtilsGSON.decodeJSON(br); } } catch (Exception pe) { // StatusLine statusLine = response.getStatusLine(); if (statusLine != null && statusLine.getStatusCode() == 409) { throw new RPCException(response, "409"); } try { String line; if (useStringBuffer) { line = sb.subSequence(0, Math.min(128, sb.length())).toString(); } else { br.reset(); line = br.readLine().trim(); } isr.close(); if (AndroidUtils.DEBUG_RPC) { Log.d(TAG, id + "]line: " + line); } Header contentType = entity.getContentType(); if (line.startsWith("<") || line.contains("<html") || (contentType != null && contentType.getValue().startsWith("text/html"))) { // TODO: use android strings.xml throw new RPCException(response, "Could not retrieve remote client location information. The most common cause is being on a guest wifi that requires login before using the internet."); } } catch (IOException ignore) { } Log.e(TAG, id, pe); if (statusLine != null) { String msg = statusLine.getStatusCode() + ": " + statusLine.getReasonPhrase() + "\n" + pe.getMessage(); throw new RPCException(msg, pe); } throw new RPCException(pe); } finally { closeOnNewThread(useStringBuffer ? isr : br); } if (AndroidUtils.DEBUG_RPC) { // Log.d(TAG, id + "]JSON Result: " + json); } } } catch (RPCException e) { throw e; } catch (Throwable e) { Log.e(TAG, id, e); throw new RPCException(e); } if (AndroidUtils.DEBUG_RPC) { then = System.currentTimeMillis(); Log.d(TAG, id + "] conn " + connSetupTime + "/" + connTime + "ms. Read " + bytesRead + " in " + readTime + "ms, parsed in " + (then - now) + "ms"); } return json; }
From source file:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java
/** * Returns the resource uri or <code>null</code> if no resource id and/or path * could be found on the specified document. This method is intended to serve * as a utility method when importing resources. * /*from w ww.j a v a 2 s. c o m*/ * @param site * the resource uri * @param contentUrl * location of the resource file * @return the resource uri */ protected ResourceURI loadResourceURI(Site site, URL contentUrl) throws IOException { InputStream is = null; InputStreamReader reader = null; try { is = new BufferedInputStream(contentUrl.openStream()); reader = new InputStreamReader(is); CharBuffer buf = CharBuffer.allocate(1024); reader.read(buf); String s = new String(buf.array()); s = s.replace('\n', ' '); Matcher m = resourceHeaderRegex.matcher(s); if (m.matches()) { long version = ResourceUtils.getVersion(m.group(4)); return new ResourceURIImpl(m.group(1), site, m.group(3), m.group(2), version); } return null; } finally { if (reader != null) reader.close(); IOUtils.closeQuietly(is); } }
From source file:org.computeforcancer.android.client.Monitor.java
/** * Determines ProcessID corresponding to given process name * @param processName name of process, according to output of "ps" * @return process id, according to output of "ps" */// w w w. j ava2 s . c om private Integer getPidForProcessName(String processName) { int count; char[] buf = new char[1024]; StringBuffer sb = new StringBuffer(); //run ps and read output try { Process p = Runtime.getRuntime().exec("ps"); p.waitFor(); InputStreamReader isr = new InputStreamReader(p.getInputStream()); while ((count = isr.read(buf)) != -1) { sb.append(buf, 0, count); } } catch (Exception e) { if (Logging.ERROR) Log.e(Logging.TAG, "Exception: " + e.getMessage()); return null; } String[] processLinesAr = sb.toString().split("\n"); if (processLinesAr.length < 2) { if (Logging.ERROR) Log.e(Logging.TAG, "getPidForProcessName(): ps output has less than 2 lines, failure!"); return null; } // figure out what index PID has String[] headers = processLinesAr[0].split("[\\s]+"); Integer PidIndex = 1; for (int x = 0; x < headers.length; x++) { if (headers[x].equals("PID")) { PidIndex = x; continue; } } if (Logging.DEBUG) Log.d(Logging.TAG, "getPidForProcessName(): PID at index: " + PidIndex + " for output: " + processLinesAr[0]); Integer pid = null; for (int y = 1; y < processLinesAr.length; y++) { Boolean found = false; String[] comps = processLinesAr[y].split("[\\s]+"); for (String arg : comps) { if (arg.equals(processName)) { if (Logging.DEBUG) Log.d(Logging.TAG, "getPidForProcessName(): " + processName + " found in line: " + y); found = true; } } if (found) { try { pid = Integer.parseInt(comps[PidIndex]); if (Logging.ERROR) Log.d(Logging.TAG, "getPidForProcessName(): pid: " + pid); } catch (NumberFormatException e) { if (Logging.ERROR) Log.e(Logging.TAG, "getPidForProcessName(): NumberFormatException for " + comps[PidIndex] + " at index: " + PidIndex); } continue; } } // if not happen in ps output, not running?! if (pid == null) if (Logging.ERROR) Log.d(Logging.TAG, "getPidForProcessName(): " + processName + " not found in ps output!"); // Find required pid return pid; }
From source file:org.testeditor.fixture.swt.SwtBotFixture.java
/** * Creates a thread to log the content of the input stream. This thread is * started after creation./*from w w w. jav a 2s. c om*/ * * @param inputStream * to piped to the logger. * @param errorStream * if true the logger uses the error level in other cases info. */ private void createAndRunLoggerOnStream(final InputStream inputStream, final boolean errorStream) { new Thread(new Runnable() { @Override public void run() { char[] cbuf = new char[8192]; int len = -1; try { InputStreamReader reader = new InputStreamReader(inputStream, CHARSET_UTF_8); while ((len = reader.read(cbuf)) > 0) { if (errorStream) { LOGGER.error(new String(cbuf, 0, len)); } else { LOGGER.info(new String(cbuf, 0, len)); } } } catch (IOException e) { LOGGER.debug("Error reading remote Process Stream", e); } } }).start(); }
From source file:com.zoffcc.applications.aagtl.HTMLDownloader.java
public void loadCookies() { String[] ret = new String[2]; // make dirs/*from w ww. ja v a 2 s.c o m*/ File dir1 = new File(this.main_aagtl.main_dir + "/config"); dir1.mkdirs(); // load cookies from file File cookie_file = new File(this.main_aagtl.main_dir + "/config/cookie.txt"); FileInputStream fIn = null; InputStreamReader isr = null; char[] inputBuffer = new char[255]; Writer writer = new StringWriter(); String data = null; try { fIn = new FileInputStream(cookie_file); isr = new InputStreamReader(fIn); int n = 0; while ((n = isr.read(inputBuffer)) != -1) { writer.write(inputBuffer, 0, n); } data = writer.toString(); } catch (Exception e) { e.printStackTrace(); System.out.println("loadCookies: Exception1"); return; } finally { try { isr.close(); fIn.close(); } catch (NullPointerException e2) { System.out.println("loadCookies: Exception2"); return; } catch (IOException e) { System.out.println("loadCookies: Exception3"); e.printStackTrace(); return; } } if (cookie_jar == null) { // cookie_jar = new CookieStore(); return; } else { cookie_jar.clear(); } // Log.d("load cookie:", "->" + String.valueOf(data)); // [[version: 0][name: ASP.NET_SessionId] // [value: cyuoctxrwio1x13vivqzlxgi][domain: www.geocaching.com] // [path: /][expiry: null], [version: 0][name: userid] // [value: 8a72e55f-419c-4da7-8de3-7813a3fda9c7][domain: // www.geocaching.com] // [path: /][expiry: Tue Apr 26 15:41:14 Europe/Belgrade 2011]] if (data.length() > 1) { // check for multpile cookies if (data.startsWith("[[")) { // strip [ and ] at begin and end of string data = data.substring(1, data.length() - 1); String s3 = "\\], \\["; String[] a3 = data.split(s3); String data_cookie; for (int j3 = 0; j3 < a3.length; j3++) { data_cookie = a3[j3]; if (j3 == 0) { data_cookie = data_cookie + "]"; } else { data_cookie = "[" + data_cookie; } // System.out.println("parsing cookie #" + j3 + ": " + // data_cookie); String s2 = "]"; String[] a = data_cookie.split(s2); String x = null; String c1, c2 = null; String c_name = null, c_value = null, c_domain = null, c_path = null; String c_version = null; BasicClientCookie this_cookie = null; for (int j = 0; j < a.length; j++) { x = a[j].replace("[", "").trim(); c1 = x.split(":")[0]; c2 = x.split(":")[1].substring(1); // Log.d("load cookie:", "->" + String.valueOf(c1)); // Log.d("load cookie:", "->" + String.valueOf(c2)); if (c1.matches("name") == true) { // Log.d("name:", "->" + String.valueOf(c1)); c_name = c2; } else if (c1.matches("value") == true) { c_value = c2; } else if (c1.matches("domain") == true) { c_domain = c2; } else if (c1.matches("path") == true) { c_path = c2; } else if (c1.matches("version") == true) { c_version = c2; } } this_cookie = new BasicClientCookie(c_name, c_value); this_cookie.setDomain(c_domain); this_cookie.setPath(c_path); // System.out.println("created cookie: ->" + // String.valueOf(this_cookie)); this.cookie_jar.addCookie(this_cookie); } } // single cookie else { String s2 = "]"; String[] a = data.split(s2); String x = null; String c1, c2 = null; String c_name = null, c_value = null, c_domain = null, c_path = null; String c_version = null; BasicClientCookie this_cookie = null; for (int j = 0; j < a.length; j++) { x = a[j].replace("[", "").trim(); c1 = x.split(":")[0]; c2 = x.split(":")[1].substring(1); // Log.d("load cookie:", "->" + String.valueOf(c1)); // Log.d("load cookie:", "->" + String.valueOf(c2)); if (c1.matches("name") == true) { // Log.d("name:", "->" + String.valueOf(c1)); c_name = c2; } else if (c1.matches("value") == true) { c_value = c2; } else if (c1.matches("domain") == true) { c_domain = c2; } else if (c1.matches("path") == true) { c_path = c2; } else if (c1.matches("version") == true) { c_version = c2; } } this_cookie = new BasicClientCookie(c_name, c_value); this_cookie.setDomain(c_domain); this_cookie.setPath(c_path); // System.out.println("created cookie: ->" + // String.valueOf(this_cookie)); this.cookie_jar.addCookie(this_cookie); } } return; }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
/** * //w w w . j a v a 2 s .com * * @param stream * * @param encoding * * @return * * @throws IOException * IO */ static String inputStreamToString(InputStream stream, String encoding) throws IOException { char buffer[] = new char[4096]; StringBuilder sb = new StringBuilder(); InputStreamReader isr = new InputStreamReader(stream, "utf-8"); // For // now, // assume // utf-8 // to // work // around // server // bug int nRead = 0; while ((nRead = isr.read(buffer)) >= 0) { sb.append(buffer, 0, nRead); } isr.close(); return sb.toString(); }
From source file:fur.shadowdrake.minecraft.InstallPanel.java
private void showReadMe() throws NetworkException { StringBuilder sb = new StringBuilder(); while (true) { result = ftpClient.openDataChannel((ActionEvent e) -> { if (e.getID() == FtpClient.FTP_OK) { try { InputStreamReader isr; char[] buffer = new char[4096]; int n; isr = new InputStreamReader(((Socket) e.getSource()).getInputStream()); while (true) { n = isr.read(buffer); if (n < 0) { break; }//from w w w . j a v a2s.c o m sb.append(buffer, 0, n); } } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "Readme", ex); log.println("Faild retrieve readme."); ftpClient.closeDataChannel(); } } }); switch (result) { case FtpClient.FTP_OK: downloadSize = ftpClient.retr(workingPack + "/readme", (ActionEvent e) -> { ftpClient.closeDataChannel(); EventQueue.invokeLater(() -> { ReadmeBox rb = new ReadmeBox(parentFrame, true, sb.toString()); rb.setVisible(true); }); }); if (downloadSize >= 0) { } else { switch (downloadSize) { case FtpClient.FTP_NODATA: log.println( "Oops! Server's complaining about missing data channel, although I've opened it."); ftpClient.abandonDataChannel(); return; default: ftpClient.abandonDataChannel(); } } break; case FtpClient.FTP_TIMEOUT: if (reconnect()) { continue; } } break; } }
From source file:fur.shadowdrake.minecraft.InstallPanel.java
private List<String> fetchUpdateInstructions(Pack pack) throws NetworkException { final Semaphore semaphore = new Semaphore(0); final StringBuffer sb = new StringBuffer(); while (true) { result = ftpClient.openDataChannel((ActionEvent e) -> { if (e.getID() == FtpClient.FTP_OK) { try { InputStreamReader isr; int n; char[] buffer = new char[4096]; isr = new InputStreamReader(((Socket) e.getSource()).getInputStream()); while (true) { n = isr.read(buffer); if (n < 0) { break; }/* ww w. j a v a 2 s . co m*/ sb.append(buffer, 0, n); } } catch (IOException ex) { Logger.getLogger(InstallPanel.class.getName()).log(Level.SEVERE, "Download", ex); log.println("Faild to save file."); ftpClient.closeDataChannel(); } } }); switch (result) { case FtpClient.FTP_OK: int status = ftpClient.uins(pack, (ActionEvent e) -> { ftpClient.closeDataChannel(); semaphore.release(); }); switch (status) { case FtpClient.FTP_OK: try { semaphore.acquire(); } catch (InterruptedException ex) { return null; } break; case FtpClient.FTP_NODATA: log.println("Oops! Server's complaining about missing data channel, although I've opened it."); ftpClient.abandonDataChannel(); return null; default: ftpClient.abandonDataChannel(); return null; } break; case FtpClient.FTP_TIMEOUT: if (reconnect()) { continue; } else { return null; } default: return null; } break; } return Arrays.asList(sb.toString().split("\n")); }
From source file:org.kalypso.optimize.SceJob.java
private void startSCEOptimization(final SceIOHandler sceIO, final ISimulationMonitor monitor) throws SimulationException { InputStreamReader inStream = null; InputStreamReader errStream = null; // FIXME: too much copy/paste from ProcessHelper; we can probably use process helper instead! ProcessControlThread procCtrlThread = null; try {/*from w ww .jav a 2 s. co m*/ final String[] commands = new String[] { m_sceExe.getAbsolutePath() }; final Process process = Runtime.getRuntime().exec(commands, null, m_sceDir); final long lTimeOut = 1000l * 60l * 15l;// 15 minutes procCtrlThread = new ProcessControlThread(process, lTimeOut); procCtrlThread.start(); final StringBuffer outBuffer = new StringBuffer(); final StringBuffer errBuffer = new StringBuffer(); final Writer inputWriter = new PrintWriter(process.getOutputStream(), false); inStream = new InputStreamReader(process.getInputStream()); errStream = new InputStreamReader(process.getErrorStream()); final int stepMax = m_autoCalibration.getOptParameter().getMaxN(); while (true) { final int step = sceIO.getStep(); monitor.setProgress(100 * step / (stepMax + 1)); if (step > stepMax) { final String monitorMsg = String.format( "Optimierungsrechnung abgeschlossen, Ergebnisauswertung", step + 1, stepMax + 1); monitor.setMessage(monitorMsg); } else { final String monitorMsg = String.format("Optimierungsrechnung %d von %d", step + 1, stepMax + 1); monitor.setMessage(monitorMsg); } if (inStream.ready()) { final char buffer[] = new char[100]; final int bufferC = inStream.read(buffer); outBuffer.append(buffer, 0, bufferC); } if (errStream.ready()) { final char buffer[] = new char[100]; final int bufferC = errStream.read(buffer); errBuffer.append(buffer, 0, bufferC); } if (monitor.isCanceled()) { process.destroy(); procCtrlThread.endProcessControl(); return; } try { process.exitValue(); break; } catch (final IllegalThreadStateException e) { final OptimizeMonitor subMonitor = new OptimizeMonitor(monitor); sceIO.handleStreams(outBuffer, errBuffer, inputWriter, subMonitor); } Thread.sleep(100); } procCtrlThread.endProcessControl(); } catch (final IOException e) { e.printStackTrace(); throw new SimulationException("Fehler beim Ausfuehren", e); } catch (final InterruptedException e) { e.printStackTrace(); throw new SimulationException("beim Ausfuehren unterbrochen", e); } finally { IOUtils.closeQuietly(inStream); IOUtils.closeQuietly(errStream); if (procCtrlThread != null && procCtrlThread.procDestroyed()) { throw new SimulationException("beim Ausfuehren unterbrochen", new ProcessTimeoutException("Timeout bei der Abarbeitung der Optimierung")); } } }