Java Code Examples for java.io.CharArrayWriter#toString()

The following examples show how to use java.io.CharArrayWriter#toString() . 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: bug8005391.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
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 2
Source File: SolrException.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public static String toStr(Throwable e) {   
    CharArrayWriter cw = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(cw);
    e.printStackTrace(pw);
    pw.flush();
    return cw.toString();

/** This doesn't work for some reason!!!!!
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    e.printStackTrace(pw);
    pw.flush();
    System.out.println("The STRING:" + sw.toString());
    return sw.toString();
**/
  }
 
Example 3
Source File: FmHelper.java    From stategen with GNU Affero General Public License v3.0 6 votes vote down vote up
private static String checkAndConvertIfMybatisXml(JavaType javaType, CharArrayWriter charArrayWriter,
                                                  boolean isFileExits) throws IOException {
    String gerneratedText = null;
    if (javaType == null) {
        if (GenProperties.daoType == DaoType.mybatis) {
            gerneratedText = charArrayWriter.toString();
            if (gerneratedText.lastIndexOf("</sqlMap>") > 0) {
                gerneratedText = IbatisXmlToMybatis.transformXmlByXslt(gerneratedText);
                charArrayWriter.reset();
                charArrayWriter.write(gerneratedText);
            }
            return gerneratedText;
        }
    }
    
    if (isFileExits) {
        gerneratedText = charArrayWriter.toString(); 
    }
    return gerneratedText;
}
 
Example 4
Source File: bug8005391.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
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 5
Source File: IJError.java    From TrakEM2 with GNU General Public License v3.0 6 votes vote down vote up
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 6
Source File: ClassDump.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 7
Source File: ErrorPage.java    From hadoop with Apache License 2.0 5 votes vote down vote up
public static String toStackTrace(Throwable error, int cutoff) {
  // default initial size is 32 chars
  CharArrayWriter buffer = new CharArrayWriter(8 * 1024);
  error.printStackTrace(new PrintWriter(buffer));
  return buffer.size() < cutoff ? buffer.toString()
      : buffer.toString().substring(0, cutoff);
}
 
Example 8
Source File: InjectBytecodes.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 9
Source File: RhinoException.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
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;
}
 
Example 10
Source File: ClassDump.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 11
Source File: ClassDump.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 12
Source File: ModuleList.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** 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);
        }
    }
}
 
Example 13
Source File: InjectBytecodes.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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 14
Source File: JacksonJsonFieldBodyFilter.java    From logbook with MIT License 5 votes vote down vote up
public String filter(final String body) {
    try {
        final JsonParser parser = factory.createParser(body);
        
        final CharArrayWriter writer = new CharArrayWriter(body.length() * 2); // rough estimate of final size
        
        final JsonGenerator generator = factory.createGenerator(writer);
        try {
            while(true) {
                JsonToken nextToken = parser.nextToken();
                if(nextToken == null) {
                    break;
                }

                generator.copyCurrentEvent(parser);
                if(nextToken == JsonToken.FIELD_NAME && fields.contains(parser.getCurrentName())) {
                    nextToken = parser.nextToken();
                    generator.writeString(replacement);
                    if(!nextToken.isScalarValue()) {
                        parser.skipChildren(); // skip children
                    }
                }
            }                    
        } finally {
            parser.close();
            
            generator.close();
        }
        
        return writer.toString();
    } catch(final Exception e) {
        log.trace("Unable to filter body for fields {}, compacting result. `{}`", fields, e.getMessage()); 
        return fallbackCompactor.compact(body);
    }
}
 
Example 15
Source File: IOTinyUtils.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
static public String toString(Reader reader) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(reader, sw);
    return sw.toString();
}
 
Example 16
Source File: Context.java    From astor with GNU General Public License v2.0 4 votes vote down vote up
static String getSourcePositionFromStack(int[] linep)
{
    Context cx = getCurrentContext();
    if (cx == null)
        return null;
    if (cx.lastInterpreterFrame != null) {
        Evaluator evaluator = createInterpreter();
        if (evaluator != null)
            return evaluator.getSourcePositionFromStack(cx, linep);
    }
    /**
     * A bit of a hack, but the only way to get filename and line
     * number from an enclosing frame.
     */
    CharArrayWriter writer = new CharArrayWriter();
    RuntimeException re = new RuntimeException();
    re.printStackTrace(new PrintWriter(writer));
    String s = writer.toString();
    int open = -1;
    int close = -1;
    int colon = -1;
    for (int i=0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == ':')
            colon = i;
        else if (c == '(')
            open = i;
        else if (c == ')')
            close = i;
        else if (c == '\n' && open != -1 && close != -1 && colon != -1 &&
                 open < colon && colon < close)
        {
            String fileStr = s.substring(open + 1, colon);
            if (!fileStr.endsWith(".java")) {
                String lineStr = s.substring(colon + 1, close);
                try {
                    linep[0] = Integer.parseInt(lineStr);
                    if (linep[0] < 0) {
                        linep[0] = 0;
                    }
                    return fileStr;
                }
                catch (NumberFormatException e) {
                    // fall through
                }
            }
            open = close = colon = -1;
        }
    }

    return null;
}
 
Example 17
Source File: NetworkStatsHistory.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    final CharArrayWriter writer = new CharArrayWriter();
    dump(new IndentingPrintWriter(writer, "  "), false);
    return writer.toString();
}
 
Example 18
Source File: VolumeInfo.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    final CharArrayWriter writer = new CharArrayWriter();
    dump(new IndentingPrintWriter(writer, "    ", 80));
    return writer.toString();
}
 
Example 19
Source File: Utility.java    From commons-bcel with Apache License 2.0 4 votes vote down vote up
/**
 * Encode byte array it into Java identifier string, i.e., a string
 * that only contains the following characters: (a, ... z, A, ... Z,
 * 0, ... 9, _, $).  The encoding algorithm itself is not too
 * clever: if the current byte's ASCII value already is a valid Java
 * identifier part, leave it as it is. Otherwise it writes the
 * escape character($) followed by:
 *
 * <ul>
 *   <li> the ASCII value as a hexadecimal string, if the value is not in the range 200..247</li>
 *   <li>a Java identifier char not used in a lowercase hexadecimal string, if the value is in the range 200..247</li>
 * </ul>
 *
 * <p>This operation inflates the original byte array by roughly 40-50%</p>
 *
 * @param bytes the byte array to convert
 * @param compress use gzip to minimize string
 *
 * @throws IOException if there's a gzip exception
 */
public static String encode(byte[] bytes, final boolean compress) throws IOException {
    if (compress) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gos = new GZIPOutputStream(baos)) {
            gos.write(bytes, 0, bytes.length);
            bytes = baos.toByteArray();
        }
    }
    final CharArrayWriter caw = new CharArrayWriter();
    try (JavaWriter jw = new JavaWriter(caw)) {
        for (final byte b : bytes) {
            final int in = b & 0x000000ff; // Normalize to unsigned
            jw.write(in);
        }
    }
    return caw.toString();
}
 
Example 20
Source File: NetworkStatsHistory.java    From 365browser with Apache License 2.0 4 votes vote down vote up
@Override
public String toString() {
    final CharArrayWriter writer = new CharArrayWriter();
    dump(new PrintWriter(writer), false);
    return writer.toString();
}