Example usage for org.apache.commons.lang3.text StrBuilder setLength

List of usage examples for org.apache.commons.lang3.text StrBuilder setLength

Introduction

In this page you can find the example usage for org.apache.commons.lang3.text StrBuilder setLength.

Prototype

public StrBuilder setLength(final int length) 

Source Link

Document

Updates the length of the builder by either dropping the last characters or adding filler of Unicode zero.

Usage

From source file:org.kie.workbench.common.services.datamodeller.util.StringEscapeUtils.java

/**
 * Comes from  org.apache.commons.lang.StringEscapeUtils
 *//* w  w w  .ja v  a2  s .c  o m*/
public static void unescapeJavaUTF(Writer out, String str) throws IOException {
    if (out == null) {
        throw new IllegalArgumentException("The Writer must not be null");
    }
    if (str == null) {
        return;
    }
    int sz = str.length();
    StrBuilder unicode = new StrBuilder(4);
    boolean hadSlash = false;
    boolean inUnicode = false;
    for (int i = 0; i < sz; i++) {
        char ch = str.charAt(i);
        if (inUnicode) {
            // if in unicode, then we're reading unicode
            // values in somehow
            unicode.append(ch);
            if (unicode.length() == 4) {
                // unicode now contains the four hex digits
                // which represents our unicode character
                try {
                    int value = Integer.parseInt(unicode.toString(), 16);
                    out.write((char) value);
                    unicode.setLength(0);
                    inUnicode = false;
                    hadSlash = false;
                } catch (NumberFormatException nfe) {
                    throw new RuntimeException("Unable to parse unicode value: " + unicode, nfe);
                }
            }
            continue;
        }
        if (hadSlash) {
            // handle an escaped value
            hadSlash = false;
            if (ch == 'u') {
                // uh-oh, we're in unicode country....
                inUnicode = true;
            } else {
                out.write('\\');
                out.write(ch);
            }
            continue;
        } else if (ch == '\\') {
            hadSlash = true;
            continue;
        }
        out.write(ch);
    }
    if (hadSlash) {
        // then we're in the weird case of a \ at the end of the
        // string, let's output it anyway.
        out.write('\\');
    }
}