Example usage for java.io CharArrayWriter toCharArray

List of usage examples for java.io CharArrayWriter toCharArray

Introduction

In this page you can find the example usage for java.io CharArrayWriter toCharArray.

Prototype

public char[] toCharArray() 

Source Link

Document

Returns a copy of the input data.

Usage

From source file:org.apache.jasper.compiler.JspReader.java

/**
 * Push a file (and its associated Stream) on the file stack.  THe
 * current position in the current file is remembered.
 *///from  w  w w  .ja va  2  s.co  m
private void pushFile(String file, String encoding, InputStreamReader reader)
        throws JasperException, FileNotFoundException {

    // Register the file
    String longName = file;

    int fileid = registerSourceFile(longName);

    if (fileid == -1) {
        err.jspError("jsp.error.file.already.registered", file);
    }

    currFileId = fileid;

    try {
        CharArrayWriter caw = new CharArrayWriter();
        char buf[] = new char[1024];
        for (int i = 0; (i = reader.read(buf)) != -1;)
            caw.write(buf, 0, i);
        caw.close();
        if (current == null) {
            current = new Mark(this, caw.toCharArray(), fileid, getFile(fileid), master, encoding);
        } else {
            current.pushStream(caw.toCharArray(), fileid, getFile(fileid), longName, encoding);
        }
    } catch (Throwable ex) {
        log.error("Exception parsing file ", ex);
        // Pop state being constructed:
        popFile();
        err.jspError("jsp.error.file.cannot.read", file);
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (Exception any) {
            }
        }
    }
}

From source file:net.sf.jasperreports.engine.JRResultSetDataSource.java

protected CharArrayReader getArrayReader(Reader reader, long size) throws IOException {
    char[] buf = new char[8192];
    CharArrayWriter bufWriter = new CharArrayWriter((size > 0) ? (int) size : 8192);

    BufferedReader bufReader = new BufferedReader(reader, 8192);
    for (int read = bufReader.read(buf); read > 0; read = bufReader.read(buf)) {
        bufWriter.write(buf, 0, read);//from  ww w  .ja va  2 s. co m
    }
    bufWriter.flush();

    return new CharArrayReader(bufWriter.toCharArray());
}

From source file:org.ireland.jnetty.webapp.ErrorPageManager.java

/**
 * Escapes HTML symbols in a stack trace.
 *//*from  w  w  w. j a  v a 2  s .c o  m*/
private void printStackTrace(PrintWriter out, String lineMessage, Throwable e, Throwable rootExn,
        LineMap lineMap) {
    CharArrayWriter writer = new CharArrayWriter();
    PrintWriter pw = new PrintWriter(writer);

    if (lineMessage != null)
        pw.println(lineMessage);

    if (lineMap != null)
        lineMap.printStackTrace(e, pw);
    else
        ScriptStackTrace.printStackTrace(e, pw);

    pw.close();

    char[] array = writer.toCharArray();
    out.print(escapeHtml(new String(array)));
}

From source file:launcher.net.CustomIOUtils.java

/**
 * Get the contents of an <code>InputStream</code> as a character array
 * using the specified character encoding.
 * <p>/*www.  j  av a 2s.  c o  m*/
 * 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();
}

From source file:org.theospi.portfolio.portal.web.XsltPortal.java

private Element createSitesTabArea(Session session, String siteId, Document doc, HttpServletRequest req)
        throws IOException, SAXException {
    Element siteTabs = doc.createElement("siteTabs");
    CharArrayWriter writer = new CharArrayWriter();
    PrintWriter printWriter = new PrintWriter(writer);
    printWriter.write("<div id=\"blank\">");
    includeTabs(printWriter, req, session, siteId, "site", false);
    Document tabs = getDocumentBuilder().parse(new InputSource(new CharArrayReader(writer.toCharArray())));
    siteTabs.appendChild(doc.importNode(tabs.getDocumentElement(), true));
    return siteTabs;
}

From source file:com.tomagoyaky.jdwp.IOUtils.java

/**
 * Gets the contents of an <code>InputStream</code> as a character array
 * using the specified character encoding.
 * <p/>// ww w.  ja  v  a  2s.c o  m
 * 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();
}

From source file:com.netscape.cms.logging.LogFile.java

/**
 * This method actually does the logging, and is not overridden
 * by subclasses, so you can call it and know that it will do exactly
 * what you see below.//from   w w w .j ava  2s .  com
 */
