Example usage for java.io CharArrayWriter close

List of usage examples for java.io CharArrayWriter close

Introduction

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

Prototype

public void close() 

Source Link

Document

Close the stream.

Usage

From source file:Main.java

public static void main(String[] args) {

    CharArrayWriter chw = new CharArrayWriter();

    CharSequence csq = "java2s.com";

    // closes the stream
    chw.close();

    // append character sequence to the writer
    chw.append(csq);/*from ww  w. jav  a  2s. c o  m*/

    // prints out the character sequences
    System.out.println(chw.toString());

}

From source file:Main.java

/**
 * Fully reads the characters available from the supplied Reader
 * and returns these characters as a String object.
 *
 * @param reader The Reader to read the characters from.
 * @return A String existing of the characters that were read.
 * @throws IOException If I/O error occurred.
 *///from  w  w  w .jav a2  s  . c  om
public static final String readFully(Reader reader) throws IOException {
    CharArrayWriter out = new CharArrayWriter(4096);
    transfer(reader, out);
    out.close();

    return out.toString();
}

From source file:com.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java

protected String readFile(String path) throws IOException {
    CharArrayWriter writer = null;
    InputStream in = null;/*from   w  w  w.  j  a  va  2  s .  co  m*/
    Reader reader = null;
    try {
        in = new FileInputStream(path);
        writer = new CharArrayWriter();
        reader = new InputStreamReader(in);
        char[] buffer = new char[8];
        int c = 0;
        while ((c = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, c);
        }
        return new String(writer.toCharArray());
    } catch (IOException ioex) {
        return null;
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (in != null) {
            in.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

From source file:com.silverpeas.jcrutil.model.impl.AbstractJcrTestCase.java

protected String readFileFromNode(Node fileNode)
        throws IOException, ValueFormatException, PathNotFoundException, RepositoryException {
    CharArrayWriter writer = null;
    InputStream in = null;/*  w ww  .j a v  a2 s . c o m*/
    Reader reader = null;
    try {
        in = fileNode.getNode(JcrConstants.JCR_CONTENT).getProperty(JcrConstants.JCR_DATA).getStream();
        writer = new CharArrayWriter();
        reader = new InputStreamReader(in);
        char[] buffer = new char[8];
        int c = 0;
        while ((c = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, c);
        }
        return new String(writer.toCharArray());
    } catch (IOException ioex) {
        return null;
    } finally {
        if (reader != null) {
            reader.close();
        }
        if (in != null) {
            in.close();
        }
        if (writer != null) {
            writer.close();
        }
    }
}

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.//  w  ww. j  a  v a2 s.c o  m
 */
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:org.apache.jasper.compiler.JspReader.java

String getText(Mark start, Mark stop) throws JasperException {
    Mark oldstart = mark();/*  w ww .j  a  v a2  s . c  o  m*/
    reset(start);
    CharArrayWriter caw = new CharArrayWriter();
    while (!stop.equals(mark()))
        caw.write(nextChar());
    caw.close();
    reset(oldstart);
    return caw.toString();
}

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.
 *//* w w w .  ja  v  a2  s  . c  o  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:org.apache.struts2.views.freemarker.FreemarkerResult.java

/**
 * Execute this result, using the specified template locationArg.
 * <p/>//from   w  w  w.  j  a  va 2  s.c  o m
 * The template locationArg has already been interoplated for any variable substitutions
 * <p/>
 * this method obtains the freemarker configuration and the object wrapper from the provided hooks.
 * It them implements the template processing workflow by calling the hooks for
 * preTemplateProcess and postTemplateProcess
 */
public void doExecute(String locationArg, ActionInvocation invocation) throws IOException, TemplateException {
    this.location = locationArg;
    this.invocation = invocation;
    this.configuration = getConfiguration();
    this.wrapper = getObjectWrapper();

    ActionContext ctx = invocation.getInvocationContext();
    HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);

    if (!locationArg.startsWith("/")) {
        String base = ResourceUtil.getResourceBase(req);
        locationArg = base + "/" + locationArg;
    }

    Template template = configuration.getTemplate(locationArg, deduceLocale());
    TemplateModel model = createModel();

    // Give subclasses a chance to hook into preprocessing
    if (preTemplateProcess(template, model)) {
        try {
            // Process the template
            Writer writer = getWriter();
            if (isWriteIfCompleted() || configuration
                    .getTemplateExceptionHandler() == TemplateExceptionHandler.RETHROW_HANDLER) {
                CharArrayWriter parentCharArrayWriter = (CharArrayWriter) req
                        .getAttribute(PARENT_TEMPLATE_WRITER);
                boolean isTopTemplate = false;
                if (isTopTemplate = (parentCharArrayWriter == null)) {
                    //this is the top template
                    parentCharArrayWriter = new CharArrayWriter();
                    //set it in the request because when the "action" tag is used a new VS and ActionContext is created
                    req.setAttribute(PARENT_TEMPLATE_WRITER, parentCharArrayWriter);
                }

                try {
                    template.process(model, parentCharArrayWriter);

                    if (isTopTemplate) {
                        parentCharArrayWriter.flush();
                        parentCharArrayWriter.writeTo(writer);
                    }
                } catch (TemplateException e) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Error processing Freemarker result!", e);
                    }
                    throw e;
                } catch (IOException e) {
                    if (LOG.isErrorEnabled()) {
                        LOG.error("Error processing Freemarker result!", e);
                    }
                    throw e;
                } finally {
                    if (isTopTemplate && parentCharArrayWriter != null) {
                        req.removeAttribute(PARENT_TEMPLATE_WRITER);
                        parentCharArrayWriter.close();
                    }
                }
            } else {
                template.process(model, writer);
            }
        } finally {
            // Give subclasses a chance to hook into postprocessing
            postTemplateProcess(template, model);
        }
    }
}

From source file:org.dhatim.SmooksUtil.java

/**
 * Utility method to filter the content in the specified {@link InputStream} for the specified {@link org.dhatim.container.ExecutionContext}.
 * <p/>//w w w. ja v a  2s .  c  o m
 * Useful for testing purposes.  In a real scenario, use
 * {@link Smooks#filter(org.dhatim.container.ExecutionContext,javax.xml.transform.Source,javax.xml.transform.Result)}.
 * <p/>
 * The content of the returned String is totally dependent on the configured
 * {@link org.dhatim.delivery.dom.DOMElementVisitor} and {@link org.dhatim.delivery.dom.serialize.SerializationUnit}
 * implementations.
 *
 * @param executionContext Execution context for the filter.
 * @param stream           Stream to be processed.  Will be closed before returning.
 * @param smooks           The {@link Smooks} instance through which to perform the filter and serialize operations.
 * @return The Smooks processed content buffer.
 * @throws IOException     Exception using or closing the supplied InputStream.
 * @throws SmooksException Excepting processing content stream.
 */
public static String filterAndSerialize(ExecutionContext executionContext, InputStream stream, Smooks smooks)
        throws SmooksException {
    String responseBuf = null;
    CharArrayWriter writer = new CharArrayWriter();
    try {
        smooks.filterSource(executionContext, new StreamSource(stream), new StreamResult(writer));
        responseBuf = writer.toString();
    } finally {
        if (stream != null) {
            try {
                stream.close();
            } catch (IOException e) {
                new SmooksException("Failed to close stream...", e);
            }
        }
        writer.close();
    }

    return responseBuf;
}