java.io.CharArrayWriter

Here are the examples of the java api class java.io.CharArrayWriter taken from open source projects.

1. CharArrayWriterTest#testCharArrayWriter()

Project: j2objc
File: CharArrayWriterTest.java
public void testCharArrayWriter() throws Exception {
    String str = "AbCdEfGhIjKlMnOpQrStUvWxYz";
    CharArrayWriter a = new CharArrayWriter();
    CharArrayWriter b = new CharArrayWriter();
    a.write(str, 0, 26);
    a.write('X');
    a.writeTo(b);
    assertEquals(27, a.size());
    assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYzX", a.toString());
    b.write("alphabravodelta", 5, 5);
    b.append('X');
    assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYzXbravoX", b.toString());
    b.append("omega");
    assertEquals("AbCdEfGhIjKlMnOpQrStUvWxYzXbravoXomega", b.toString());
}

2. TestDateTimeFormatter#testPrint_writerMethods()

Project: joda-time
File: TestDateTimeFormatter.java
//-----------------------------------------------------------------------
public void testPrint_writerMethods() throws Exception {
    DateTime dt = new DateTime(2004, 6, 9, 10, 20, 30, 40, UTC);
    CharArrayWriter out = new CharArrayWriter();
    f.printTo(out, dt);
    assertEquals("Wed 2004-06-09T10:20:30Z", out.toString());
    out = new CharArrayWriter();
    f.printTo(out, dt.getMillis());
    assertEquals("Wed 2004-06-09T11:20:30+01:00", out.toString());
    out = new CharArrayWriter();
    ISODateTimeFormat.yearMonthDay().printTo(out, dt.toYearMonthDay());
    assertEquals("2004-06-09", out.toString());
    out = new CharArrayWriter();
    try {
        ISODateTimeFormat.yearMonthDay().printTo(out, (ReadablePartial) null);
        fail();
    } catch (IllegalArgumentException ex) {
    }
}

3. Parser#parseScriptText()

Project: sling
File: Parser.java
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();
}

4. SolrException#toStr()

Project: lucene-solr
File: SolrException.java
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();
**/
}

5. JSONCollection#toString()

Project: tapestry-5
File: JSONCollection.java
/**
     * Converts this JSON collection into a parsable string representation.
     *
     * Warning: This method assumes that the data structure is acyclical.
     *
     * Starting in release 5.2, the result will be pretty printed for readability.
     * 
     * @return a printable, displayable, portable, transmittable representation of the object, beginning with
     *         <code>{</code> <small>(left brace)</small> and ending with <code>}</code> <small>(right
     *         brace)</small>.
     */
@Override
public String toString() {
    CharArrayWriter caw = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(caw);
    JSONPrintSession session = new PrettyPrintSession(pw);
    print(session);
    pw.close();
    return caw.toString();
}

6. JspUtil#removeQuotes()

Project: sling
File: JspUtil.java
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();
}

7. ErrorLog#addMessage()

Project: SimpleServer
File: ErrorLog.java
public void addMessage(Exception exception, String message) {
    CharArrayWriter charWriter = new CharArrayWriter();
    PrintWriter writer = new PrintWriter(charWriter);
    writer.append(message);
    if (exception != null) {
        writer.append("\n");
        exception.printStackTrace(writer);
    }
    super.addMessage(charWriter.toString());
    writer.close();
    charWriter.close();
}

8. TestPeriodFormatter#testPrint_writerMethods()

Project: joda-time
File: TestPeriodFormatter.java
//-----------------------------------------------------------------------
public void testPrint_writerMethods() throws Exception {
    Period p = new Period(1, 2, 3, 4, 5, 6, 7, 8);
    CharArrayWriter out = new CharArrayWriter();
    f.printTo(out, p);
    assertEquals("P1Y2M3W4DT5H6M7.008S", out.toString());
    out = new CharArrayWriter();
    try {
        f.printTo(out, null);
        fail();
    } catch (IllegalArgumentException ex) {
    }
}

9. Utility#encode()

Project: commons-bcel
File: Utility.java
/**
     * 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) {
            // Normalize to unsigned
            final int in = b & 0x000000ff;
            jw.write(in);
        }
    }
    return caw.toString();
}

10. XSLTResponseWriter#write()

Project: lucene-solr
File: XSLTResponseWriter.java
@Override
public void write(Writer writer, SolrQueryRequest request, SolrQueryResponse response) throws IOException {
    final Transformer t = getTransformer(request);
    // capture the output of the XMLWriter
    final CharArrayWriter w = new CharArrayWriter();
    XMLWriter.writeResponse(w, request, response);
    // and write transformed result to our writer
    final Reader r = new BufferedReader(new CharArrayReader(w.toCharArray()));
    final StreamSource source = new StreamSource(r);
    final StreamResult result = new StreamResult(writer);
    try {
        t.transform(source, result);
    } catch (TransformerException te) {
        throw new IOException("XSLT transformation error", te);
    }
}

11. JSONArrayEventResultProcessorTest#response_sent()

Project: tapestry5
File: JSONArrayEventResultProcessorTest.java
@Test
public void response_sent() throws IOException {
    String encoding = "UTF-8";
    Response response = mockResponse();
    CharArrayWriter writer = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(writer);
    expect(response.getPrintWriter("application/json;charset=UTF-8")).andReturn(pw);
    replay();
    JSONArray array = new JSONArray("   [ \"fred\", \"barney\" \n\n]");
    JSONArrayEventResultProcessor p = new JSONArrayEventResultProcessor(response, encoding);
    p.processResultValue(array);
    verify();
    assertEquals(writer.toString(), "[\"fred\",\"barney\"]");
}

12. PortletExceptionPresenter#reportActionRequestException()

Project: tapestry4
File: PortletExceptionPresenter.java
private void reportActionRequestException(IRequestCycle cycle, Throwable cause) {
    CharArrayWriter caw = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(caw);
    IMarkupWriter writer = _markupWriterSource.newMarkupWriter(pw, new ContentType("text/html"));
    writeException(writer, cycle, cause);
    writer.close();
    String markup = caw.toString();
    _request.getSession(true).setAttribute(PortletConstants.PORTLET_EXCEPTION_MARKUP_ATTRIBUTE, markup);
    ActionResponse response = _globals.getActionResponse();
    response.setRenderParameter(ServiceConstants.SERVICE, PortletConstants.EXCEPTION_SERVICE);
}

13. TestBinaryDumpOutputStream#testNoAscii()

Project: tapestry4
File: TestBinaryDumpOutputStream.java
public void testNoAscii() throws Exception {
    CharArrayWriter writer = new CharArrayWriter();
    BinaryDumpOutputStream bdos = new BinaryDumpOutputStream(writer);
    bdos.setShowAscii(false);
    ObjectOutputStream oos = new ObjectOutputStream(bdos);
    oos.writeObject(createOutputObject());
    oos.close();
    assertEquals(contentsOf("NoAscii.txt"), writer.toString());
}

14. TestBinaryDumpOutputStream#testNoOffset()

Project: tapestry4
File: TestBinaryDumpOutputStream.java
public void testNoOffset() throws Exception {
    CharArrayWriter writer = new CharArrayWriter();
    BinaryDumpOutputStream bdos = new BinaryDumpOutputStream(writer);
    bdos.setShowOffset(false);
    ObjectOutputStream oos = new ObjectOutputStream(bdos);
    oos.writeObject(createOutputObject());
    oos.close();
    assertEquals(contentsOf("NoOffset.txt"), writer.toString());
}

15. TestBinaryDumpOutputStream#testOptions()

Project: tapestry4
File: TestBinaryDumpOutputStream.java
public void testOptions() throws Exception {
    CharArrayWriter writer = new CharArrayWriter();
    BinaryDumpOutputStream bdos = new BinaryDumpOutputStream(writer);
    bdos.setAsciiBegin(" { ");
    bdos.setAsciiEnd(" }");
    bdos.setOffsetSeperator(" = ");
    bdos.setSubstituteChar('?');
    bdos.setBytesPerLine(48);
    bdos.setSpacingInterval(8);
    ObjectOutputStream oos = new ObjectOutputStream(bdos);
    oos.writeObject(createOutputObject());
    oos.close();
    assertEquals(contentsOf("Options.txt"), writer.toString());
}

16. TestBinaryDumpOutputStream#testBasic()

Project: tapestry4
File: TestBinaryDumpOutputStream.java
public void testBasic() throws Exception {
    CharArrayWriter writer = new CharArrayWriter();
    BinaryDumpOutputStream bdos = new BinaryDumpOutputStream(writer);
    ObjectOutputStream oos = new ObjectOutputStream(bdos);
    oos.writeObject(createOutputObject());
    oos.close();
    assertEquals(contentsOf("Basic.txt"), writer.toString());
}

17. JSONArrayEventResultProcessorTest#response_sent()

Project: tapestry-5
File: JSONArrayEventResultProcessorTest.java
@Test
public void response_sent() throws IOException {
    String encoding = "UTF-8";
    Response response = mockResponse();
    CharArrayWriter writer = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(writer);
    expect(response.getPrintWriter("application/json;charset=UTF-8")).andReturn(pw);
    replay();
    JSONArray array = new JSONArray("   [ \"fred\", \"barney\" \n\n]");
    JSONArrayEventResultProcessor p = new JSONArrayEventResultProcessor(response, encoding, false);
    p.processResultValue(array);
    verify();
    assertEquals(writer.toString(), "[\n  \"fred\",\n  \"barney\"\n]");
}

18. Javac#compile()

Project: one-nio
File: Javac.java
public byte[] compile(CharSequence code) throws CompilationException {
    CharArrayWriter messages = new CharArrayWriter();
    List<String> options = Arrays.asList("-classpath", classPath);
    List<MemoryInputFileObject> input = Arrays.asList(new MemoryInputFileObject(code));
    final ByteArrayOutputStream output = new ByteArrayOutputStream(200);
    JavaFileManager manager = new ForwardingJavaFileManager<StandardJavaFileManager>(fileManager) {

        @Override
        public JavaFileObject getJavaFileForOutput(Location location, String className, JavaFileObject.Kind kind, FileObject sibling) {
            return new MemoryOutputFileObject(output);
        }
    };
    if (compiler.getTask(messages, manager, null, options, null, input).call()) {
        return output.toByteArray();
    }
    throw new CompilationException(messages.toString());
}

19. OldCharArrayWriterTest#test_ConstructorI()

Project: j2objc
File: OldCharArrayWriterTest.java
public void test_ConstructorI() {
    // Test for method java.io.CharArrayWriter(int)
    cw = new CharArrayWriter(90);
    assertEquals("Test 1: Incorrect writer created.", 0, cw.size());
    try {
        cw = new CharArrayWriter(-1);
        fail("IllegalArgumentException expected.");
    } catch (IllegalArgumentException e) {
    }
}

20. Connection#authenticateWithPublicKey()

Project: intellij-community
File: Connection.java
/**
	 * 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);
}

21. KerberosTestUtils#getControlDocument()

Project: directory-server
File: KerberosTestUtils.java
public static char[] getControlDocument(String resource) throws IOException {
    InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(resource);
    CharArrayWriter writer = new CharArrayWriter();
    try (Reader reader = new InputStreamReader(new BufferedInputStream(is))) {
        char[] buf = new char[2048];
        int len = 0;
        while (len >= 0) {
            len = reader.read(buf);
            if (len > 0) {
                writer.write(buf, 0, len);
            }
        }
    }
    char[] isca = writer.toCharArray();
    return isca;
}

22. ClobTest#testGetSubString_BiggerThanInternalBuffer()

Project: derby
File: ClobTest.java
/**
     * Tests if big strings can be handled.
     * <p>
     * The motivation for the test is to make sure big buffers are filled with
     * the call to read inside a loop. Big in this sense means bigger than some
     * internal buffer. This is typically around 8 KB or so, but we try
     * something considerably bigger. If a char/byte array is attempted filled
     * with a single call to read, the resulting string wil typically contain
     * \u0000 at positions after the size of the internal buffer.
     */
