List of usage examples for java.io BufferedReader read
public int read(char cbuf[], int off, int len) throws IOException
From source file:com.enjoyxstudy.selenium.autoexec.ResultIndexHtmlWriter.java
/** * *///from w w w. j a v a 2 s .c om public ResultIndexHtmlWriter() { try { // read template BufferedReader reader = new BufferedReader( new InputStreamReader(this.getClass().getResourceAsStream(TEMPLATE_FILE_NAME), "UTF-8")); try { StringBuilder builder = new StringBuilder(); char[] buf = new char[BUF_SIZE]; int bufSize = 0; while ((bufSize = reader.read(buf, 0, BUF_SIZE)) != -1) { builder.append(buf, 0, bufSize); } templateText = builder.toString(); } finally { reader.close(); } } catch (IOException e) { log.error("Error Can't write result index.html", e); throw new RuntimeException(e); } }
From source file:UTF8.java
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try {/*ww w. j ava2 s. c o m*/ BufferedReader reader = req.getReader(); res.setContentType("text/html; charset=UTF-8"); PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "UTF8"), true); // Read and write 4K chars at a time // (Far more efficient than reading and writing a line at a time) char[] buf = new char[4 * 1024]; // 4Kchar buffer int len; while ((len = reader.read(buf, 0, buf.length)) != -1) { out.write(buf, 0, len); } out.flush(); } catch (Exception e) { getServletContext().log(e, "Problem filtering page to UTF-8"); } }
From source file:com.metaparadigm.jsonrpc.JSONRPCServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ClassCastException { // Find the JSONRPCBridge for this session or create one // if it doesn't exist HttpSession session = request.getSession(); JSONRPCBridge json_bridge = null;// w ww . j a va 2s . com json_bridge = (JSONRPCBridge) session.getAttribute("JSONRPCBridge"); if (json_bridge == null) { // Only create a new bridge if not disabled in config if (!auto_session_bridge) { // Use the global bridge only, and don't set on session. json_bridge = JSONRPCBridge.getGlobalBridge(); if (json_bridge.isDebug()) log.info("Using global bridge."); } else { json_bridge = new JSONRPCBridge(); session.setAttribute("JSONRPCBridge", json_bridge); if (json_bridge.isDebug()) log.info("Created a bridge for this session."); } } // Encode using UTF-8, although We are actually ASCII clean as // all unicode data is JSON escaped using backslash u. This is // less data efficient for foreign character sets but it is // needed to support naughty browsers such as Konqueror and Safari // which do not honour the charset set in the response response.setContentType("text/plain;charset=utf-8"); OutputStream out = response.getOutputStream(); // Decode using the charset in the request if it exists otherwise // use UTF-8 as this is what all browser implementations use. // The JSON-RPC-Java JavaScript client is ASCII clean so it // although here we can correctly handle data from other clients // that do not escape non ASCII data String charset = request.getCharacterEncoding(); if (charset == null) charset = "UTF-8"; BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset)); // Read the request CharArrayWriter data = new CharArrayWriter(); char buf[] = new char[buf_size]; int ret; while ((ret = in.read(buf, 0, buf_size)) != -1) data.write(buf, 0, ret); if (json_bridge.isDebug()) log.fine("recieve: " + data.toString()); // Process the request JSONObject json_req = null; JSONRPCResult json_res = null; try { json_req = new JSONObject(data.toString()); json_res = json_bridge.call(new Object[] { request }, json_req); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } // Write the response if (json_bridge.isDebug()) log.fine("send: " + json_res.toString()); byte[] bout = json_res.toString().getBytes("UTF-8"); if (keepalive) { response.setIntHeader("Content-Length", bout.length); } out.write(bout); out.flush(); out.close(); }
From source file:org.betaconceptframework.astroboa.console.security.ResourceApiProxy.java
private String getBody(HttpServletRequest httpServletRequest) throws Exception { BufferedReader bufferedReader = null; StringBuilder stringBuilder = new StringBuilder(); try {//from w w w. j a v a2s . com bufferedReader = httpServletRequest.getReader(); char[] buffer = new char[4 * 1024]; // 4 KB char buffer int len; while ((len = bufferedReader.read(buffer, 0, buffer.length)) != -1) { stringBuilder.append(buffer, 0, len); } } catch (IOException e) { throw e; } finally { if (bufferedReader != null) { try { bufferedReader.close(); } catch (IOException e) { throw e; } } } return stringBuilder.toString(); }
From source file:com.oneops.boo.BooConfigInterpolator.java
private String readFileToString(File inputFile) throws IOException { BufferedReader bufrdr = new BufferedReader(new FileReader(inputFile)); StringWriter strWr = new StringWriter(); BufferedWriter wr = new BufferedWriter(strWr); try {/*from w w w. j a v a 2 s . c om*/ char[] copyBuffer = new char[1024]; int readChars; do { readChars = bufrdr.read(copyBuffer, 0, 1024); if (readChars != -1) { boolean addNewLine = false; for (int charIndex = 0; charIndex < readChars; charIndex++) { char thisChar = copyBuffer[charIndex]; if (thisChar == '\n') { // Append the newline to the output. Add // another newline before the next character. wr.append('\n'); addNewLine = true; } else { if (addNewLine) { wr.append('\n'); addNewLine = false; } wr.append(thisChar); } } } } while (readChars != -1); } finally { bufrdr.close(); wr.close(); } return strWr.toString(); }
From source file:flex.messaging.services.http.proxy.ResponseFilter.java
protected void writeResponseAsString(InputStream inStream, int length, ProxyContext context) throws IOException { char[] tmp = new char[RESPONSE_CHUNK]; //int i = 0;/*from w w w.j ava2 s . c om*/ StringBuffer sb = new StringBuffer(length < 0 ? 16 : length); BufferedInputStream bufferedIn = new BufferedInputStream(inStream); String charset = context.getHttpMethod().getResponseCharSet(); bufferedIn.mark(4); // Check for BOM as InputStreamReader does not strip BOM in all cases. boolean hasBOM = false; int read = bufferedIn.read(); if (read > 0) { // UTF-8 BOM is EF BB BF if (0xEF == (read & 0xFF)) { read = bufferedIn.read(); if (0xBB == (read & 0xFF)) { read = bufferedIn.read(); if (0xBF == (read & 0xFF)) { hasBOM = true; charset = "UTF-8"; } } } // UTF-16 Little Endian BOM is FF FE // UTF-32 Little Endian BOM is FF FE 00 00 else if (0xFF == (read & 0xFF)) { read = bufferedIn.read(); if (0xFE == (read & 0xFF)) { hasBOM = true; charset = "UTF16-LE"; // Check two more bytes incase we have UTF-32 bufferedIn.mark(2); read = bufferedIn.read(); if (0x00 == (read & 0xFF)) { read = bufferedIn.read(); if (0x00 == (read & 0xFF)) { charset = "UTF32-LE"; } else { bufferedIn.reset(); } } else { bufferedIn.reset(); } } } // UTF-16 Big Endian BOM is FE FF else if (0xFE == (read & 0xFF)) { read = bufferedIn.read(); if (0xFF == (read & 0xFF)) { hasBOM = true; charset = "UTF16-BE"; } } // UTF-32 Big Endian BOM is 00 00 FE FF else if (0x00 == (read & 0xFF)) { read = bufferedIn.read(); if (0x00 == (read & 0xFF)) { read = bufferedIn.read(); if (0xFE == (read & 0xFF)) { read = bufferedIn.read(); if (0xFF == (read & 0xFF)) { hasBOM = true; charset = "UTF32-BE"; } } } } // If we didn't find a BOM, all bytes should contribute to the content if (!hasBOM) bufferedIn.reset(); } BufferedReader reader = new BufferedReader(new InputStreamReader(bufferedIn, charset)); int charactersRead = -1; while ((charactersRead = reader.read(tmp, 0, tmp.length)) >= 0) { sb.append(new String(tmp, 0, charactersRead)); } context.setResponse(sb.toString()); }
From source file:com.orange.mmp.api.ws.jsonrpc.MMPJsonRpcServlet.java
@Override public void service(HttpServletRequest request, HttpServletResponse response) throws IOException { ExecutionContext executionContext = ExecutionContext.newInstance(request); executionContext.setName("JSON-RCP Request"); executionContext.executionStart();/*from w ww . jav a 2 s. c om*/ String requestInfo = ""; try { // Use protected method in case someone wants to override it JSONRPCBridge json_bridge = findBridge(request); // Encode using UTF-8, although We are actually ASCII clean as // all unicode data is JSON escaped using backslash u. This is // less data efficient for foreign character sets but it is // needed to support naughty browsers such as Konqueror and Safari // which do not honour the charset set in the response response.setContentType("application/json"); response.setCharacterEncoding(Constants.DEFAULT_ENCODING); OutputStream out = response.getOutputStream(); // Decode using the charset in the request if it exists otherwise // use UTF-8 as this is what all browser implementations use. // The JSON-RPC-Java JavaScript client is ASCII clean so it // although here we can correctly handle data from other clients // that do not escape non ASCII data String charset = request.getCharacterEncoding(); if (charset == null) { charset = Constants.DEFAULT_ENCODING; } String receiveString = null; // Test HTTP GET if (request.getQueryString() != null) { String id = request.getParameter(HTTP_PARAM_ID); if (id != null) { executionContext.setApiName(id); StringBuilder receiveStringBuilder = new StringBuilder("{\"id\":").append(id) .append(",\"method\":\""); String method = request.getParameter(HTTP_PARAM_METHOD); // Get params if (method != null) { executionContext.setMethodName(method); receiveStringBuilder.append(method); String param = request.getParameter(HTTP_PARAM_PARAM); // There is parameters if (param != null) { receiveStringBuilder.append("\",\"params\":").append(param).append("}"); } // Empty params else { receiveStringBuilder.append("\",\"params\":[]}"); } } // Default method (list API) else { receiveStringBuilder.append("system.listMethods\",\"params\":[]}"); } // Set JSON-RPC call string receiveString = receiveStringBuilder.toString(); //Trace request executionContext.setName("JSON-RCP Request: " + receiveString); } } // Test HTTP POST if (receiveString == null) { BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset)); // Read the request CharArrayWriter data = new CharArrayWriter(); char buf[] = new char[4096]; int ret; while ((ret = in.read(buf, 0, 4096)) != -1) { data.write(buf, 0, ret); } receiveString = data.toString(); requestInfo = receiveString; } // Process the request JSONObject json_req; JSONRPCResult json_res; try { json_req = new JSONObject(receiveString); json_res = json_bridge.call(new Object[] { request, response }, json_req); } catch (JSONException e) { json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE); } String sendString = json_res.toString(); // Write the response byte[] bout = sendString.getBytes(Constants.DEFAULT_ENCODING); // if the request header says that the browser can take gzip compressed // output, then gzip the output // but only if the response is large enough to warrant it and if the // resultant compressed output is // actually smaller. String ae = request.getHeader("accept-encoding"); if (ae != null && ae.indexOf("gzip") != -1) { byte[] gzippedOut = gzip(bout); // if gzip didn't actually help, abort if (bout.length > gzippedOut.length) { bout = gzippedOut; response.addHeader("Content-Encoding", "gzip"); } } response.setIntHeader("Content-Length", bout.length); out.write(bout); } catch (Throwable error) { //Catch exception throw new IOExceptionWithCause("Error during request processing", error); } finally { executionContext.executionStop(); printMonitoredRequest(requestInfo); executionContext.close(); } }
From source file:com.esri.gpt.control.arcims.ServletConnectorProxy.java
/** * Fully reads the characters from an InputStream. * /*from ww w . j a va2 s .c o m*/ * @param strm * the InputStream * @return the characters read * @throws IOException * if an exception occurs */ private String readInputCharacters(InputStream inputStream) throws IOException { StringBuffer sb = new StringBuffer(); InputStreamReader ir = null; BufferedReader br = null; try { char cbuf[] = new char[2048]; int n = 0; int nLen = cbuf.length; String sEncoding = "UTF-8"; ir = new InputStreamReader(inputStream, sEncoding); br = new BufferedReader(ir); while ((n = br.read(cbuf, 0, nLen)) > 0) { sb.append(cbuf, 0, n); } } finally { try { if (br != null) br.close(); } catch (Exception ef) { } try { if (ir != null) ir.close(); } catch (Exception ef) { } } return sb.toString(); }
From source file:com.esri.gpt.server.csw.client.CswClient.java
/** * Fully reads the characters from an input stream. * @param stream the input stream//from w w w . ja v a 2s. com * @param charset the encoding of the input stream * @return the characters read * @throws IOException if an exception occurs */ private String readCharacters(InputStream stream, String charset) throws IOException { StringBuffer sb = new StringBuffer(); BufferedReader br = null; InputStreamReader ir = null; try { if ((charset == null) || (charset.trim().length() == 0)) charset = "UTF-8"; char cbuf[] = new char[4096]; int n = 0; int nLen = cbuf.length; ir = new InputStreamReader(stream, charset); br = new BufferedReader(ir); while ((n = br.read(cbuf, 0, nLen)) >= 0) sb.append(cbuf, 0, n); } finally { try { if (br != null) br.close(); } catch (Exception ef) { } try { if (ir != null) ir.close(); } catch (Exception ef) { } } return sb.toString(); }
From source file:it.flavianopetrocchi.jpdfbookmarks.JPdfBookmarks.java
private byte[] askUserPassword() { //avoid the use of strings when dealing with passwords they remain in memomory Console cons;/*from w ww . j a v a 2s . com*/ char[] passwdChars = null; byte[] passwdBytes = null; if ((cons = System.console()) != null && (passwdChars = cons.readPassword("[%s:]", Res.getString("PASSWORD"))) != null) { passwdBytes = Ut.arrayOfCharsToArrayOfBytes(passwdChars); Arrays.fill(passwdChars, ' '); } else { out.print("[" + Res.getString("LABEL_PASSWORD") + "]"); out.flush(); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); passwdChars = new char[MAX_PASSWORD_LEN]; try { int charsRead = in.read(passwdChars, 0, MAX_PASSWORD_LEN); //remove \r and \n from the password for (int i = charsRead - 1; i >= 0; i--) { if (passwdChars[i] == '\r' || passwdChars[i] == '\n') { charsRead--; } else { break; } } char[] trimmedPasswd = Arrays.copyOf(passwdChars, charsRead); Arrays.fill(passwdChars, ' '); passwdBytes = Ut.arrayOfCharsToArrayOfBytes(trimmedPasswd); Arrays.fill(trimmedPasswd, ' '); } catch (IOException ex) { } } return passwdBytes; }