private synchronized void doLog(ILogEvent event, boolean noFlush) throws ELogException {

    String entry = logEvt2String(event);

    if (mLogWriter == null) {
        String[] params = { mFileName, entry };

        if (mLogSigning) {
            ConsoleError.send(new SystemEvent(CMS.getUserMessage("CMS_LOG_LOGFILE_CLOSED", params)));
            // Failed to write to audit log, shut down CMS
            shutdownCMS();
        }
        throw new ELogException(CMS.getUserMessage("CMS_LOG_LOGFILE_CLOSED", params));
    } else {
        try {
            mLogWriter.write(entry, 0/*offset*/, entry.length());

            if (mLogSigning == true) {
                if (mSignature != null) {
                    // include newline for calculating MAC
                    mSignature.update(entry.getBytes("UTF-8"));
                } else {
                    CMS.debug("LogFile: mSignature is not yet ready... null in log()");
                }
            }
            if (mTrace) {
                CharArrayWriter cw = new CharArrayWriter(200);
                PrintWriter pw = new PrintWriter(cw);
                Exception e = new Exception();
                e.printStackTrace(pw);
                char[] c = cw.toCharArray();
                cw.close();
                pw.close();

                CharArrayReader cr = new CharArrayReader(c);
                LineNumberReader lr = new LineNumberReader(cr);

                String text = null;
                String method = null;
                String fileAndLine = null;
                if (lr.ready()) {
                    text = lr.readLine();
                    do {
                        text = lr.readLine();
                    } while (text.indexOf("logging") != -1);
                    int p = text.indexOf("(");
                    fileAndLine = text.substring(p);

                    String classandmethod = text.substring(0, p);
                    int q = classandmethod.lastIndexOf(".");
                    method = classandmethod.substring(q + 1);
                    mLogWriter.write(fileAndLine, 0/*offset*/, fileAndLine.length());
                    mLogWriter.write(" ", 0/*offset*/, " ".length());
                    mLogWriter.write(method, 0/*offset*/, method.length());
                }
            }
            mLogWriter.newLine();

            if (mLogSigning == true) {
                if (mSignature != null) {
                    mSignature.update(LINE_SEP_BYTE);
                } else {
                    CMS.debug("LogFile: mSignature is null in log() 2");
                }
            }
        } catch (IOException e) {
            ConsoleError.send(new SystemEvent(
                    CMS.getUserMessage("CMS_LOG_WRITE_FAILED", mFileName, entry, e.toString())));
            if (mLogSigning) {
                // Failed to write to audit log, shut down CMS
                e.printStackTrace();
                shutdownCMS();
            }
        } catch (IllegalStateException e) {
            CMS.debug("LogFile: exception thrown in log(): " + e.toString());
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, e.toString())));
        } catch (GeneralSecurityException gse) {
            // DJN: handle error
            CMS.debug("LogFile: exception thrown in log(): " + gse.toString());
            gse.printStackTrace();
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, gse.toString())));
        } catch (Exception ee) { // Make darn sure we got everything
            ConsoleError
                    .send(new SignedAuditEvent(CMS.getLogMessage(LOG_SIGNED_AUDIT_EXCEPTION, ee.toString())));
            if (mLogSigning) {
                // Failed to write to audit log, shut down CMS
                ee.printStackTrace();
                shutdownCMS();
            }

        }

        // XXX
        // Although length will be in Unicode dual-bytes, the PrintWriter
        // will only print out 1 byte per character.  I suppose this could
        // be dependent on the encoding of your log file, but it ain't that
        // smart yet.  Also, add one for the newline. (hmm, on NT, CR+LF)
        int nBytes = entry.length() + 1;

        mBytesWritten += nBytes;
        mBytesUnflushed += nBytes;

        if (mBufferSize > 0 && mBytesUnflushed > mBufferSize && !noFlush) {
            flush();
        }
    }
}

From source file:importer.filters.PoemFilter.java

/**
 * Convert to standoff properties/*from  ww w.  j ava  2s  .c  om*/
 * @param input the raw text input string
 * @param name the name of the new version
 * @param cortext a cortex mvd archive
 * @param corcode a corcode mvd archive
 * @return log output
 */