public void testGetSubString_BiggerThanInternalBuffer() throws IOException, SQLException {
    // 1 M characters
    int stringLength = 1 * 1024 * 1024;
    transferData(new LoopingAlphabetReader(stringLength), this.clob.setCharacterStream(1L), TRANSFER_BUFFER_SIZE);
    String obtained = this.clob.getSubString(1, stringLength);
    assertEquals("Incorrect string length", stringLength, obtained.length());
    // Obtain the string we inserted for comparison.
    CharArrayWriter charWriter = new CharArrayWriter();
    transferData(new LoopingAlphabetReader(stringLength), charWriter, TRANSFER_BUFFER_SIZE);
    assertEquals("String do not match", charWriter.toString(), obtained);
}

23. KnownHosts#initialize()

Project: connectbot
File: KnownHosts.java
private void initialize(File knownHosts) throws IOException {
    char[] buff = new char[512];
    CharArrayWriter cw = new CharArrayWriter();
    knownHosts.createNewFile();
    FileReader fr = new FileReader(knownHosts);
    while (true) {
        int len = fr.read(buff);
        if (len < 0)
            break;
        cw.write(buff, 0, len);
    }
    fr.close();
    initialize(cw.toCharArray());
}

24. Connection#authenticateWithPublicKey()

Project: connectbot
File: Connection.java
/**
	 * 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);
}

25. TestMultiRefIdentity#testEquality3()

Project: axis1-java
File: TestMultiRefIdentity.java
/**
       Tests when beans have same contents and use their own hashCode().
    */
public void testEquality3() throws Exception {
    TestBeanB tb1 = new TestBeanB();
    tb1.s1 = "john";
    TestBeanB tb2 = new TestBeanB();
    tb2.s1 = "john";
    CharArrayWriter caw = new CharArrayWriter();
    SerializationContext sci = new SerializationContext(caw);
    sci.setDoMultiRefs(true);
    sci.serialize(new QName("someLocalPart"), null, tb1);
    sci.serialize(new QName("someOtherLocalPart"), null, tb2);
    String s = caw.toString();
    // Cheap but fragile.
    int first = s.indexOf("#id0");
    int last = s.lastIndexOf("#id1");
    assertTrue(s, first >= 0);
    assertTrue(s, last >= 0 && last != first);
}

26. TestMultiRefIdentity#testEquality2()

Project: axis1-java
File: TestMultiRefIdentity.java
/**
       Tests when beans have same contents but rely on default hashCode().
    */
public void testEquality2() throws Exception {
    TestBeanA tb1 = new TestBeanA();
    tb1.s1 = "john";
    TestBeanA tb2 = new TestBeanA();
    tb2.s1 = "john";
    CharArrayWriter caw = new CharArrayWriter();
    SerializationContext sci = new SerializationContext(caw);
    sci.setDoMultiRefs(true);
    sci.serialize(new QName("someLocalPart"), null, tb1);
    sci.serialize(new QName("someOtherLocalPart"), null, tb2);
    String s = caw.toString();
    // Cheap but fragile.
    int first = s.indexOf("#id0");
    int last = s.lastIndexOf("#id1");
    assertTrue(s, first >= 0);
    assertTrue(s, last >= 0);
}

27. TestMultiRefIdentity#testEquality1()

Project: axis1-java
File: TestMultiRefIdentity.java
/**
       Tests when beans have different contents and rely on default hashCode().
    */
public void testEquality1() throws Exception {
    TestBeanA tb1 = new TestBeanA();
    tb1.s1 = "john";
    TestBeanA tb2 = new TestBeanA();
    tb2.s1 = "gregg";
    CharArrayWriter caw = new CharArrayWriter();
    SerializationContext sci = new SerializationContext(caw);
    sci.setDoMultiRefs(true);
    sci.serialize(new QName("someLocalPart"), null, tb1);
    sci.serialize(new QName("someOtherLocalPart"), null, tb2);
    String s = caw.toString();
    // Cheap but fragile.
    int first = s.indexOf("#id0");
    int last = s.lastIndexOf("#id1");
    assertTrue(s, first >= 0);
    assertTrue(s, last >= 0);
}

28. TestMultiRefIdentity#testIdentity2()

Project: axis1-java
File: TestMultiRefIdentity.java
/**
       Tests when beans are identical and use their own hashCode().
    */
public void testIdentity2() throws Exception {
    TestBeanB tb1 = new TestBeanB();
    tb1.s1 = "john";
    TestBeanB tb2 = tb1;
    CharArrayWriter caw = new CharArrayWriter();
    SerializationContext sci = new SerializationContext(caw);
    sci.setDoMultiRefs(true);
    sci.serialize(new QName("someLocalPart"), null, tb1);
    sci.serialize(new QName("someOtherLocalPart"), null, tb2);
    String s = caw.toString();
    // Cheap but fragile.
    int first = s.indexOf("#id0");
    int last = s.lastIndexOf("#id0");
    assertTrue(s, first >= 0);
    assertTrue(s, last >= 0 && last != first);
}

