List of usage examples for java.io InputStreamReader read
public int read() throws IOException
From source file:com.ericsson.research.trap.spi.transports.ApacheClientHttpTransport.java
@Override protected void internalConnect() throws TrapException { this.updateConfig(); // Make a request to get a new TransportID if (!this.isClientConfigured()) { this.logger.debug( "HTTP Transport not properly configured... Unless autoconfigure is enabled (and another transport succeeds) this transport will not be available."); this.setState(TrapTransportState.ERROR); return;/*from www. j ava2 s . c om*/ } try { this.running = true; HttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = this.openGet(this.connectUrl); HttpResponse response = httpclient.execute(httpget); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream is = null; InputStreamReader isr = null; try { is = entity.getContent(); isr = new InputStreamReader(is, Charset.forName("UTF-8")); StringWriter sr = new StringWriter(); int ch = 0; while ((ch = isr.read()) != -1) sr.write(ch); String rawUrl = sr.toString(); String urlBase = this.connectUrl.toString(); if (urlBase.endsWith("/")) urlBase += rawUrl; else urlBase += "/" + rawUrl; this.activeUrl = URI.create(urlBase); // Start a new thread for polling Thread t = new Thread(this); t.setDaemon(true); t.start(); this.postclient = new DefaultHttpClient(); // Change state to connected this.setState(TrapTransportState.CONNECTED); } finally { if (is != null) is.close(); if (isr != null) isr.close(); } } } catch (Exception e) { this.setState(TrapTransportState.ERROR); throw new TrapException(e); } }
From source file:ut.ee.mh.WebServer.java
private void handleLocationRequest(DefaultHttpServerConnection serverConnection, HttpRequest request, RequestLine requestLine) throws HttpException, IOException { BasicHttpEntityEnclosingRequest enclosingRequest = new BasicHttpEntityEnclosingRequest( request.getRequestLine());/*from w ww. j av a 2 s .c om*/ serverConnection.receiveRequestEntity(enclosingRequest); InputStream input = enclosingRequest.getEntity().getContent(); InputStreamReader reader = new InputStreamReader(input); StringBuffer form = new StringBuffer(); while (reader.ready()) { form.append((char) reader.read()); } String password = form.substring(form.indexOf("=") + 1); if (password.equals(mSharedPreferences.getString(FileSharingService.PREFS_PASSWORD, ""))) { HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 302, "Found"); response.addHeader("Location", "/"); response.addHeader("Set-Cookie", "id=" + createCookie()); response.setEntity(new StringEntity(getHTMLHeader() + "Success!" + getHTMLFooter())); serverConnection.sendResponseHeader(response); serverConnection.sendResponseEntity(response); } else { HttpResponse response = new BasicHttpResponse(new HttpVersion(1, 1), 401, "Unauthorized"); response.setEntity( new StringEntity(getHTMLHeader() + "<p>Login failed.</p>" + getLoginForm() + getHTMLFooter())); serverConnection.sendResponseHeader(response); serverConnection.sendResponseEntity(response); } }
From source file:be.docarch.odt2braille.PEF.java
private boolean validatePEF(File pefFile) throws IOException, MalformedURLException { logger.entering("PEF", "validatePEF"); if (validator.validate(pefFile.toURI().toURL())) { logger.info("pef valid"); return true; } else {//from w ww. j a va 2 s.com String message = "pef invalid!\nMessages returned by the validator:\n"; InputStreamReader report = new InputStreamReader(validator.getReportStream()); int c; while ((c = report.read()) != -1) { message += (char) c; } logger.log(Level.SEVERE, message); return false; } }
From source file:org.andrewberman.sync.PDFDownloader.java
/** * Uploads and downloads the bibtex library file, to synchronize library * changes.//from w w w .j av a 2 s . c om */ void syncBibTex() throws Exception { String base = baseDir.getCanonicalPath() + sep; itemMax = -1; final File bibFile = new File(base + username + ".bib"); // final File md5File = new File(base + ".md5s.txt"); final File dateFile = new File(base + "sync_info.txt"); // Check the MD5s, if the .md5s.txt file exists. long bibModified = bibFile.lastModified(); long lastDownload = 0; boolean download = true; boolean upload = true; if (dateFile.exists()) { String fileS = readFile(dateFile); String[] props = fileS.split("\n"); for (String prop : props) { String[] keyval = prop.split("="); if (keyval[0].equals("date")) { lastDownload = Long.valueOf(keyval[1]); } } } if (lastDownload >= bibModified) { upload = false; } boolean uploadSuccess = false; if (bibFile.exists() && uploadNewer && upload) { BufferedReader br = null; try { status("Uploading BibTex file..."); FilePartSource fsrc = new FilePartSource(bibFile); FilePart fp = new FilePart("file", fsrc); br = new BufferedReader(new FileReader(bibFile)); StringBuffer sb = new StringBuffer(); String s; while ((s = br.readLine()) != null) { sb.append(s + "\n"); } String str = sb.toString(); final Part[] parts = new Part[] { new StringPart("btn_bibtex", "Import BibTeX file..."), new StringPart("to_read", "2"), new StringPart("tag", ""), new StringPart("private", "t"), new StringPart("update_allowed", "t"), new StringPart("update_id", "cul-id"), new StringPart("replace_notes", "t"), new StringPart("replace_tags", "t"), fp }; waitOrExit(); PostMethod filePost = new PostMethod(BASE_URL + "/profile/" + username + "/import_do"); try { filePost.setRequestEntity(new MultipartRequestEntity(parts, filePost.getParams())); httpclient.executeMethod(filePost); String response = filePost.getResponseBodyAsString(); // System.out.println(response); uploadSuccess = true; System.out.println("Bibtex upload success!"); } finally { filePost.releaseConnection(); } } catch (Exception e) { e.printStackTrace(); } finally { if (br != null) br.close(); } } if (download || upload) { status("Downloading BibTeX file..."); String pageURL = BASE_URL + "bibtex/user/" + username + ""; FileWriter fw = new FileWriter(bibFile); try { GetMethod get = new GetMethod(pageURL); httpclient.executeMethod(get); InputStreamReader read = new InputStreamReader(get.getResponseBodyAsStream()); int c; while ((c = read.read()) != -1) { waitOrExit(); fw.write(c); } read.close(); } finally { fw.close(); } } // Store the checksums. if (uploadSuccess) { // if (fileChecksum == null) // { // fileChecksum = getMd5(bibFile); // remoteChecksum = get(BASE_URL + "bibtex/user/" + username + "?md5=true"); // } // String md5S = fileChecksum + "\n" + remoteChecksum; // writeFile(md5File, md5S); String dateS = "date=" + Calendar.getInstance().getTimeInMillis(); writeFile(dateFile, dateS); } }
From source file:tsuboneSystem.original.util.TsuboneSystemUtil.java
/** * Download?/* ww w . j a v a2s . c om*/ * * @param filePath * @param fileName * @return null * @author Hiroaki * * */ public static void downloadCommon(String filePath, String fileName) { // ??? FileInputStream fis = null; InputStreamReader isr = null; HttpServletResponse res = ResponseUtil.getResponse(); // ???? OutputStream os = null; OutputStreamWriter osw = null; try { // ?File? File file = new File(filePath); if (!file.exists() || !file.isFile()) { // ??????? } // ?? res.setContentType("application/octet-stream"); res.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("Windows-31J"), "ISO-8859-1")); // ???? fis = new FileInputStream(file); isr = new InputStreamReader(fis, "ISO-8859-1"); // ????? os = res.getOutputStream(); osw = new OutputStreamWriter(os, "ISO-8859-1"); // IO??? int i; while ((i = isr.read()) != -1) { osw.write(i); } } catch (FileNotFoundException e) { // ? } catch (UnsupportedEncodingException e) { // ? } catch (IOException e) { // ? } finally { try { // ? if (osw != null) { osw.close(); } if (os != null) { os.close(); } if (isr != null) { isr.close(); } if (fis != null) { fis.close(); } } catch (IOException e) { // ? } } }
From source file:org.pentaho.di.baserver.utils.web.HttpConnectionHelper.java
protected String getContent(HttpMethod method, String encoding) throws IOException { String body;//from w ww .j a va 2 s .co m InputStreamReader inputStreamReader; if (!Const.isEmpty(encoding)) { inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream(), encoding); } else { inputStreamReader = new InputStreamReader(method.getResponseBodyAsStream()); } StringBuilder bodyBuffer = new StringBuilder(); int c; while ((c = inputStreamReader.read()) != -1) { bodyBuffer.append((char) c); } inputStreamReader.close(); body = bodyBuffer.toString(); return body; }
From source file:cuanto.api.CuantoConnector.java
/** * This is here to substitute for HttpMethod.getResponseBodyAsString(), which logs an annoying error message each time * it's called.// w w w . j a v a2s . co m * * @param method The method for which to get the response. * @return The full response body as a String. * @throws IOException If something bad happened. */ private String getResponseBodyAsString(HttpMethod method) throws IOException { InputStreamReader reader = new InputStreamReader(method.getResponseBodyAsStream()); StringWriter writer = new StringWriter(); int in; while ((in = reader.read()) != -1) { writer.write(in); } reader.close(); return writer.toString(); }
From source file:nmtysh.android.test.speedtest.SpeedTestActivity.java
private void runHttpURLConnection() { final String url = urlEdit.getText().toString(); if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) { list.add("URL error!"); adapter.notifyDataSetChanged();//from w w w .j a v a 2 s. c om return; } task = new AsyncTask<Void, Integer, Void>() { long startTime; ProgressDialog progress; // ?? @Override protected void onPreExecute() { super.onPreExecute(); progress = new ProgressDialog(SpeedTestActivity.this); progress.setMessage(getString(R.string.progress_message)); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setIndeterminate(false); progress.setCancelable(true); progress.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { task.cancel(true); } }); progress.setMax(10); progress.setProgress(0); progress.show(); startTime = System.currentTimeMillis(); } // ??? @Override protected Void doInBackground(Void... params) { // 10????? for (int i = 0; i < 10; i++) { HttpURLConnection connection = null; InputStreamReader in = null; // BufferedReader br = null; try { connection = (HttpURLConnection) (new URL(url)).openConnection(); connection.setRequestMethod("GET"); connection.connect(); in = new InputStreamReader(connection.getInputStream()); // br = new BufferedReader(in); // while (br.readLine() != null) { long len = 0; while (in.read() != -1) { len++; } Log.i("HttpURLConnection", len + " Bytes"); } catch (IOException e) { } finally { /* * if (br != null) { try { br.close(); } catch * (IOException e) { } br = null; } */ if (in != null) { try { in.close(); } catch (IOException e) { } in = null; } if (connection != null) { connection.disconnect(); connection = null; } } publishProgress(i + 1); // Dos???????? try { Thread.sleep(1000); } catch (InterruptedException e) { } } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); if (progress == null) { return; } progress.setProgress(values[0]); } // @Override protected void onPostExecute(Void result) { long endTime = System.currentTimeMillis(); // progress.cancel(); progress = null; list.add("HttpURLConnection:" + url + " " + (endTime - startTime) + "msec/10" + " " + (endTime - startTime) / 10 + "msec"); adapter.notifyDataSetChanged(); } @Override protected void onCancelled() { super.onCancelled(); progress.dismiss(); progress = null; } }.execute(); }
From source file:org.openqa.selenium.server.SeleniumDriverResourceHandler.java
/** * extract the posted data from an incoming request, stripping away a piggybacked data * * @param req request/*ww w . ja v a 2 s . c om*/ * @param sessionId session id * @param uniqueId unique id * @return a string containing the posted data (with piggybacked log info stripped) * @throws IOException */ private String readPostedData(HttpRequest req, String sessionId, String uniqueId) throws IOException { // if the request was sent as application/x-www-form-urlencoded, we can get the decoded data // right away... // we do this because it appears that Safari likes to send the data back as // application/x-www-form-urlencoded // even when told to send it back as application/xml. So in short, this function pulls back the // data in any // way it can! if (req.getParameter("postedData") != null) { return req.getParameter("postedData"); } InputStream is = req.getInputStream(); StringBuffer sb = new StringBuffer(); InputStreamReader r = new InputStreamReader(is, "UTF-8"); int c; while ((c = r.read()) != -1) { sb.append((char) c); } String postedData = sb.toString(); // we check here because, depending on the Selenium Core version you have, specifically the // selenium-testrunner.js, // the data could be sent back directly or as URL-encoded for the parameter "postedData" (see // above). Because // firefox and other browsers like to send it back as application/xml (opposite of Safari), we // need to be prepared // to decode the data ourselves. Also, we check for the string starting with the key because in // the rare case // someone has an outdated version selenium-testrunner.js, which, until today (3/25/2007) sent // back the data // *un*-encoded, we'd like to be as flexible as possible. if (postedData.startsWith("postedData=")) { postedData = postedData.substring(11); postedData = URLDecoder.decode(postedData, "UTF-8"); } return postedData; }
From source file:nmtysh.android.test.speedtest.SpeedTestActivity.java
private void runHttpClient() { final String url = urlEdit.getText().toString(); if (url == null || (!url.startsWith("http://") && !url.startsWith("https://"))) { list.add("URL error!"); adapter.notifyDataSetChanged();/*from ww w. ja v a 2 s .c o m*/ return; } task = new AsyncTask<Void, Integer, Void>() { long startTime; ProgressDialog progress; // ?? @Override protected void onPreExecute() { super.onPreExecute(); progress = new ProgressDialog(SpeedTestActivity.this); progress.setMessage(getString(R.string.progress_message)); progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); progress.setIndeterminate(false); progress.setCancelable(true); progress.setOnCancelListener(new OnCancelListener() { @Override public void onCancel(DialogInterface dialog) { task.cancel(true); } }); progress.setMax(10); progress.setProgress(0); progress.show(); startTime = System.currentTimeMillis(); } // ??? @Override protected Void doInBackground(Void... params) { // 10????? for (int i = 0; i < 10; i++) { HttpClient client = new DefaultHttpClient(); InputStreamReader in = null; // BufferedReader br = null; try { HttpGet get = new HttpGet(url); HttpResponse response = client.execute(get); if (response.getStatusLine().getStatusCode() < 400) { in = new InputStreamReader(response.getEntity().getContent()); // br = new BufferedReader(in); // while (br.readLine() != null) { long len = 0; while (in.read() != -1) { len++; } Log.i("HttpClient", len + " Bytes"); } } catch (IOException e) { } finally { /* * if (br != null) { try { br.close(); } catch * (IOException e) { } br = null; } */ if (in != null) { try { in.close(); } catch (IOException e) { } in = null; } // ? client.getConnectionManager().shutdown(); client = null; } publishProgress(i + 1); // Dos???????? try { Thread.sleep(1000); } catch (InterruptedException e) { } } return null; } @Override protected void onProgressUpdate(Integer... values) { super.onProgressUpdate(values); if (progress == null) { return; } progress.setProgress(values[0]); } // @Override protected void onPostExecute(Void result) { long endTime = System.currentTimeMillis(); // progress.cancel(); progress = null; list.add("HttpClient:" + url + " " + (endTime - startTime) + "msec/10" + " " + (endTime - startTime) / 10 + "msec"); adapter.notifyDataSetChanged(); } @Override protected void onCancelled() { super.onCancelled(); progress.dismiss(); progress = null; } }.execute(); }