java.io.CharArrayWriter Java Examples
The following examples show how to use
java.io.CharArrayWriter.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DriverManagerTests.java From openjdk-jdk9 with GNU General Public License v2.0 | 9 votes |
/** * Create a PrintWriter and use to to send output via DriverManager.println * Validate that if you disable the writer, the output sent is not present */ @Test public void tests18() throws Exception { CharArrayWriter cw = new CharArrayWriter(); PrintWriter pw = new PrintWriter(cw); DriverManager.setLogWriter(pw); assertTrue(DriverManager.getLogWriter() == pw); DriverManager.println(results[0]); DriverManager.setLogWriter(null); assertTrue(DriverManager.getLogWriter() == null); DriverManager.println(noOutput); DriverManager.setLogWriter(pw); DriverManager.println(results[1]); DriverManager.println(results[2]); DriverManager.println(results[3]); DriverManager.setLogWriter(null); DriverManager.println(noOutput); /* * Check we do not get the output when the stream is disabled */ BufferedReader reader = new BufferedReader(new CharArrayReader(cw.toCharArray())); for (String result : results) { assertTrue(result.equals(reader.readLine())); } }
Example #2
Source File: ExtendedAccessLogValve.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { if (null != response) { Iterator<String> iter = response.getHeaders(header).iterator(); if (iter.hasNext()) { StringBuilder buffer = new StringBuilder(); boolean first = true; while (iter.hasNext()) { if (first) { first = false; } else { buffer.append(","); } buffer.append(iter.next()); } buf.append(wrap(buffer.toString())); } return ; } buf.append("-"); }
Example #3
Source File: AbstractAccessLogValve.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { String value = null; if (requestAttributesEnabled) { Object host = request.getAttribute(REMOTE_HOST_ATTRIBUTE); if (host != null) { value = host.toString(); } } if (value == null || value.length() == 0) { value = request.getRemoteHost(); } if (value == null || value.length() == 0) { value = "-"; } if (ipv6Canonical) { value = IPv6Utils.canonize(value); } buf.append(value); }
Example #4
Source File: PageDataImpl.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
private String escapeCDATA(String text) { if( text==null ) return ""; int len = text.length(); CharArrayWriter result = new CharArrayWriter(len); for (int i=0; i<len; i++) { if (((i+2) < len) && (text.charAt(i) == ']') && (text.charAt(i+1) == ']') && (text.charAt(i+2) == '>')) { // match found result.write(']'); result.write(']'); result.write('&'); result.write('g'); result.write('t'); result.write(';'); i += 2; } else { result.write(text.charAt(i)); } } return result.toString(); }
Example #5
Source File: bug8005391.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 6 votes |
public static void main(String[] args) throws Exception { int N = 10; for (int i = 0; i < N; i++) { HTMLEditorKit kit = new HTMLEditorKit(); Class c = Class.forName("javax.swing.text.html.parser.ParserDelegator"); HTMLEditorKit.Parser parser = (HTMLEditorKit.Parser) c.newInstance(); HTMLDocument doc = (HTMLDocument) kit.createDefaultDocument(); HTMLEditorKit.ParserCallback htmlReader = doc.getReader(0); parser.parse(new CharArrayReader(htmlDoc.toCharArray()), htmlReader, true); htmlReader.flush(); CharArrayWriter writer = new CharArrayWriter(1000); kit.write(writer, doc, 0, doc.getLength()); writer.flush(); String result = writer.toString(); if (!result.contains("<tt><a")) { throw new RuntimeException("The <a> and <tt> tags are swapped"); } } }
Example #6
Source File: CR6689809Test.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
@Test public final void testTransform() { try { StreamSource input = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xml")); StreamSource stylesheet = new StreamSource(getClass().getResourceAsStream("PredicateInKeyTest.xsl")); CharArrayWriter buffer = new CharArrayWriter(); StreamResult output = new StreamResult(buffer); TransformerFactory.newInstance().newTransformer(stylesheet).transform(input, output); Assert.assertEquals(buffer.toString(), "0|1|2|3", "XSLT xsl:key implementation is broken!"); // expected success } catch (Exception e) { // unexpected failure e.printStackTrace(); Assert.fail(e.toString()); } }
Example #7
Source File: LineMap.java From baratine with GNU General Public License v2.0 | 6 votes |
/** * Filter a stack trace, replacing names. */ public void printStackTrace(Throwable e, OutputStream os) { CharArrayWriter writer = new CharArrayWriter(); PrintWriter pw = new PrintWriter(writer); e.printStackTrace(pw); pw.close(); char []array = writer.toCharArray(); CharBuffer cb = filter(array); if (os != null) { byte []b = cb.toString().getBytes(); try { os.write(b, 0, b.length); } catch (IOException e1) { } } else System.out.println(cb); }
Example #8
Source File: Base64.java From ccu-historian with GNU General Public License v3.0 | 6 votes |
private static char[] readChars(final File file) { final CharArrayWriter caw = new CharArrayWriter(); try { final Reader fr = new FileReader(file); final Reader in = new BufferedReader(fr); int count; final char[] buf = new char[16384]; while ((count = in.read(buf)) != -1) { if (count > 0) { caw.write(buf, 0, count); } } in.close(); } catch (Exception e) { e.printStackTrace(); } return caw.toCharArray(); }
Example #9
Source File: JsonParserTest.java From gson with Apache License 2.0 | 6 votes |
public void testReadWriteTwoObjects() throws Exception { Gson gson = new Gson(); CharArrayWriter writer = new CharArrayWriter(); BagOfPrimitives expectedOne = new BagOfPrimitives(1, 1, true, "one"); writer.write(gson.toJson(expectedOne).toCharArray()); BagOfPrimitives expectedTwo = new BagOfPrimitives(2, 2, false, "two"); writer.write(gson.toJson(expectedTwo).toCharArray()); CharArrayReader reader = new CharArrayReader(writer.toCharArray()); JsonReader parser = new JsonReader(reader); parser.setLenient(true); JsonElement element1 = Streams.parse(parser); JsonElement element2 = Streams.parse(parser); BagOfPrimitives actualOne = gson.fromJson(element1, BagOfPrimitives.class); assertEquals("one", actualOne.stringValue); BagOfPrimitives actualTwo = gson.fromJson(element2, BagOfPrimitives.class); assertEquals("two", actualTwo.stringValue); }
Example #10
Source File: IJError.java From TrakEM2 with GNU General Public License v3.0 | 6 votes |
static public final void print(Throwable e, final boolean stdout) { StringBuilder sb = new StringBuilder("==================\nERROR:\n"); while (null != e) { CharArrayWriter caw = new CharArrayWriter(); PrintWriter pw = new PrintWriter(caw); e.printStackTrace(pw); String s = caw.toString(); if (isMacintosh()) { if (s.indexOf("ThreadDeath")>0) ;//return null; else s = fixNewLines(s); } sb.append(s); Throwable t = e.getCause(); if (e == t || null == t) break; sb.append("==> Caused by:\n"); e = t; } sb.append("==================\n"); if (stdout) Utils.log2(sb.toString()); else Utils.log(sb.toString()); }
Example #11
Source File: SSH2Holders.java From super-cloudops with Apache License 2.0 | 6 votes |
/** * Get local current user ssh authentication private key of default. * * @param host * @param user * @return * @throws Exception */ protected final char[] getDefaultLocalUserPrivateKey() throws Exception { // Check private key. File privateKeyFile = new File(USER_HOME + "/.ssh/id_rsa"); isTrue(privateKeyFile.exists(), String.format("Not found privateKey for %s", privateKeyFile)); log.warn("Fallback use local user pemPrivateKey of: {}", privateKeyFile); try (CharArrayWriter cw = new CharArrayWriter(); FileReader fr = new FileReader(privateKeyFile.getAbsolutePath())) { char[] buff = new char[256]; int len = 0; while ((len = fr.read(buff)) != -1) { cw.write(buff, 0, len); } return cw.toCharArray(); } }
Example #12
Source File: JspC.java From Tomcat7.0.67 with Apache License 2.0 | 6 votes |
protected void initWebXml() { try { if (webxmlLevel >= INC_WEBXML) { mapout = openWebxmlWriter(new File(webxmlFile)); servletout = new CharArrayWriter(); mappingout = new CharArrayWriter(); } else { mapout = null; servletout = null; mappingout = null; } if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.header")); mapout.flush(); } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.header")); mapout.flush(); } } catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; } }
Example #13
Source File: cfFile.java From openbd-core with GNU General Public License v3.0 | 6 votes |
private static boolean isCFENCODED(Reader _inFile) throws IOException { CharArrayWriter buffer = new CharArrayWriter(CFENCODE_HEADER_LEN); _inFile.mark(CFENCODE_HEADER_LEN); for (int i = 0; i < CFENCODE_HEADER_LEN; i++) { buffer.write(_inFile.read()); } if (buffer.toString().equals(CFENCODE_HEADER)) { return true; } _inFile.reset(); return false; }
Example #14
Source File: AbstractAccessLogValve.java From Tomcat8-Source-Read with MIT License | 6 votes |
@Override public void addElement(CharArrayWriter buf, Date date, Request request, Response response, long time) { Object value = null; if (null != request) { HttpSession sess = request.getSession(false); if (null != sess) { value = sess.getAttribute(header); } } else { value = "??"; } if (value != null) { if (value instanceof String) { buf.append((String) value); } else { buf.append(value.toString()); } } else { buf.append('-'); } }
Example #15
Source File: cfWDDX.java From openbd-core with GNU General Public License v3.0 | 6 votes |
public static String cfml2Wddx( cfData _input, int version ) { CharArrayWriter outChar = new CharArrayWriter( 1024 ); PrintWriter out = new PrintWriter( outChar ); if ( version > 10 ){ out.write( "<wddxPacket version='1.1'><h></h><d>" ); _input.dumpWDDX( version, out ); out.write( "</d></wddxPacket>" ); }else{ out.write( "<wddxPacket version='1.0'><header></header><data>" ); _input.dumpWDDX( version, out ); out.write( "</data></wddxPacket>" ); } out.flush(); return outChar.toString(); }
Example #16
Source File: LineMap.java From baratine with GNU General Public License v2.0 | 6 votes |
/** * Filter a stack trace, replacing names. */ public void printStackTrace(Throwable e, PrintWriter os) { CharArrayWriter writer = new CharArrayWriter(); PrintWriter pw = new PrintWriter(writer); e.printStackTrace(pw); pw.close(); char []array = writer.toCharArray(); CharBuffer cb = filter(array); if (os != null) os.print(cb.toString()); else System.out.println(cb); }
Example #17
Source File: StreamUtil.java From goclipse with Eclipse Public License 1.0 | 6 votes |
/** Reads and returns all chars from given reader until an EOF is read. * Closes reader afterwards. */ public static CharArrayWriter readAllCharsFromReader(Reader reader) throws IOException { try { final int BUFFER_SIZE = 1024; char[] buffer = new char[BUFFER_SIZE]; CharArrayWriter chars = new CharArrayWriter(); int read; while((read = reader.read(buffer)) != EOF) { chars.write(buffer, 0, read); } return chars; } finally { reader.close(); } }
Example #18
Source File: GenFileStream.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
public GenFileStream (String filename) { // What I really want to do here is: // super (byteStream = new ByteArrayOutputStream ()); // but that isn't legal. The super constructor MUST // be called before any instance variables are used. // This implementation gets around that problem. // <f49747.1> //super (tmpByteStream = new ByteArrayOutputStream ()); //byteStream = tmpByteStream; super (tmpCharArrayWriter = new CharArrayWriter()); charArrayWriter = tmpCharArrayWriter; name = filename; }
Example #19
Source File: XmlGatewayDescriptorExporterTest.java From knox with Apache License 2.0 | 5 votes |
@Test public void testXmlGatewayDescriptorStoreMissingValue() throws IOException, SAXException, ParserConfigurationException { GatewayDescriptor descriptor = GatewayDescriptorFactory.create() .addResource().addFilter().param().up().up().up(); CharArrayWriter writer = new CharArrayWriter(); GatewayDescriptorFactory.store( descriptor, "xml", writer ); String xml = writer.toString(); InputSource source = new InputSource( new StringReader( xml ) ); Document doc = XmlUtils.readXml( source ); assertThat( doc, hasXPath( "/gateway/resource/filter/param" ) ); }
Example #20
Source File: JspC.java From Tomcat8-Source-Read with MIT License | 5 votes |
protected void initWebXml() throws JasperException { try { if (webxmlLevel >= INC_WEBXML) { mapout = openWebxmlWriter(new File(webxmlFile)); servletout = new CharArrayWriter(); mappingout = new CharArrayWriter(); } else { mapout = null; servletout = null; mappingout = null; } if (webxmlLevel >= ALL_WEBXML) { mapout.write(Localizer.getMessage("jspc.webxml.header", webxmlEncoding)); mapout.flush(); } else if (webxmlLevel >= FRG_WEBXML) { mapout.write(Localizer.getMessage("jspc.webfrg.header", webxmlEncoding)); mapout.flush(); } else if ((webxmlLevel>= INC_WEBXML) && !addWebXmlMappings) { mapout.write(Localizer.getMessage("jspc.webinc.header")); mapout.flush(); } } catch (IOException ioe) { mapout = null; servletout = null; mappingout = null; throw new JasperException(ioe); } }
Example #21
Source File: InjectBytecodes.java From jdk8u-dev-jdk with GNU General Public License v2.0 | 5 votes |
/** * Print an integer so that it takes 'length' characters in * the output. Temporary until formatting code is stable. */ private void traceFixedWidthInt(int x, int length) { if (Inject.verbose) { CharArrayWriter baStream = new CharArrayWriter(); PrintWriter pStream = new PrintWriter(baStream); pStream.print(x); String str = baStream.toString(); for (int cnt = length - str.length(); cnt > 0; --cnt) trace(" "); trace(str); } }
Example #22
Source File: ConnectionToServer.java From Open-Lowcode with Eclipse Public License 2.0 | 5 votes |
/** * Sends the message to the server, restarting the connection if necessary, and * getting the first element, as in some cases of broken connection, the error * appears only after trying to get the first element * * @param writertoserver function to send the message to the server * @return the first message element * @throws Exception */ public MessageElement sendMessage(WriterToServer writertoserver) throws Exception { int index = 0; boolean sent = false; while ((index < 2) && (!sent)) { try { if (clientsocket == null) { initConnection(); } CharArrayWriter encryptedmessageloc = new CharArrayWriter(); MessageBufferedWriter writertoencrypt = new MessageBufferedWriter(new BufferedWriter(encryptedmessageloc), false); writertoserver.apply(writertoencrypt); writertoencrypt.flushMessage(); String messagetoencrypt = encryptedmessageloc.toString(); writertoencrypt.close(); byte[]encodedmessagetosend = aescommunicator.zipandencrypt(messagetoencrypt); writer.startNewMessage(); writer.startStructure("ENCMES"); writer.addLongBinaryField("ENCMES",new SFile("ENC",encodedmessagetosend)); writer.endStructure("ENCMES"); writer.endMessage(); sent = true; return reader.getNextElement(); } catch (IOException e) { logger.warning("Client disconnected"); initConnection(); index++; } } throw new RuntimeException("Did not manage to send message after attempt "+(index+1)); }
Example #23
Source File: JspReader.java From Tomcat8-Source-Read with MIT License | 5 votes |
/** * Constructor: same as above constructor but with initialized reader * to the file given. * * @param ctxt The compilation context * @param fname The file name * @param reader A reader for the JSP source file * @param err The error dispatcher * * @throws JasperException If an error occurs parsing the JSP file */ public JspReader(JspCompilationContext ctxt, String fname, InputStreamReader reader, ErrorDispatcher err) throws JasperException { this.context = ctxt; this.err = err; try { CharArrayWriter caw = new CharArrayWriter(); char buf[] = new char[1024]; for (int i = 0 ; (i = reader.read(buf)) != -1 ;) caw.write(buf, 0, i); caw.close(); current = new Mark(this, caw.toCharArray(), fname); } catch (Throwable ex) { ExceptionUtils.handleThrowable(ex); log.error("Exception parsing file ", ex); err.jspError("jsp.error.file.cannot.read", fname); } finally { if (reader != null) { try { reader.close(); } catch (Exception any) { if(log.isDebugEnabled()) { log.debug("Exception closing reader: ", any); } } } } }
Example #24
Source File: AbstractGMConnectionTest.java From gm4java with Apache License 2.0 | 5 votes |
@Before public void setup() throws Exception { MockitoAnnotations.initMocks(this); writer = new CharArrayWriter(); when(process.getWriter()).thenReturn(writer); when(process.getReader()).thenReturn(reader); }
Example #25
Source File: ClassDump.java From openjdk-jdk8u with GNU General Public License v2.0 | 5 votes |
/** * Print an integer so that it takes 'length' characters in * the output. Temporary until formatting code is stable. */ private void traceFixedWidthInt(int x, int length) { if (verbose) { CharArrayWriter baStream = new CharArrayWriter(); PrintWriter pStream = new PrintWriter(baStream); pStream.print(x); String str = baStream.toString(); for (int cnt = length - str.length(); cnt > 0; --cnt) trace(" "); trace(str); } }
Example #26
Source File: CreateResultSet.java From gemfirexd-oss with Apache License 2.0 | 5 votes |
/** * Data Node messaging information. * * @param out * @throws SQLException * @throws IOException */ private void createMsgReceiveAndResultSendInfo(CharArrayWriter out) throws SQLException, IOException { PreparedStatement ps; ResultSet results; StringBuilder gatherLine = new StringBuilder(); getCompressedDistDetails(XPLAINUtil.OP_QUERY_RECEIVE, maxMinAvgSum); getCompressedDistDetails(XPLAINUtil.OP_RESULT_SEND, maxMinAvgSum); { final String queryScatter = "SELECT 'DISTRIBUTION to ' || TRIM(CHAR(NO_PRUNED_MEMBERS)) || ' members took ' || TRIM(CHAR(SCATTER_TIME/1000)) || ' microseconds ' from " + GfxdConstants.PLAN_SCHEMA + ".SYSXPLAIN_DIST_PROPS " + " where STMT_RS_ID = ? and DIST_OBJECT_TYPE = '" + XPLAINUtil.OP_QUERY_SCATTER + "' "; ps = ds.conn.prepareStatementByPassQueryInfo(-1, queryScatter, false, false, false, null, 0, 0); ps.setString(1, ds.getQueryID()); results = ps.executeQuery(); if (results.next()) { gatherLine.append(results.getString(1)); } assert !results.next(); results.close(); ps.close(); } out.write(gatherLine.toString()); }
Example #27
Source File: ExtFormatter.java From netbeans with Apache License 2.0 | 5 votes |
/** Reformat a block of code. * @param doc document to work with * @param startOffset position at which the formatting starts * @param endOffset position at which the formatting ends * @param indentOnly whether just the indentation should be changed * or regular formatting should be performed. * @return formatting writer. The text was already reformatted * but the writer can contain useful information. */ public Writer reformat(BaseDocument doc, int startOffset, int endOffset, boolean indentOnly) throws BadLocationException, IOException { pushFormattingContextDocument(doc); try { CharArrayWriter cw = new CharArrayWriter(); Writer w = createWriter(doc, startOffset, cw); FormatWriter fw = (w instanceof FormatWriter) ? (FormatWriter)w : null; boolean fix5620 = true; // whether apply fix for #5620 or not if (fw != null) { fw.setIndentOnly(indentOnly); if (fix5620) { fw.setReformatting(true); // #5620 } } w.write(doc.getChars(startOffset, endOffset - startOffset)); w.close(); if (!fix5620 || fw == null) { // #5620 - for (fw != null) the doc was already modified String out = new String(cw.toCharArray()); doc.remove(startOffset, endOffset - startOffset); doc.insertString(startOffset, out, null); } return w; } finally { popFormattingContextDocument(doc); } }
Example #28
Source File: JFCParser.java From dragonwell8_jdk with GNU General Public License v2.0 | 5 votes |
private static String readContent(Reader r) throws IOException { CharArrayWriter writer = new CharArrayWriter(1024); int count = 0; int ch; while ((ch = r.read()) != -1) { writer.write(ch); count++; if (count >= MAXIMUM_FILE_SIZE) { throw new IOException("Presets with more than " + MAXIMUM_FILE_SIZE + " characters can't be read."); } } return new String(writer.toCharArray()); }
Example #29
Source File: DriverManagerTests.java From openjdk-jdk8u-backup with GNU General Public License v2.0 | 5 votes |
/** * Create a PrintWriter and use to to send output via DriverManager.println * Validate that if you disable the writer, the output sent is not present */ @Test public void tests18() throws Exception { CharArrayWriter cw = new CharArrayWriter(); PrintWriter pw = new PrintWriter(cw); DriverManager.setLogWriter(pw); assertTrue(DriverManager.getLogWriter() == pw); DriverManager.println(results[0]); DriverManager.setLogWriter(null); assertTrue(DriverManager.getLogWriter() == null); DriverManager.println(noOutput); DriverManager.setLogWriter(pw); DriverManager.println(results[1]); DriverManager.println(results[2]); DriverManager.println(results[3]); DriverManager.setLogWriter(null); DriverManager.println(noOutput); /* * Check we do not get the output when the stream is disabled */ BufferedReader reader = new BufferedReader(new CharArrayReader(cw.toCharArray())); for (String result : results) { assertTrue(result.equals(reader.readLine())); } }
Example #30
Source File: GenFileStream.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
public GenFileStream (String filename) { // What I really want to do here is: // super (byteStream = new ByteArrayOutputStream ()); // but that isn't legal. The super constructor MUST // be called before any instance variables are used. // This implementation gets around that problem. // <f49747.1> //super (tmpByteStream = new ByteArrayOutputStream ()); //byteStream = tmpByteStream; super (tmpCharArrayWriter = new CharArrayWriter()); charArrayWriter = tmpCharArrayWriter; name = filename; }