29. TestMultiRefIdentity#testIdentity1()

Project: axis1-java
File: TestMultiRefIdentity.java
/**
       Tests when beans are identical and use default hashCode().
    */
public void testIdentity1() throws Exception {
    TestBeanA tb1 = new TestBeanA();
    tb1.s1 = "john";
    TestBeanA tb2 = tb1;
    CharArrayWriter caw = new CharArrayWriter();
    SerializationContext sci = new SerializationContext(caw);
    sci.setDoMultiRefs(true);
    sci.serialize(new QName("someLocalPart"), null, tb1);
    sci.serialize(new QName("someOtherLocalPart"), null, tb2);
    String s = caw.toString();
    // Cheap but fragile.
    int first = s.indexOf("#id0");
    int last = s.lastIndexOf("#id0");
    assertTrue(s, first >= 0);
    assertTrue(s, last >= 0 && last != first);
}

30. KnownHosts#addHostkeyToFile()

Project: connectbot
File: KnownHosts.java
/**
	 * Adds a single public key entry to the a known_hosts file.
	 * This method is designed to be used in a {@link ServerHostKeyVerifier}.
	 * 
	 * @param knownHosts the file where the publickey entry will be appended.
	 * @param hostnames a list of hostname patterns - at least one most be specified. Check out the
	 *        OpenSSH sshd man page for a description of the pattern matching algorithm.
	 * @param serverHostKeyAlgorithm as passed to the {@link ServerHostKeyVerifier}.
	 * @param serverHostKey as passed to the {@link ServerHostKeyVerifier}.
	 * @throws IOException
	 */
public static final void addHostkeyToFile(File knownHosts, String[] hostnames, String serverHostKeyAlgorithm, byte[] serverHostKey) throws IOException {
    if ((hostnames == null) || (hostnames.length == 0))
        throw new IllegalArgumentException("Need at least one hostname specification");
    if ((serverHostKeyAlgorithm == null) || (serverHostKey == null))
        throw new IllegalArgumentException();
    CharArrayWriter writer = new CharArrayWriter();
    for (int i = 0; i < hostnames.length; i++) {
        if (i != 0)
            writer.write(',');
        writer.write(hostnames[i]);
    }
    writer.write(' ');
    writer.write(serverHostKeyAlgorithm);
    writer.write(' ');
    writer.write(Base64.encode(serverHostKey));
    writer.write("\n");
    char[] entry = writer.toCharArray();
    RandomAccessFile raf = new RandomAccessFile(knownHosts, "rw");
    long len = raf.length();
    if (len > 0) {
        raf.seek(len - 1);
        int last = raf.read();
        if (last != '\n')
            raf.write('\n');
    }
    raf.write(new String(entry).getBytes("ISO-8859-1"));
    raf.close();
}

31. OldCharArrayWriterTest#test_appendLjava_langCharSequenceII()

Project: j2objc
File: OldCharArrayWriterTest.java
public void test_appendLjava_langCharSequenceII() {
    String testString = "My Test String";
    CharArrayWriter writer = new CharArrayWriter(10);
    // Illegal argument checks.
    try {
        writer.append(testString, -1, 0);
        fail("Test 1: IndexOutOfBoundsException expected.");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        writer.append(testString, 0, -1);
        fail("Test 2: IndexOutOfBoundsException expected.");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        writer.append(testString, 1, 0);
        fail("Test 3: IndexOutOfBoundsException expected.");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        writer.append(testString, 1, testString.length() + 1);
        fail("Test 4: IndexOutOfBoundsException expected.");
    } catch (IndexOutOfBoundsException e) {
    }
    writer.append(testString, 1, 3);
    writer.flush();
    assertEquals("Test 5: Appending failed;", testString.substring(1, 3), writer.toString());
    writer.close();
}

32. JspReader#getText()

Project: sling
File: JspReader.java
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();
}

33. IOUtils#toCharArray()

Project: wicket
File: IOUtils.java
/**
	 * Get the contents of a <code>Reader</code> as a character array.
	 * <p>
	 * This method buffers the input internally, so there is no need to use a
	 * <code>BufferedReader</code>.
	 * 
	 * @param input
	 *            the <code>Reader</code> to read from
	 * @return the requested character array
	 * @throws NullPointerException
	 *             if the input is null
	 * @throws IOException
	 *             if an I/O error occurs
	 */
public static char[] toCharArray(final Reader input) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}

34. IOUtils#toCharArray()

Project: wicket
File: IOUtils.java
/**
	 * Get the contents of an <code>InputStream</code> as a character array using the specified
	 * character encoding.
	 * <p>
	 * Character encoding names can be found at <a
	 * href="http://www.iana.org/assignments/character-sets">IANA</a>.
	 * <p>
	 * This method buffers the input internally, so there is no need to use a
	 * <code>BufferedInputStream</code>.
	 * 
	 * @param is
	 *            the <code>InputStream</code> to read from
	 * @param encoding
	 *            the encoding to use, null means platform default
	 * @return the requested character array
	 * @throws NullPointerException
	 *             if the input is null
	 * @throws IOException
	 *             if an I/O error occurs
	 */
public static char[] toCharArray(final InputStream is, final String encoding) throws IOException {
    CharArrayWriter output = new CharArrayWriter();
    copy(is, output, encoding);
    return output.toCharArray();
}

35. IOUtils#toCharArray()

Project: wicket
File: IOUtils.java
/**
	 * Get the contents of an <code>InputStream</code> as a character array using the default
	 * character encoding of the platform.
	 * <p>
	 * This method buffers the input internally, so there is no need to use a
	 * <code>BufferedInputStream</code>.
	 * 
	 * @param is
	 *            the <code>InputStream</code> to read from
	 * @return the requested character array
	 * @throws NullPointerException
	 *             if the input is null
	 * @throws IOException
	 *             if an I/O error occurs
	 */
public static char[] toCharArray(final InputStream is) throws IOException {
    CharArrayWriter output = new CharArrayWriter();
    copy(is, output);
    return output.toCharArray();
}

36. IOUtils#toCharArray()

Project: ToolsFinal
File: IOUtils.java
/**
     * Get the contents of a <code>Reader</code> as a character array.
     * <p/>
     * This method buffers the input internally, so there is no need to use a
     * <code>BufferedReader</code>.
     *
     * @param input the <code>Reader</code> to read from
     * @return the requested character array
     * @throws NullPointerException if the input is null
     * @throws IOException  if an I/O error occurs
     * @since 1.1
     */
public static char[] toCharArray(Reader input) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}

37. IOUtils#toCharArray()

Project: ToolsFinal
File: IOUtils.java
/**
     * Get the contents of an <code>InputStream</code> as a character array
     * using the specified character encoding.
     * <p/>
     * This method buffers the input internally, so there is no need to use a
     * <code>BufferedInputStream</code>.
     *
     * @param is       the <code>InputStream</code> to read from
     * @param encoding the encoding to use, null means platform default
     * @return the requested character array
     * @throws NullPointerException if the input is null
     * @throws IOException  if an I/O error occurs
     * @since 2.3
     */
public static char[] toCharArray(InputStream is, Charset encoding) throws IOException {
    CharArrayWriter output = new CharArrayWriter();
    copy(is, output, encoding);
    return output.toCharArray();
}

38. JSONCollection#toCompactString()

Project: tapestry-5
File: JSONCollection.java
/**
     * Prints the JSONObject as a compact string (not extra punctuation). This is, essentially, what
     * Tapestry 5.1 did inside {@link #toString()}.
     */
public String toCompactString() {
    CharArrayWriter caw = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(caw);
    print(pw);
    pw.close();
    return caw.toString();
}

39. EventsLog#addMessage()

Project: SimpleServer
File: EventsLog.java
public void addMessage(String event, String message) {
    CharArrayWriter charWriter = new CharArrayWriter();
    PrintWriter writer = new PrintWriter(charWriter);
    writer.append(event + "\t" + message);
    super.addMessage(charWriter.toString());
    writer.close();
    charWriter.close();
}

40. IOTinyUtils#toString()

Project: rocketmq-all
File: IOTinyUtils.java
public static String toString(Reader reader) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(reader, sw);
    return sw.toString();
}

41. IOTinyUtils#toString()

Project: RocketMQ
File: IOTinyUtils.java
public static String toString(Reader reader) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(reader, sw);
    return sw.toString();
}

42. JaxbMatchers#toXml()

