Example usage for java.io CharArrayWriter flush

List of usage examples for java.io CharArrayWriter flush

Introduction

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

Prototype

public void flush() 

Source Link

Document

Flush the stream.

Usage

From source file:Main.java

public static void main(String[] args) {
    CharArrayWriter chw = new CharArrayWriter();

    CharSequence csq = "java2s.com";

    // append character sequence to the writer
    chw.append(csq);/*from w w w. j  a v a  2  s  .  co m*/

    // flush
    chw.flush();

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

}

From source file:com.alvermont.terraj.stargen.ui.SystemFrame.java

private void detailsMenuItemActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_detailsMenuItemActionPerformed
{//GEN-HEADEREND:event_detailsMenuItemActionPerformed

    try {/*from   w  ww.j  av a 2  s.com*/
        Configuration cfg = new Configuration();
        // Specify the data source where the template files come from.
        cfg.setClassForTemplateLoading(TemplateTest.class, "/com/alvermont/terraj/stargen/templates/");

        // Specify how templates will see the data model. This is an advanced topic...
        // but just use this:
        cfg.setObjectWrapper(new DefaultObjectWrapper());

        DetailsFromTemplate dft = new DetailsFromTemplate();

        List<PlanetDetailsPanel> panels = new ArrayList<PlanetDetailsPanel>();

        // first the star

        Template temp = cfg.getTemplate("starmain_html.ftl");

        CharArrayWriter out = new CharArrayWriter();

        dft.processTemplate(temp, star, out);
        out.flush();

        BufferedImage image = UIUtils.getImage("Sun");

        image = UIUtils.scaleImage(image, 32, 64);

        PlanetDetailsPanel panel = new PlanetDetailsPanel(image, "Star", out.toString());

        panel.setName("Star");

        panels.add(panel);

        // now do the planets

        temp = cfg.getTemplate("planetmain_html.ftl");

        for (Planet planet : this.planets) {
            out = new CharArrayWriter();

            dft.processTemplate(temp, planet, this.star, out);
            out.flush();

            image = UIUtils.getImage(planet.getType().getPrintText(planet.getType()));

            image = UIUtils.scaleImage(image, 64, 64);

            panel = new PlanetDetailsPanel(image, planet.getType().getPrintText(planet.getType()),
                    out.toString());

            panel.setName("#" + planet.getNumber());

            panels.add(panel);
        }

        DetailsFrame details = new DetailsFrame(this.star, this.planets, panels);

        details.setVisible(true);
    } catch (Exception ex) {
        log.error("Error getting details from template", ex);

        JOptionPane.showMessageDialog(this, "Error: " + ex.getMessage() + "\nCheck log file for full details",
                "Template Error", JOptionPane.ERROR_MESSAGE);
    }

}

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  w w  w  .ja  v a2  s  .c o m*/
    }
    bufWriter.flush();

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

From source file:org.apache.struts2.views.freemarker.FreemarkerResult.java

/**
 * Execute this result, using the specified template locationArg.
 * <p/>/*from   w w w  . ja v  a  2  s.  com*/
 * 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.commoncrawl.util.ArcFileWriter.java

private String escapeURI(String uri, String charsetEncoding) throws IOException {

    boolean needToChange = false;

    StringBuffer out = new StringBuffer(uri.length());

    Charset charset;/*from  w  w  w . ja  v a  2 s . c  o  m*/

    CharArrayWriter charArrayWriter = new CharArrayWriter();

    if (charsetEncoding == null)
        throw new NullPointerException("charsetName");

    try {
        charset = Charset.forName(charsetEncoding);
    } catch (IllegalCharsetNameException e) {
        throw new UnsupportedEncodingException(charsetEncoding);
    } catch (UnsupportedCharsetException e) {
        throw new UnsupportedEncodingException(charsetEncoding);
    }

    for (int i = 0; i < uri.length();) {
        int c = (int) uri.charAt(i);
        // System.out.println("Examining character: " + c);
        if (dontNeedEncoding.get(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) < uri.length()) {
                        int d = (int) uri.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 < uri.length() && !dontNeedEncoding.get((c = (int) uri.charAt(i))));

            charArrayWriter.flush();
            String str = new String(charArrayWriter.toCharArray());
            byte[] ba = str.getBytes(charsetEncoding);
            for (int j = 0; j < ba.length; j++) {
                out.append('%');
                char ch = Character.forDigit((ba[j] >> 4) & 0xF, 16);
                // converting to use uppercase letter as part of
                // 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() : uri);
}