@Override
public String convert(String input, String name, Archive cortex, Archive corcode) throws ImporterException {
    try {
        CharArrayWriter txt = new CharArrayWriter();
        String[] lines = input.split("\n");
        init();
        analyseStanzas(lines);
        int state = (hasHeading) ? 0 : 1;
        for (int i = 0; i < lines.length; i++) {
            String str = lines[i].trim();
            char[] current = str.toCharArray();
            switch (state) {
            case 0:
                if (lines[i].length() > 0) {
                    writeCurrent(txt, current);
                    writeCurrent(txt, CR);
                    numHeadingLines++;
                    if (numHeadingLines == minStanzaLength) {
                        markup.add("head", 0, written);
                        state = 1;
                    }
                }
                break;
            case 1: // new stanza
                lgStart = written;
                markup.add("l", written, current.length);
                writeCurrent(txt, current);
                writeCurrent(txt, CR);
                state = 2;
                break;
            case 2: // body of stanza
                if (lines[i].length() > 0) {
                    markup.add("l", written, current.length);
                    writeCurrent(txt, current);
                    writeCurrent(txt, CR);
                } else {
                    markup.add("lg", lgStart, written - lgStart);
                    writeCurrent(txt, CR);
                    state = 1;
                }
                break;
            }
        }
        if (state == 2) {
            markup.add("lg", lgStart, written - lgStart);
            writeCurrent(txt, CR);
        }
        markup.sort();
        cortex.put(name, txt.toCharArray());
        String json = markup.toSTILDocument().toString();
        corcode.put(name, json.toCharArray());
        return "";
    } catch (Exception e) {
        throw new ImporterException(e);
    }
}

From source file:com.allblacks.utils.web.HttpUtil.java

/**
 * Gets data from URL as char[] throws {@link RuntimeException} If anything
 * goes wrong/*from  www .  j a  va  2 s.c  o m*/
 * 
 * @return The content of the URL as a char[]
 * @throws java.io.IOException
 */
public char[] postDataAsCharArray(String url, String contentType, String contentName, char[] content)
        throws IOException {

    URLConnection urlc = null;
    OutputStream os = null;
    InputStream is = null;
    CharArrayWriter dat = null;
    BufferedReader reader = null;
    String boundary = "" + new Date().getTime();

    try {
        urlc = new URL(url).openConnection();
        urlc.setDoOutput(true);
        urlc.setRequestProperty(HttpUtil.CONTENT_TYPE,
                "multipart/form-data; boundary=---------------------------" + boundary);

        String message1 = "-----------------------------" + boundary + HttpUtil.BNL;
        message1 += "Content-Disposition: form-data; name=\"nzbfile\"; filename=\"" + contentName + "\""
                + HttpUtil.BNL;
        message1 += "Content-Type: " + contentType + HttpUtil.BNL;
        message1 += HttpUtil.BNL;
        String message2 = HttpUtil.BNL + "-----------------------------" + boundary + "--" + HttpUtil.BNL;

        os = urlc.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName(HttpUtil.UTF_8)));

        writer.write(message1);
        writer.write(content);
        writer.write(message2);
        writer.flush();

        dat = new CharArrayWriter();
        if (urlc.getContentEncoding() != null && urlc.getContentEncoding().equalsIgnoreCase(HttpUtil.GZIP)) {
            is = new GZIPInputStream(urlc.getInputStream());
        } else {
            is = urlc.getInputStream();
        }
        reader = new BufferedReader(new InputStreamReader(is, Charset.forName(HttpUtil.UTF_8)));

        int c;
        while ((c = reader.read()) != -1) {
            dat.append((char) c);
        }
    } catch (IOException exception) {
        throw exception;
    } finally {
        try {
            reader.close();
            os.close();
            is.close();
        } catch (Exception e) {
            // we do not care about this
        }
    }

    return dat.toCharArray();
}

From source file:com.silentcircle.silenttext.application.SilentTextApplication.java

public CharSequence getFullJIDForUsername(CharSequence username) {
    CharArrayWriter out = new CharArrayWriter();
    boolean shouldAppend = true;
    for (int i = 0; i < username.length(); i++) {
        char c = username.charAt(i);
        out.append(username.charAt(i));/*from  ww w. j a  va  2 s .  c om*/
        if (c == '@') {
            shouldAppend = false;
        }
    }
    if (shouldAppend) {
        out.append('@');
        out.append(getDomain());
    }
    return CharBuffer.wrap(out.toCharArray());
}