Project: isis
File: JaxbMatchers.java
public static <T> String toXml(final T dto) {
    final CharArrayWriter caw = new CharArrayWriter();
    toXml(dto, caw);
    return caw.toString();
}

43. InteractionDtoUtils#toXml()

Project: isis
File: InteractionDtoUtils.java
public static String toXml(final InteractionDto interactionDto) {
    final CharArrayWriter caw = new CharArrayWriter();
    toXml(interactionDto, caw);
    return caw.toString();
}

44. CommandDtoUtils#toXml()

Project: isis
File: CommandDtoUtils.java
public static String toXml(final CommandDto commandDto) {
    final CharArrayWriter caw = new CharArrayWriter();
    toXml(commandDto, caw);
    return caw.toString();
}

45. ChangesDtoUtils#toXml()

Project: isis
File: ChangesDtoUtils.java
public static String toXml(final ChangesDto changesDto) {
    final CharArrayWriter caw = new CharArrayWriter();
    toXml(changesDto, caw);
    return caw.toString();
}

46. JaxbUtil#toXml()

Project: isis
File: JaxbUtil.java
public static <T> String toXml(final T dto) {
    final CharArrayWriter caw = new CharArrayWriter();
    toXml(dto, caw);
    return caw.toString();
}

47. Base64#encode()

Project: intellij-community
File: Base64.java
public static char[] encode(byte[] content) {
    CharArrayWriter cw = new CharArrayWriter((4 * content.length) / 3);
    int idx = 0;
    int x = 0;
    for (int i = 0; i < content.length; i++) {
        if (idx == 0)
            x = (content[i] & 0xff) << 16;
        else if (idx == 1)
            x = x | ((content[i] & 0xff) << 8);
        else
            x = x | (content[i] & 0xff);
        idx++;
        if (idx == 3) {
            cw.write(alphabet[x >> 18]);
            cw.write(alphabet[(x >> 12) & 0x3f]);
            cw.write(alphabet[(x >> 6) & 0x3f]);
            cw.write(alphabet[x & 0x3f]);
            idx = 0;
        }
    }
    if (idx == 1) {
        cw.write(alphabet[x >> 18]);
        cw.write(alphabet[(x >> 12) & 0x3f]);
        cw.write('=');
        cw.write('=');
    }
    if (idx == 2) {
        cw.write(alphabet[x >> 18]);
        cw.write(alphabet[(x >> 12) & 0x3f]);
        cw.write(alphabet[(x >> 6) & 0x3f]);
        cw.write('=');
    }
    return cw.toCharArray();
}

48. Base64#encode()

Project: connectbot
File: Base64.java
public static char[] encode(byte[] content) {
    CharArrayWriter cw = new CharArrayWriter((4 * content.length) / 3);
    int idx = 0;
    int x = 0;
    for (int i = 0; i < content.length; i++) {
        if (idx == 0)
            x = (content[i] & 0xff) << 16;
        else if (idx == 1)
            x = x | ((content[i] & 0xff) << 8);
        else
            x = x | (content[i] & 0xff);
        idx++;
        if (idx == 3) {
            cw.write(alphabet[x >> 18]);
            cw.write(alphabet[(x >> 12) & 0x3f]);
            cw.write(alphabet[(x >> 6) & 0x3f]);
            cw.write(alphabet[x & 0x3f]);
            idx = 0;
        }
    }
    if (idx == 1) {
        cw.write(alphabet[x >> 18]);
        cw.write(alphabet[(x >> 12) & 0x3f]);
        cw.write('=');
        cw.write('=');
    }
    if (idx == 2) {
        cw.write(alphabet[x >> 18]);
        cw.write(alphabet[(x >> 12) & 0x3f]);
        cw.write(alphabet[(x >> 6) & 0x3f]);
        cw.write('=');
    }
    return cw.toCharArray();
}

49. IOUtils#toCharArray()

Project: commons-io
File: IOUtils.java
/**
     * Gets the contents of a <code>Reader</code> as a character array.
     * <p>
     * This method buffers the input internally, so there is no need to use a
     * <code>BufferedReader</code>.
     *
     * @param input the <code>Reader</code> to read from
     * @return the requested character array
     * @throws NullPointerException if the input is null
     * @throws IOException          if an I/O error occurs
     * @since 1.1
     */
public static char[] toCharArray(final Reader input) throws IOException {
    final CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}

50. IOUtils#toCharArray()

Project: commons-io
File: IOUtils.java
/**
     * Gets the contents of an <code>InputStream</code> as a character array
     * using the specified character encoding.
     * <p>
     * This method buffers the input internally, so there is no need to use a
     * <code>BufferedInputStream</code>.
     *
     * @param is the <code>InputStream</code> to read from
     * @param encoding the encoding to use, null means platform default
     * @return the requested character array
     * @throws NullPointerException if the input is null
     * @throws IOException          if an I/O error occurs
     * @since 2.3
     */
public static char[] toCharArray(final InputStream is, final Charset encoding) throws IOException {
    final CharArrayWriter output = new CharArrayWriter();
    copy(is, output, encoding);
    return output.toCharArray();
}

51. IOUtils#toCharArray()

Project: Android-RTEditor
File: IOUtils.java
/**
     * Get the contents of a <code>Reader</code> as a character array.
     * <p/>
     * This method buffers the input internally, so there is no need to use a
     * <code>BufferedReader</code>.
     *
     * @param input the <code>Reader</code> to read from
     * @return the requested character array
     * @throws NullPointerException if the input is null
     * @throws IOException          if an I/O error occurs
     * @since 1.1
     */
public static char[] toCharArray(Reader input) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}

52. IOUtils#toCharArray()

Project: Android-RTEditor
File: IOUtils.java
/**
     * Get the contents of an <code>InputStream</code> as a character array
     * using the specified character encoding.
     * <p/>
     * This method buffers the input internally, so there is no need to use a
     * <code>BufferedInputStream</code>.
     *
     * @param is       the <code>InputStream</code> to read from
     * @param encoding the encoding to use, null means platform default
     * @return the requested character array
     * @throws NullPointerException if the input is null
     * @throws IOException          if an I/O error occurs
     * @since 2.3
     */
public static char[] toCharArray(InputStream is, Charset encoding) throws IOException {
    CharArrayWriter output = new CharArrayWriter();
    copy(is, output, encoding);
    return output.toCharArray();
}

53. IOUtils#readChars()

Project: Android-Next
File: IOUtils.java
public static char[] readChars(Reader input) throws IOException {
    CharArrayWriter sw = new CharArrayWriter();
    copy(input, sw);
    return sw.toCharArray();
}

54. IOUtils#readChars()

Project: Android-Next
File: IOUtils.java
public static char[] readChars(InputStream is, Charset encoding) throws IOException {
    CharArrayWriter output = new CharArrayWriter();
    copy(is, output, encoding);
    return output.toCharArray();
}

55. UrlEncoder#encode()

Project: wicket
File: UrlEncoder.java
/**
	 * @param unsafeInput
	 *            string to encode
	 * @param charsetName
	 *            encoding to use
	 * @return encoded string
	 * @see java.net.URLEncoder#encode(String, String)
	 */
public String encode(final String unsafeInput, final String charsetName) {
    final String s = unsafeInput.replace("\0", "NULL");
    StringBuilder out = new StringBuilder(s.length());
    Charset charset;
    CharArrayWriter charArrayWriter = new CharArrayWriter();
    Args.notNull(charsetName, "charsetName");
    try {
        charset = Charset.forName(charsetName);
    } catch (IllegalCharsetNameExceptionUnsupportedCharsetException |  e) {
        throw new RuntimeException(new UnsupportedEncodingException(charsetName));
    }
    for (int i = 0; i < s.length(); ) {
        int c = s.charAt(i);
        // System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            if (c == ' ') {
                c = '+';
            }
            // System.out.println("Storing: " + c);
            out.append((char) c);
            i++;
        } else {
            // convert to external encoding before hex conversion
            do {
                charArrayWriter.write(c);
                /*
					 * If this character represents the start of a Unicode surrogate pair, then pass
					 * in two characters. It's not clear what should be done if a bytes reserved in
					 * the surrogate pairs range occurs outside of a legal surrogate pair. For now,
					 * just treat it as if it were any other character.
					 */
                if ((c >= 0xD800) && (c <= 0xDBFF)) {
                    /*
						 * System.out.println(Integer.toHexString(c) + " is high surrogate");
						 */
                    if ((i + 1) < s.length()) {
                        int d = s.charAt(i + 1);
                        /*
							 * System.out.println("\tExamining " + Integer.toHexString(d));
							 */
                        if ((d >= 0xDC00) && (d <= 0xDFFF)) {
                            /*
								 * System.out.println("\t" + Integer.toHexString(d) + " is low
								 * surrogate");
								 */
                            charArrayWriter.write(d);
                            i++;
                        }
                    }
                }
                i++;
            } while ((i < s.length()) && !dontNeedEncoding.get((c = s.charAt(i))));
            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charset);
            for (byte b : ba) {
                out.append('%');
                char ch = Character.forDigit((b >> 4) & 0xF, 16);
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(b & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
        }
    }
    return out.toString();
}

