@Override public Writer filterWriter(final Writer w) { return new CharArrayWriter() { @Override public void close() { try { super.close(); for (String line : new String(toCharArray()).split("\n")) { w.write("t" + line); w.write(System.getProperty("line.separator")); } w.close(); } catch (IOException ex) { throw new IllegalStateException(ex); } } }; }
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(); }
/** * Check if the CRC of the snapshot file matches the digest. * @param f The snapshot file object * @return The table list as a string * @throws IOException If CRC does not match */ public static String CRCCheck(File f) throws IOException { final FileInputStream fis = new FileInputStream(f); try { final BufferedInputStream bis = new BufferedInputStream(fis); ByteBuffer crcBuffer = ByteBuffer.allocate(4); if (4 != bis.read(crcBuffer.array())) { throw new EOFException("EOF while attempting to read CRC from snapshot digest"); } final int crc = crcBuffer.getInt(); final InputStreamReader isr = new InputStreamReader(bis, "UTF-8"); CharArrayWriter caw = new CharArrayWriter(); while (true) { int nextChar = isr.read(); if (nextChar == -1) { throw new EOFException("EOF while reading snapshot digest"); } if (nextChar == '\n') { break; } caw.write(nextChar); } String tableList = caw.toString(); byte tableListBytes[] = tableList.getBytes("UTF-8"); CRC32 tableListCRC = new CRC32(); tableListCRC.update(tableListBytes); tableListCRC.update("\n".getBytes("UTF-8")); final int calculatedValue = (int)tableListCRC.getValue(); if (crc != calculatedValue) { throw new IOException("CRC of snapshot digest did not match digest contents"); } return tableList; } finally { try { if (fis != null) fis.close(); } catch (IOException e) {} } }
private String parseScriptText(String tx) { CharArrayWriter cw = new CharArrayWriter(); int size = tx.length(); int i = 0; while (i < size) { char ch = tx.charAt(i); if (i + 2 < size && ch == '%' && tx.charAt(i + 1) == '\\' && tx.charAt(i + 2) == '>') { cw.write('%'); cw.write('>'); i += 3; } else { cw.write(ch); ++i; } } cw.close(); return cw.toString(); }
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; } }
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; } }
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(); }
public CharArrayWriter toCharArrayWriter(String prefix) { CharArrayWriter buffer = new CharArrayWriter(100); final char delimiter = DEFAULT_DELIMITER; final String replaceDelimiter = DEFAULT_REPLACE_DELIMITER; if (prefix != null && !prefix.isEmpty()) { buffer.append(prefix); } buffer.append(replaceDelimiter(userId(), delimiter, replaceDelimiter)).append(delimiter); buffer.append(replaceDelimiter(eventType(), delimiter, replaceDelimiter)) .append(delimiter); buffer.append(replaceDelimiter(date(), delimiter, replaceDelimiter)).append(delimiter); buffer.append(replaceDelimiter(time(), delimiter, replaceDelimiter)).append(delimiter); buffer.append(replaceDelimiter(status(), delimiter, replaceDelimiter)).append(delimiter); buffer.append(replaceDelimiter(origination(), delimiter, replaceDelimiter)) .append(delimiter); buffer.append(replaceDelimiter(affectedResource(), delimiter, replaceDelimiter)); return buffer; }
@Override protected void logEvent0(PciAuditEvent event) { CharArrayWriter msg = event.toCharArrayWriter(""); AuditLevel al = event.level(); switch (al) { case DEBUG: if (LOG.isDebugEnabled()) { LOG.debug("{} | {}", al.alignedText(), msg); } break; default: if (LOG.isInfoEnabled()) { LOG.info("{} | {}", al.alignedText(), msg); } break; } // end switch }
protected void initWebXml() { try { if (webxmlLevel >= INC_WEBXML) { File fmapings = new File(webxmlFile); mapout = new FileWriter(fmapings); 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; } }
/** * Writes an explanatory message and a stack trace for a given * <code>Throwable</code> exception to the servlet log file. The name * and type of the servlet log file is specific to the servlet container, * usually an event log. This message will be logged unconditionally. * * @param msg A <code>String</code> that describes the error or * exception * @param throwable The <code>Throwable</code> error or exception */ public void log(String msg, Throwable throwable) { CharArrayWriter buf = new CharArrayWriter(); PrintWriter writer = new PrintWriter(buf); writer.println(msg); throwable.printStackTrace(writer); Throwable rootCause = null; if (throwable instanceof LifecycleException) rootCause = ((LifecycleException) throwable).getThrowable(); else if (throwable instanceof ServletException) rootCause = ((ServletException) throwable).getRootCause(); if (rootCause != null) { writer.println("----- Root Cause -----"); rootCause.printStackTrace(writer); } log(buf.toString()); }
/** * A convenience wrapper function which reads in a private key (PEM format, either DSA or RSA) * and then calls <code>authenticateWithPublicKey(String, char[], String)</code>. * <p> * NOTE PUTTY USERS: Event though your key file may start with "-----BEGIN..." * it is not in the expected format. You have to convert it to the OpenSSH * key format by using the "puttygen" tool (can be downloaded from the Putty * website). Simply load your key and then use the "Conversions/Export OpenSSH key" * functionality to get a proper PEM file. * * @param user A <code>String</code> holding the username. * @param pemFile A <code>File</code> object pointing to a file containing a DSA or RSA * private key of the user in OpenSSH key format (PEM, you can't miss the * "-----BEGIN DSA PRIVATE KEY-----" or "-----BEGIN RSA PRIVATE KEY-----" * tag). * @param password If the PEM file is encrypted then you must specify the password. * Otherwise, this argument will be ignored and can be set to <code>null</code>. * @return whether the connection is now authenticated. * @throws IOException */ public synchronized boolean authenticateWithPublicKey(String user, File pemFile, String password) throws IOException { if (pemFile == null) throw new IllegalArgumentException("pemFile argument is null"); char[] buff = new char[256]; CharArrayWriter cw = new CharArrayWriter(); FileReader fr = new FileReader(pemFile); while (true) { int len = fr.read(buff); if (len < 0) break; cw.write(buff, 0, len); } fr.close(); return authenticateWithPublicKey(user, cw.toCharArray(), password); }
/** * 读取请求流 * @param request * @return * @throws IOException */ public static String binaryReader(HttpServletRequest request) throws IOException { 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[8192]; int ret; while ((ret = in.read(buf, 0, 8192)) != -1) { data.write(buf, 0, ret); } return data.toString(); }
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"); } } }
public static void main(String[] args) { String htmlDoc = "<pre><p> </pre>"; try { 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(); } catch (Exception ex) { throw new RuntimeException("Test Failed " + ex); } }
@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()); } }
private static char[] readFully(Reader reader) throws IOException { CharArrayWriter baos = new CharArrayWriter(); int r; while ((r = reader.read()) != (-1)) { baos.append((char) r); } return baos.toCharArray(); }
/** Read a maximal string until delim is encountered (which will be removed from stream). * This impl reads only ASCII, for speed. * Newline conventions are normalized to Unix \n. * @return the read string, or null if the delim is not encountered before EOF. */ private String readTo(InputStream is, char delim) throws IOException { if (delim == 10) { // Not implemented - stream might have "foo\r\n" and we would // return "foo" and leave "\n" in the stream. throw new IOException("Not implemented"); // NOI18N } CharArrayWriter caw = new CharArrayWriter(100); boolean inNewline = false; while (true) { int c = is.read(); if (c == -1) return null; if (c > 126) return null; if (c == 10 || c == 13) { // Normalize: s/[\r\n]+/\n/g if (inNewline) { continue; } else { inNewline = true; c = 10; } } else if (c < 32 && c != 9) { // Random control character! return null; } else { inNewline = false; } if (c == delim) { return caw.toString(); } else { caw.write(c); } } }
/** Reformat a block of code. * @param doc document to work with * @param startOffset offset at which the formatting starts * @param endOffset offset at which the formatting ends * @return length of the reformatted code */ public int reformat(BaseDocument doc, int startOffset, int endOffset) throws BadLocationException { LegacyFormattersProvider.pushFormattingContextDocument(doc); try { try { CharArrayWriter cw = new CharArrayWriter(); Writer w = createWriter(doc, startOffset, cw); String originalString = doc.getText(startOffset, endOffset - startOffset); w.write(originalString); w.close(); String out = new String(cw.toCharArray()); if(!out.equals(originalString)){ doc.remove(startOffset, endOffset - startOffset); doc.insertString(startOffset, out, null); return out.length(); }else{ //nothing changed return 0; } } catch (IOException e) { Utilities.annotateLoggable(e); return 0; } } finally { LegacyFormattersProvider.popFormattingContextDocument(doc); } }
/** 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); } }
private String generateStackTrace() { // Get stable reference to work properly with concurrent access CharArrayWriter writer = new CharArrayWriter(); super.printStackTrace(new PrintWriter(writer)); String origStackTrace = writer.toString(); Evaluator e = Context.createInterpreter(); if (e != null) return e.getPatchedStack(this, origStackTrace); return null; }
String getText(Mark start, Mark stop) throws JasperException { Mark oldstart = mark(); reset(start); CharArrayWriter caw = new CharArrayWriter(); while (!markEquals(stop)) { caw.write(nextChar()); } caw.close(); setCurrent(oldstart); return caw.toString(); }
@Before public void setup() { args = new HashMap<String, String>(); out = new CharArrayWriter(); err = new CharArrayWriter(); OperatorService service = (OperatorService) Proxy.newProxyInstance( getClass().getClassLoader(), new Class[] { OperatorService.class }, this); ctx = new CommandContext(service, args, new PrintWriter(out, true), new PrintWriter(err, true)); command = createCommand(); }
@Test public void testHandleException() { final CharArrayWriter err = new CharArrayWriter(); final OperatorClient client = new OperatorClient(null, null, new PrintWriter(err, true)); final Exception cause1 = new Exception("Cause 1"); final Exception cause2 = new Exception("Cause 2", cause1); final Exception exception = new Exception("Bumm", cause2); client.handleException(exception); final String expected = "Bumm\ncaused by: Cause 2\ncaused by: Cause 1"; assertEquals(String.format(expected), err.toString()); }
@Before public void setup() { service = new OperatorServiceStub(); args = new HashMap<String, String>(); out = new CharArrayWriter(); err = new CharArrayWriter(); ctx = new CommandContext(service, args, new PrintWriter(out, true), new PrintWriter(err, true)); }
private void writeBytecodeToDisk(final byte[] clazz, Path folder) throws IOException { final ClassReader reader = new ClassReader(clazz); CharArrayWriter buffer = new CharArrayWriter(); reader.accept(new TraceClassVisitor(null, new Textifier(), new PrintWriter( buffer)), ClassReader.EXPAND_FRAMES); Path outFile = folder.resolve(currentClass.asJavaName() + ".txt"); Files.write(outFile, Collections.singleton(buffer.toString()), StandardCharsets.UTF_8, StandardOpenOption.CREATE); }
public static char[] removeQuotes(char []chars) { CharArrayWriter caw = new CharArrayWriter(); for (int i = 0; i < chars.length; i++) { if (chars[i] == '%' && chars[i+1] == '\\' && chars[i+2] == '>') { caw.write('%'); caw.write('>'); i = i + 2; } else { caw.write(chars[i]); } } return caw.toCharArray(); }
String getText(Mark start, Mark stop) throws JasperException { Mark oldstart = mark(); reset(start); CharArrayWriter caw = new CharArrayWriter(); while (!stop.equals(mark())) caw.write(nextChar()); caw.close(); reset(oldstart); return caw.toString(); }
public Object get(ResultSet rs, String name) throws SQLException { Reader stream = rs.getCharacterStream(name); if ( stream == null ) return toExternalFormat( null ); CharArrayWriter writer = new CharArrayWriter(); for(;;) { try { int c = stream.read(); if ( c == -1) return toExternalFormat( writer.toCharArray() ); writer.write( c ); } catch (IOException e) { throw new HibernateException("Unable to read character stream from rs"); } } }
private static String loadFile(String filePath, IShaderPack shaderPack, int includeLevel) throws IOException { if (includeLevel >= 10) { throw new IOException("#include depth exceeded: " + includeLevel + ", file: " + filePath); } else { ++includeLevel; InputStream inputstream = shaderPack.getResourceAsStream(filePath); if (inputstream == null) { return null; } else { InputStreamReader inputstreamreader = new InputStreamReader(inputstream, "ASCII"); BufferedReader bufferedreader = new BufferedReader(inputstreamreader); bufferedreader = resolveIncludes(bufferedreader, filePath, shaderPack, includeLevel); CharArrayWriter chararraywriter = new CharArrayWriter(); while (true) { String s = bufferedreader.readLine(); if (s == null) { return chararraywriter.toString(); } chararraywriter.write(s); chararraywriter.write("\n"); } } } }
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; }