56. TestPageRenderSupport#newWriter()

Project: tapestry4
File: TestPageRenderSupport.java
private IMarkupWriter newWriter() {
    _writer = new CharArrayWriter();
    return new MarkupWriterImpl("text/html", new PrintWriter(_writer), new AsciiMarkupFilter());
}

57. TestMarkupWriter#newPrintWriter()

Project: tapestry4
File: TestMarkupWriter.java
private PrintWriter newPrintWriter() {
    _writer = new CharArrayWriter();
    return new PrintWriter(_writer);
}

58. BaseComponentTestCase#newBufferWriter()

Project: tapestry4
File: BaseComponentTestCase.java
protected IMarkupWriter newBufferWriter() {
    _charArrayWriter = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(_charArrayWriter);
    return new MarkupWriterImpl("text/html", pw, new AsciiMarkupFilter());
}

59. ShowEngine#dumpSerializedEngine()

Project: tapestry3
File: ShowEngine.java
private void dumpSerializedEngine(IMarkupWriter responseWriter) {
    CharArrayWriter writer = null;
    BinaryDumpOutputStream bos = null;
    try {
        // Because IReponseWriter doesn't implement the
        // java.io.Writer interface, we have to buffer this
        // stuff then pack it in all at once.  Kind of a waste!
        writer = new CharArrayWriter();
        bos = new BinaryDumpOutputStream(writer);
        bos.setBytesPerLine(32);
        bos.write(getSerializedEngine());
        bos.close();
        responseWriter.print(writer.toString());
    } catch (IOException ex) {
    } finally {
        if (bos != null) {
            try {
                bos.close();
            } catch (IOException ex) {
            }
        }
        if (writer != null) {
            writer.reset();
            writer.close();
        }
    }
}

60. Parser#parseTemplateText()

Project: sling
File: Parser.java
/*
     * Parse for a template text string until '<' or "${" or "#{" is encountered,
     * recognizing escape sequences "\%", "\$", and "\#".
     */
private void parseTemplateText(Node parent) throws JasperException {
    if (!reader.hasMoreInput())
        return;
    CharArrayWriter ttext = new CharArrayWriter();
    // Output the first character
    int ch = reader.nextChar();
    if (ch == '\\') {
        reader.pushChar();
    } else {
        ttext.write(ch);
    }
    while (reader.hasMoreInput()) {
        ch = reader.nextChar();
        if (ch == '<') {
            reader.pushChar();
            break;
        } else if (ch == '$' || ch == '#') {
            if (!reader.hasMoreInput()) {
                ttext.write(ch);
                break;
            }
            if (reader.nextChar() == '{') {
                reader.pushChar();
                reader.pushChar();
                break;
            }
            ttext.write(ch);
            reader.pushChar();
            continue;
        } else if (ch == '\\') {
            if (!reader.hasMoreInput()) {
                ttext.write('\\');
                break;
            }
            char next = (char) reader.peekChar();
            // convolude multiple steps at once and create confusing parsers...)
            if (next == '%' || next == '$' || next == '#') {
                ch = reader.nextChar();
            }
        }
        ttext.write(ch);
    }
    new Node.TemplateText(ttext.toString(), start, parent);
}

61. XLContentDigester#getContent()

Project: sakai
File: XLContentDigester.java
/* (non-Javadoc)
	 * @see org.sakaiproject.search.component.adapter.contenthosting.ContentDigester#getContent(org.sakaiproject.content.api.ContentResource)
	 */
public String getContent(ContentResource contentResource) {
    CharArrayWriter writer = new CharArrayWriter();
    loadContent(writer, contentResource);
    return new String(writer.toCharArray());
}

62. XLContentDigester#getContentReader()

Project: sakai
File: XLContentDigester.java
/*
	 * (non-Javadoc)
	 * 
	 * @see org.sakaiproject.search.component.adapter.contenthosting.BaseContentDigester#getContentReader(org.sakaiproject.content.api.ContentResource)
	 */
public Reader getContentReader(ContentResource contentResource) {
    CharArrayWriter writer = new CharArrayWriter();
    loadContent(writer, contentResource);
    return new CharArrayReader(writer.toCharArray());
}

63. AbstractInterpreterEditor#getNewInputObject()

Project: Pydev
File: AbstractInterpreterEditor.java
@Override
protected Tuple<String, String> getNewInputObject(int configType) {
    CharArrayWriter charWriter = new CharArrayWriter();
    PrintWriter logger = new PrintWriter(charWriter);
    try {
        ObtainInterpreterInfoOperation operation = null;
        if (configType != InterpreterConfigHelpers.CONFIG_MANUAL) {
            //Auto-config
            AutoConfigMaker a = new AutoConfigMaker(getInterpreterType(), configType == InterpreterConfigHelpers.CONFIG_ADV_AUTO, logger, nameToInfo);
            operation = a.autoConfigSearch();
        } else {
            //Manual config
            logger.println("Information about process of adding new interpreter:");
            Tuple<String, String> interpreterNameAndExecutable = newConfig(logger);
            if (interpreterNameAndExecutable == null) {
                return null;
            }
            interpreterNameAndExecutable.o1 = InterpreterConfigHelpers.getUniqueInterpreterName(interpreterNameAndExecutable.o1, nameToInfo);
            boolean foundError = InterpreterConfigHelpers.checkInterpreterNameAndExecutable(interpreterNameAndExecutable, logger, "Error getting info on interpreter", nameToInfo, this.getShell());
            if (foundError) {
                return null;
            }
            logger.println("- Chosen interpreter (name and file):'" + interpreterNameAndExecutable);
            if (interpreterNameAndExecutable != null && interpreterNameAndExecutable.o2 != null) {
                //ok, now that we got the file, let's see if it is valid and get the library info.
                operation = InterpreterConfigHelpers.tryInterpreter(interpreterNameAndExecutable, interpreterManager, false, true, logger, this.getShell());
            }
        }
        if (operation != null) {
            String newName = operation.result.getName();
            this.nameToInfo.put(newName, operation.result.makeCopy());
            exeOrJarOfInterpretersToRestore.add(operation.result.executableOrJar);
            return new Tuple<String, String>(operation.result.getName(), operation.result.executableOrJar);
        }
    } catch (Exception e) {
        Log.log(e);
        return null;
    } finally {
        String logInfo = charWriter.toString();
        if (logInfo.length() > 0) {
            Log.logInfo(charWriter.toString());
        }
    }
    return null;
}

64. ProtoParser#parse()

Project: protoparser
File: ProtoParser.java
/** Parse a named {@code .proto} schema. The {@code Reader} is not closed. */
public static ProtoFile parse(String name, Reader reader) throws IOException {
    CharArrayWriter writer = new CharArrayWriter();
    char[] buffer = new char[1024];
    int count;
    while ((count = reader.read(buffer)) != -1) {
        writer.write(buffer, 0, count);
    }
    return new ProtoParser(name, writer.toCharArray()).readProtoFile();
}

65. InsertBatch#insertCopy()

Project: pgjdbc
File: InsertBatch.java
@Benchmark
public void insertCopy(Blackhole b) throws SQLException, IOException {
    CopyManager copyAPI = ((PGConnection) connection).getCopyAPI();
    CharArrayWriter wr = new CharArrayWriter();
    for (int i = 0; i < p1nrows; ) {
        CopyIn copyIn = copyAPI.copyIn("COPY batch_perf_test FROM STDIN");
        wr.reset();
        for (int k = 0; k < p2multi; k++, i++) {
            wr.append(Integer.toString(i));
            wr.append('\t');
            String str = strings[i];
            if (str != null) {
                boolean hasTabs = str.indexOf('\t') != -1;
                if (hasTabs) {
                    wr.append("\"");
                    wr.append(str.replace("\"", "\"\""));
                    wr.append("\"");
                } else {
                    wr.append(str);
                }
            }
            wr.append('\t');
            wr.append(Integer.toString(i));
            wr.append('\n');
        }
        byte[] bytes = wr.toString().getBytes("UTF-8");
        copyIn.writeToCopy(bytes, 0, bytes.length);
        b.consume(copyIn.endCopy());
    }
}

66. InsertBatch#insertStruct()

Project: pgjdbc
File: InsertBatch.java
@Benchmark
public int[] insertStruct() throws SQLException, IOException {
    CharArrayWriter wr = new CharArrayWriter();
    for (int i = 0; i < p1nrows; ) {
        wr.reset();
        wr.append('{');
        for (int k = 0; k < p2multi; k++, i++) {
            if (k != 0) {
                wr.append(',');
            }
            wr.append("\"(");
            wr.append(Integer.toString(i));
            wr.append(',');
            String str = strings[i];
            if (str != null) {
                boolean hasQuotes = str.indexOf('"') != -1;
                if (hasQuotes) {
                    wr.append("\"");
                    wr.append(str.replace("\"", "\\\""));
                    wr.append("\"");
                } else {
                    wr.append(str);
                }
            }
            wr.append(',');
            wr.append(Integer.toString(i));
            wr.append(")\"");
        }
        wr.append('}');
        structInsert.setString(1, wr.toString());
        structInsert.addBatch();
    }
    return structInsert.executeBatch();
}

67. RhinoException#generateStackTrace()

Project: pad
File: RhinoException.java
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;
}

68. Context#getSourcePositionFromStack()

Project: pad
File: Context.java
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) {
                }
            }
            open = close = colon = -1;
        }
    }
    return null;
}

69. ActionHelper#getChildren()

Project: openjdk
File: ActionHelper.java
public List<Long> getChildren(HtmlSection section, long pid) {
    String pidStr = "" + pid;
    ProcessBuilder pb = getChildren.prepareProcess(section, this, pidStr);
    PrintWriter log = getChildren.getSection(section).getWriter();
    CharArrayWriter writer = new CharArrayWriter();
    ExitCode code = run(log, writer, pb, getChildren.getParameters());
    Reader output = new CharArrayReader(writer.toCharArray());
    if (!ExitCode.OK.equals(code)) {
        log.println("WARNING: get children pids action failed");
        try {
            Utils.copyStream(output, log);
        } catch (IOException e) {
            e.printStackTrace(log);
        }
        return Collections.emptyList();
    }
    List<Long> result = new ArrayList<>();
    try {
        try (BufferedReader reader = new BufferedReader(output)) {
            String line;
            while ((line = reader.readLine()) != null) {
                String value = line.trim();
                if (value.isEmpty()) {
                    // ignore empty lines
                    continue;
                }
                try {
                    result.add(Long.valueOf(value));
                } catch (NumberFormatException e) {
                    log.printf("WARNING: can't parse child pid %s : %s%n", line, e.getMessage());
                    e.printStackTrace(log);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace(log);
    }
    return result;
}

70. DriverManagerTests#tests18()

Project: openjdk
File: DriverManagerTests.java
/**
     * 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()));
    }
}

71. URLEncoder#encode()

Project: openjdk
File: URLEncoder.java
/**
     * Translates a string into {@code application/x-www-form-urlencoded}
     * format using a specific encoding scheme. This method uses the
     * supplied encoding scheme to obtain the bytes for unsafe
     * characters.
     * <p>
     * <em><strong>Note:</strong> The <a href=
     * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
     * World Wide Web Consortium Recommendation</a> states that
     * UTF-8 should be used. Not doing so may introduce
     * incompatibilities.</em>
     *
     * @param   s   {@code String} to be translated.
     * @param   enc   The name of a supported
     *    <a href="../lang/package-summary.html#charenc">character
     *    encoding</a>.
     * @return  the translated {@code String}.
     * @exception  UnsupportedEncodingException
     *             If the named encoding is not supported
     * @see URLDecoder#decode(java.lang.String, java.lang.String)
     * @since 1.4
     */
public static String encode(String s, String enc) throws UnsupportedEncodingException {
    boolean needToChange = false;
    StringBuilder out = new StringBuilder(s.length());
    Charset charset;
    CharArrayWriter charArrayWriter = new CharArrayWriter();
    if (enc == null)
        throw new NullPointerException("charsetName");
    try {
        charset = Charset.forName(enc);
    } catch (IllegalCharsetNameException e) {
        throw new UnsupportedEncodingException(enc);
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException(enc);
    }
    for (int i = 0; i < s.length(); ) {
        int c = (int) s.charAt(i);
        //System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            if (c == ' ') {
                c = '+';
                needToChange = true;
            }
            //System.out.println("Storing: " + c);
            out.append((char) c);
            i++;
        } else {
            // convert to external encoding before hex conversion
            do {
                charArrayWriter.write(c);
                /*
                     * If this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a byte reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                if (c >= 0xD800 && c <= 0xDBFF) {
                    /*
                          System.out.println(Integer.toHexString(c)
                          + " is high surrogate");
                        */
                    if ((i + 1) < s.length()) {
                        int d = (int) s.charAt(i + 1);
                        /*
                              System.out.println("\tExamining "
                              + Integer.toHexString(d));
                            */
                        if (d >= 0xDC00 && d <= 0xDFFF) {
                            /*
                                  System.out.println("\t"
                                  + Integer.toHexString(d)
                                  + " is low surrogate");
                                */
                            charArrayWriter.write(d);
                            i++;
                        }
                    }
                }
                i++;
            } while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i))));
            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charset);
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
            needToChange = true;
        }
    }
    return (needToChange ? out.toString() : s);
}

72. URLEncoder#encode()

Project: jdk7u-jdk
File: URLEncoder.java
/**
     * Translates a string into <code>application/x-www-form-urlencoded</code>
     * format using a specific encoding scheme. This method uses the
     * supplied encoding scheme to obtain the bytes for unsafe
     * characters.
     * <p>
     * <em><strong>Note:</strong> The <a href=
     * "http://www.w3.org/TR/html40/appendix/notes.html#non-ascii-chars">
     * World Wide Web Consortium Recommendation</a> states that
     * UTF-8 should be used. Not doing so may introduce
     * incompatibilites.</em>
     *
     * @param   s   <code>String</code> to be translated.
     * @param   enc   The name of a supported
     *    <a href="../lang/package-summary.html#charenc">character
     *    encoding</a>.
     * @return  the translated <code>String</code>.
     * @exception  UnsupportedEncodingException
     *             If the named encoding is not supported
     * @see URLDecoder#decode(java.lang.String, java.lang.String)
     * @since 1.4
     */
public static String encode(String s, String enc) throws UnsupportedEncodingException {
    boolean needToChange = false;
    StringBuffer out = new StringBuffer(s.length());
    Charset charset;
    CharArrayWriter charArrayWriter = new CharArrayWriter();
    if (enc == null)
        throw new NullPointerException("charsetName");
    try {
        charset = Charset.forName(enc);
    } catch (IllegalCharsetNameException e) {
        throw new UnsupportedEncodingException(enc);
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException(enc);
    }
    for (int i = 0; i < s.length(); ) {
        int c = (int) s.charAt(i);
        //System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(c)) {
            if (c == ' ') {
                c = '+';
                needToChange = true;
            }
            //System.out.println("Storing: " + c);
            out.append((char) c);
            i++;
        } else {
            // convert to external encoding before hex conversion
            do {
                charArrayWriter.write(c);
                /*
                     * If this character represents the start of a Unicode
                     * surrogate pair, then pass in two characters. It's not
                     * clear what should be done if a bytes reserved in the
                     * surrogate pairs range occurs outside of a legal
                     * surrogate pair. For now, just treat it as if it were
                     * any other character.
                     */
                if (c >= 0xD800 && c <= 0xDBFF) {
                    /*
                          System.out.println(Integer.toHexString(c)
                          + " is high surrogate");
                        */
                    if ((i + 1) < s.length()) {
                        int d = (int) s.charAt(i + 1);
                        /*
                              System.out.println("\tExamining "
                              + Integer.toHexString(d));
                            */
                        if (d >= 0xDC00 && d <= 0xDFFF) {
                            /*
                                  System.out.println("\t"
                                  + Integer.toHexString(d)
                                  + " is low surrogate");
                                */
                            charArrayWriter.write(d);
                            i++;
                        }
                    }
                }
                i++;
            } while (i < s.length() && !dontNeedEncoding.get((c = (int) s.charAt(i))));
            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charset);
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // the hex value if ch is a letter.
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
                ch = Character.forDigit(ba[j] & 0xF, 16);
                if (Character.isLetter(ch)) {
                    ch -= caseDiff;
                }
                out.append(ch);
            }
            charArrayWriter.reset();
            needToChange = true;
        }
    }
    return (needToChange ? out.toString() : s);
}

73. OldCharArrayWriterTest#setUp()

Project: j2objc
File: OldCharArrayWriterTest.java
protected void setUp() {
    cw = new CharArrayWriter();
}

74. OldCharArrayWriterTest#test_write$CII_Exception()

Project: j2objc
File: OldCharArrayWriterTest.java
public void test_write$CII_Exception() {
    char[] target = new char[10];
    cw = new CharArrayWriter();
    try {
        cw.write(target, -1, 1);
        fail("Test 1: IndexOutOfBoundsException expected.");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        cw.write(target, 0, -1);
        fail("Test 2: IndexOutOfBoundsException expected.");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        cw.write(target, 1, target.length);
        fail("Test 3: IndexOutOfBoundsException expected.");
    } catch (IndexOutOfBoundsException e) {
    }
    try {
        cw.write((char[]) null, 1, 1);
        fail("Test 4: NullPointerException expected.");
    } catch (NullPointerException e) {
    }
}

75. DomSerializerJaxp#serialize()

Project: isis
File: DomSerializerJaxp.java
@Override
public String serialize(final Element domElement) {
    final CharArrayWriter caw = new CharArrayWriter();
    try {
        serializeTo(domElement, caw);
        return caw.toString();
    } catch (final Exception e) {
        return null;
    }
}

76. XMLOutputterTest#printElement()

Project: intellij-community
File: XMLOutputterTest.java
private String printElement(Element root) throws IOException {
    XMLOutputter xmlOutputter = JDOMUtil.createOutputter("\n");
    final Format format = xmlOutputter.getFormat().setOmitDeclaration(true).setOmitEncoding(true).setExpandEmptyElements(true);
    xmlOutputter.setFormat(format);
    CharArrayWriter writer = new CharArrayWriter();
    xmlOutputter.output(root, writer);
    String res = new String(writer.toCharArray());
    return res;
}

77. SchemaResolver#getInputSource()

Project: incubator-taverna-common-activities
File: SchemaResolver.java
public InputSource getInputSource(Element element) throws IOException {
    CharArrayWriter writer = new CharArrayWriter();
    try {
        TransformerFactory.newInstance().newTransformer().transform(new DOMSource(element), new StreamResult(writer));
    } catch (TransformerException ex) {
        throw new IOException(ex.getMessage(), ex);
    }
    InputSource source = new InputSource(new StringReader(writer.toString()));
    String publicId = element.getAttribute("targetNamespace");
    source.setPublicId(publicId);
    if (publicId.isEmpty()) {
        //source.setPublicId(element.getNamespaceURI());
        // if the element has no targetNamespace defined, provide a synthetic systemId, so both publicId = "" + systenId never clashes.
        URI base = URI.create(baseUri);
        URI synthetic;
        try {
            synthetic = new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), base.getPath(), base.getQuery(), String.valueOf(element.hashCode()));
        } catch (URISyntaxException ex) {
            synthetic = base;
        }
        source.setSystemId(synthetic.toString());
    } else {
        source.setSystemId(baseUri);
    }
    return source;
}

78. TrendLoader#doLoadInBackground()

Project: gh4a
File: TrendLoader.java
@Override
public List<Trend> doLoadInBackground() throws Exception {
    URL url = new URL(mUrl);
    List<Trend> trends = new ArrayList<>();
    HttpURLConnection connection = null;
    CharArrayWriter writer = null;
    JSONObject input = new JSONObject().put("input", new JSONObject().put("webpage/url", mQueryTarget));
    try {
        connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setDoInput(true);
        connection.setDoOutput(true);
        DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
        try {
            dos.write(input.toString().getBytes());
            dos.flush();
        } finally {
            dos.close();
        }
        if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
            return trends;
        }
        InputStream in = new BufferedInputStream(connection.getInputStream());
        InputStreamReader reader = new InputStreamReader(in, "UTF-8");
        int length = connection.getContentLength();
        writer = new CharArrayWriter(Math.max(0, length));
        char[] tmp = new char[1024];
        int l;
        while ((l = reader.read(tmp)) != -1) {
            writer.write(tmp, 0, l);
        }
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (writer != null) {
            writer.close();
        }
    }
    JSONObject jsonObject = new JSONObject(writer.toString());
    JSONArray resultArray = jsonObject.getJSONArray("results");
    for (int i = 0; i < resultArray.length(); i++) {
        JSONObject repoObject = resultArray.getJSONObject(i);
        Trend trend = new Trend();
        trend.setRepo(repoObject.getString("owner"), repoObject.getString("repo"));
        trend.setDescription(repoObject.optString("description"));
        trends.add(trend);
    }
    return trends;
}

79. Native#characters_to()

Project: erjang
File: Native.java
public static EObject characters_to(EObject charlist, EObject encodingSpec, CharArrayConverter output_converter) {
    Charset encoding = encodingSpecToCharset(encodingSpec);
    if (encoding == null)
        throw ERT.badarg(charlist, encodingSpec);
    CharArrayWriter out = new CharArrayWriter();
    CharCollector collector = new CharCollector(encoding, out);
    ESeq rest = ERT.NIL;
    try {
        rest = charlist.collectCharList(collector, rest);
    } catch (CharCollector.InvalidElementException e) {
        throw ERT.badarg(charlist, encodingSpec);
    } catch (CharCollector.CollectingException e) {
        EObject data = output_converter.convert(out);
        return ETuple.make(ERROR_ATOM, data, e.restOfInput);
    } catch (IOException e) {
        throw new Error(e);
    }
    try {
        collector.end();
        if (rest != ERT.NIL) {
            return ETuple.make(INCOMPLETE_ATOM, output_converter.convert(out), ErlConvert.iolist_to_binary(rest.reverse()));
        }
    } catch (CharCollector.PartialDecodingException e) {
        EObject data = output_converter.convert(out);
        return ETuple.make(INCOMPLETE_ATOM, data);
    } catch (IOException e) {
        throw new Error(e);
    }
    return output_converter.convert(out);
}

80. XMLOutputterTest#printElement()

Project: consulo
File: XMLOutputterTest.java
private String printElement(Element root) throws IOException {
    XMLOutputter xmlOutputter = JDOMUtil.createOutputter("\n");
    final Format format = xmlOutputter.getFormat().setOmitDeclaration(true).setOmitEncoding(true).setExpandEmptyElements(true);
    xmlOutputter.setFormat(format);
    CharArrayWriter writer = new CharArrayWriter();
    xmlOutputter.output(root, writer);
    String res = new String(writer.toCharArray());
    return res;
}

81. WebDAVMethod#createXMLWriter()

Project: community-edition
File: WebDAVMethod.java
/**
     * Create an XML writer for the response
     * 
     * @return XMLWriter
     * @exception IOException
     */
protected final XMLWriter createXMLWriter() throws IOException {
    // Buffer the XML response, in case we have to reset mid-transaction
    m_xmlWriter = new CharArrayWriter(1024);
    return new XMLWriter(m_xmlWriter, getXMLOutputFormat());
}

82. MlpModelTest#testLoad()

Project: aerosolve
File: MlpModelTest.java
@Test
public void testLoad() {
    CharArrayWriter charWriter = new CharArrayWriter();
    BufferedWriter writer = new BufferedWriter(charWriter);
    // create header record
    ModelHeader header = new ModelHeader();
    header.setModelType("multilayer_perceptron");
    header.setNumHiddenLayers(1);
    ArrayList<Integer> nodeNum = new ArrayList<>(2);
    nodeNum.add(3);
    nodeNum.add(1);
    header.setNumberHiddenNodes(nodeNum);
    header.setNumRecords(2);
    ModelRecord record1 = new ModelRecord();
    record1.setModelHeader(header);
    // create records for input layer
    ModelRecord record2 = new ModelRecord();
    record2.setFeatureFamily("in");
    record2.setFeatureName("a");
    ArrayList<Double> in1 = new ArrayList<>();
    in1.add(0.0);
    in1.add(1.0);
    in1.add(1.0);
    record2.setWeightVector(in1);
    ModelRecord record3 = new ModelRecord();
    record3.setFeatureFamily("in");
    record3.setFeatureName("b");
    ArrayList<Double> in2 = new ArrayList<>();
    in2.add(1.0);
    in2.add(1.0);
    in2.add(0.0);
    record3.setWeightVector(in2);
    // create records for bias
    ModelRecord record4 = new ModelRecord();
    ArrayList<Double> b1 = new ArrayList<>();
    b1.add(0.0);
    b1.add(0.0);
    b1.add(0.0);
    record4.setWeightVector(b1);
    record4.setFunctionForm(FunctionForm.RELU);
    ModelRecord record5 = new ModelRecord();
    ArrayList<Double> b2 = new ArrayList<>();
    b2.add(0.0);
    record5.setWeightVector(b2);
    record5.setFunctionForm(FunctionForm.RELU);
    // create records for hidden layer
    ModelRecord record6 = new ModelRecord();
    ArrayList<Double> h1 = new ArrayList<>();
    h1.add(0.5);
    record6.setWeightVector(h1);
    ModelRecord record7 = new ModelRecord();
    ArrayList<Double> h2 = new ArrayList<>();
    h2.add(1.0);
    record7.setWeightVector(h2);
    ModelRecord record8 = new ModelRecord();
    ArrayList<Double> h3 = new ArrayList<>();
    h3.add(2.0);
    record8.setWeightVector(h3);
    try {
        writer.write(Util.encode(record1) + "\n");
        writer.write(Util.encode(record2) + "\n");
        writer.write(Util.encode(record3) + "\n");
        writer.write(Util.encode(record4) + "\n");
        writer.write(Util.encode(record5) + "\n");
        writer.write(Util.encode(record6) + "\n");
        writer.write(Util.encode(record7) + "\n");
        writer.write(Util.encode(record8) + "\n");
        writer.close();
    } catch (IOException e) {
        assertTrue("Could not write", false);
    }
    String serialized = charWriter.toString();
    assertTrue(serialized.length() > 0);
    StringReader strReader = new StringReader(serialized);
    BufferedReader reader = new BufferedReader(strReader);
    FeatureVector fv = makeFeatureVector();
    try {
        Optional<AbstractModel> model = ModelFactory.createFromReader(reader);
        assertTrue(model.isPresent());
        float s = model.get().scoreItem(fv);
        assertEquals(s, 6.0f, 1e-10f);
    } catch (IOException e) {
        assertTrue("Could not read", false);
    }
}

83. LowRankLinearModelTest#testLoad()

Project: aerosolve
File: LowRankLinearModelTest.java
@Test
public void testLoad() {
    CharArrayWriter charWriter = new CharArrayWriter();
    BufferedWriter writer = new BufferedWriter(charWriter);
    ModelHeader header = new ModelHeader();
    header.setModelType("low_rank_linear");
    header.setLabelDictionary(makeLabelDictionary());
    Map<String, FloatVector> labelWeightVector = makeLabelWeightVector();
    Map<String, java.util.List<Double>> labelEmbedding = new HashMap<>();
    for (Map.Entry<String, FloatVector> labelRepresentation : labelWeightVector.entrySet()) {
        float[] values = labelRepresentation.getValue().getValues();
        ArrayList<Double> arrayList = new ArrayList<>();
        for (int i = 0; i < 3; i++) {
            arrayList.add((double) values[i]);
        }
        labelEmbedding.put(labelRepresentation.getKey(), arrayList);
    }
    header.setLabelEmbedding(labelEmbedding);
    header.setNumRecords(4);
    ArrayList<Double> ws = new ArrayList<>();
    ws.add(1.0);
    ws.add(0.0);
    ws.add(0.0);
    ModelRecord record1 = new ModelRecord();
    record1.setModelHeader(header);
    ModelRecord record2 = new ModelRecord();
    record2.setFeatureFamily("a");
    record2.setFeatureName("cat");
    record2.setWeightVector(ws);
    ModelRecord record3 = new ModelRecord();
    record3.setFeatureFamily("a");
    record3.setFeatureName("dog");
    record3.setWeightVector(ws);
    ModelRecord record4 = new ModelRecord();
    record4.setFeatureFamily("a");
    record4.setFeatureName("fish");
    record4.setWeightVector(ws);
    ModelRecord record5 = new ModelRecord();
    record5.setFeatureFamily("a");
    record5.setFeatureName("horse");
    record5.setWeightVector(ws);
    try {
        writer.write(Util.encode(record1) + "\n");
        writer.write(Util.encode(record2) + "\n");
        writer.write(Util.encode(record3) + "\n");
        writer.write(Util.encode(record4) + "\n");
        writer.write(Util.encode(record5) + "\n");
        writer.close();
    } catch (IOException e) {
        assertTrue("Could not write", false);
    }
    String serialized = charWriter.toString();
    assertTrue(serialized.length() > 0);
    StringReader strReader = new StringReader(serialized);
    BufferedReader reader = new BufferedReader(strReader);
    FeatureVector animalFv = makeFeatureVector("animal");
    FeatureVector colorFv = makeFeatureVector("color");
    try {
        Optional<AbstractModel> model = ModelFactory.createFromReader(reader);
        assertTrue(model.isPresent());
        ArrayList<MulticlassScoringResult> s1 = model.get().scoreItemMulticlass(animalFv);
        assertEquals(s1.size(), 3);
        assertEquals(0.0f, s1.get(0).score, 3.0f);
        assertEquals(0.0f, s1.get(1).score, 1e-10f);
        assertEquals(0.0f, s1.get(2).score, 1e-10f);
        ArrayList<MulticlassScoringResult> s2 = model.get().scoreItemMulticlass(colorFv);
        assertEquals(s2.size(), 3);
        assertEquals(0.0f, s2.get(0).score, 1e-10f);
        assertEquals(0.0f, s2.get(1).score, 1e-10f);
        assertEquals(0.0f, s2.get(2).score, 1e-10f);
    } catch (IOException e) {
        assertTrue("Could not read", false);
    }
}

84. AdditiveModelTest#testLoad()

Project: aerosolve
File: AdditiveModelTest.java
@Test
public void testLoad() {
    CharArrayWriter charWriter = new CharArrayWriter();
    BufferedWriter writer = new BufferedWriter(charWriter);
    ModelHeader header = new ModelHeader();
    header.setModelType("additive");
    header.setNumRecords(4);
    ArrayList<Double> ws = new ArrayList<Double>();
    ws.add(5.0);
    ws.add(10.0);
    ws.add(-20.0);
    ArrayList<Double> wl = new ArrayList<Double>();
    wl.add(1.0);
    wl.add(2.0);
    ModelRecord record1 = new ModelRecord();
    record1.setModelHeader(header);
    ModelRecord record2 = new ModelRecord();
    record2.setFunctionForm(FunctionForm.Spline);
    record2.setFeatureFamily("spline_float");
    record2.setFeatureName("aaa");
    record2.setWeightVector(ws);
    record2.setMinVal(1.0);
    record2.setMaxVal(3.0);
    ModelRecord record3 = new ModelRecord();
    record3.setFunctionForm(FunctionForm.Spline);
    record3.setFeatureFamily("spline_string");
    record3.setFeatureName("bbb");
    record3.setWeightVector(ws);
    record3.setMinVal(1.0);
    record3.setMaxVal(2.0);
    ModelRecord record4 = new ModelRecord();
    record4.setFunctionForm(FunctionForm.Linear);
    record4.setFeatureFamily("linear_float");
    record4.setFeatureName("ccc");
    record4.setWeightVector(wl);
    ModelRecord record5 = new ModelRecord();
    record5.setFunctionForm(FunctionForm.Linear);
    record5.setFeatureFamily("linear_string");
    record5.setFeatureName("ddd");
    record5.setWeightVector(wl);
    try {
        writer.write(Util.encode(record1) + "\n");
        writer.write(Util.encode(record2) + "\n");
        writer.write(Util.encode(record3) + "\n");
        writer.write(Util.encode(record4) + "\n");
        writer.write(Util.encode(record5) + "\n");
        writer.close();
    } catch (IOException e) {
        assertTrue("Could not write", false);
    }
    String serialized = charWriter.toString();
    assertTrue(serialized.length() > 0);
    StringReader strReader = new StringReader(serialized);
    BufferedReader reader = new BufferedReader(strReader);
    FeatureVector featureVector = makeFeatureVector(2.0f, 7.0f);
    try {
        Optional<AbstractModel> model = ModelFactory.createFromReader(reader);
        assertTrue(model.isPresent());
        float score = model.get().scoreItem(featureVector);
        assertEquals(8.0f + 10.0f + 15.0f, score, 0.001f);
    } catch (IOException e) {
        assertTrue("Could not read", false);
    }
}