Example usage for java.io CharArrayWriter write

List of usage examples for java.io CharArrayWriter write

Introduction

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

Prototype

public void write(String str, int off, int len) 

Source Link

Document

Write a portion of a string to the buffer.

Usage

From source file:org.jabsorb.JSONRPCServlet.java

/**
 * Called when a JSON-RPC requests comes in.
 * Looks in the session for a JSONRPCBridge and if not found there,
 * uses the global bridge; then passes off the
 * JSON-PRC call to be handled by the JSONRPCBridge found.
 *
 * @param request servlet request from browser.
 * @param response servlet response to browser.
 *
 * @throws IOException if an IOException occurs during processing.
 *//*from w w  w  .jav  a 2s  .c om*/
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Use protected method in case someone wants to override it
    JSONRPCBridge json_bridge = findBridge(request);

    // Decode using the charset in the request if it exists otherwise
    // use UTF-8 as this is what all browser implementations use.
    // The JSON-RPC-Java JavaScript client is ASCII clean so it
    // although here we can correctly handle data from other clients
    // that do not escape non ASCII data
    String charset = request.getCharacterEncoding();
    if (charset == null) {
        charset = "UTF-8";
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

    String receiveString = (String) request.getAttribute("_jabsorb_beenHere");

    // if JSON data is found in a special request attribute, it means
    // that a continuation was used and this request is being retried
    // as a consequence of a Jetty continuation
    // see http://blogs.webtide.com/gregw/2007/11/18/1195421880000.html
    if (receiveString == null) {
        // Read the request
        CharArrayWriter data = new CharArrayWriter();
        char buf[] = new char[buf_size];
        int ret;
        while ((ret = in.read(buf, 0, buf_size)) != -1) {
            data.write(buf, 0, ret);
        }
        receiveString = data.toString();
        int begin = receiveString.indexOf("{");
        int end = receiveString.lastIndexOf("}") + 1;
        receiveString = receiveString.substring(begin, end);

        // save the json-rpc data in a special request attribute, in case a jetty 
        // continuation exception (org.mortbay.jetty.RetryRequest) is thrown and this 
        // request is retried by the container
        request.setAttribute("_jabsorb_beenHere", receiveString);
    } else {
        log.debug("jetty continuation resumed...");
    }

    if (log.isDebugEnabled()) {
        log.debug("receive: " + receiveString);
        log.debug("receive: " + prettyPrintJson(receiveString));
    }

    // Process the request
    JSONObject json_req;
    JSONRPCResult json_res;
    try {
        json_req = new JSONObject(receiveString);
        json_res = json_bridge.call(new Object[] { request, response }, json_req);
    } catch (JSONException e) {
        log.error("can't parse call" + receiveString, e);
        json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
    }

    String sendString = json_res.toString();

    // dump the received string
    if (log.isDebugEnabled()) {
        log.debug("send: " + sendString);
        log.debug("send: " + prettyPrintJson(sendString));
    }

    // Write the response
    byte[] bout = sendString.getBytes("UTF-8");

    // handle gzipping of the response if it is turned on
    if (JSONRPCServlet.GZIP_THRESHOLD != -1) {
        // if the request header says that the browser can take gzip compressed output, then gzip the output
        // but only if the response is large enough to warrant it and if the resultant compressed output is
        // actually smaller.
        if (acceptsGzip(request)) {
            if (bout.length > JSONRPCServlet.GZIP_THRESHOLD) {
                byte[] gzippedOut = gzip(bout);
                log.debug(
                        "gzipping! original size =  " + bout.length + "  gzipped size = " + gzippedOut.length);

                // if gzip didn't actually help, abort
                if (bout.length <= gzippedOut.length) {
                    log.warn("gzipping resulted in a larger output size!  "
                            + "aborting (sending non-gzipped response)... "
                            + "you may want to increase the gzip threshold if this happens a lot!"
                            + " original size = " + bout.length + "  gzipped size = " + gzippedOut.length);
                } else {
                    // go with the gzipped output
                    bout = gzippedOut;
                    response.addHeader("Content-Encoding", "gzip");
                }
            } else {
                log.debug("not gzipping because size is " + bout.length + " (less than the GZIP_THRESHOLD of "
                        + JSONRPCServlet.GZIP_THRESHOLD + " bytes)");
            }
        } else {
            // this should be rare with modern user agents
            log.debug("not gzipping because user agent doesn't accept gzip encoding...");
        }
    }

    // Encode using UTF-8, although We are actually ASCII clean as
    // all unicode data is JSON escaped using backslash u. This is
    // less data efficient for foreign character sets but it is
    // needed to support naughty browsers such as Konqueror and Safari
    // which do not honour the charset set in the response
    response.setContentType("application/json;charset=utf-8");
    OutputStream out = response.getOutputStream();

    response.setIntHeader("Content-Length", bout.length);

    out.write(bout);
    out.flush();
    out.close();
}

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 v  a2  s  .  com*/
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.jabsorb.ng.JSONRPCServlet.java

/**
 * Called when a JSON-RPC requests comes in. Looks in the session for a
 * JSONRPCBridge and if not found there, uses the global bridge; then passes
 * off the JSON-PRC call to be handled by the JSONRPCBridge found.
 * //from ww w  .  j a  va 2s . c o  m
 * @param request
 *            servlet request from browser.
 * @param response
 *            servlet response to browser.
 * 
 * @throws IOException
 *             if an IOException occurs during processing.
 */
@Override
public void service(final HttpServletRequest request, final HttpServletResponse response) throws IOException {

    // Use protected method in case someone wants to override it
    JSONRPCBridge json_bridge = findBridge(request);

    // Decode using the charset in the request if it exists otherwise
    // use UTF-8 as this is what all browser implementations use.
    // The JSON-RPC-Java JavaScript client is ASCII clean so it
    // although here we can correctly handle data from other clients
    // that do not escape non ASCII data
    String charset = request.getCharacterEncoding();
    if (charset == null) {
        charset = "UTF-8";
    }

    BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

    String receiveString = (String) request.getAttribute("_jabsorb_beenHere");

    // if JSON data is found in a special request attribute, it means
    // that a continuation was used and this request is being retried
    // as a consequence of a Jetty continuation
    // see http://blogs.webtide.com/gregw/2007/11/18/1195421880000.html
    if (receiveString == null) {
        // Read the request
        CharArrayWriter data = new CharArrayWriter();
        char buf[] = new char[buf_size];
        int ret;
        while ((ret = in.read(buf, 0, buf_size)) != -1) {
            data.write(buf, 0, ret);
        }
        receiveString = data.toString();

        // save the json-rpc data in a special request attribute, in case a
        // jetty
        // continuation exception (org.mortbay.jetty.RetryRequest) is thrown
        // and this
        // request is retried by the container
        request.setAttribute("_jabsorb_beenHere", receiveString);
    } else {
        log.debug("service", "jetty continuation resumed...");
    }

    if (log.isDebugEnabled()) {
        log.debug("service", "receive: " + receiveString);
        log.debug("service", "receive: " + prettyPrintJson(receiveString));
    }

    // Process the request
    JSONObject json_req;
    JSONRPCResult json_res;
    try {
        json_req = new JSONObject(receiveString);
        json_res = json_bridge.call(new Object[] { request, response }, json_req);
    } catch (JSONException e) {
        log.error("service", "can't parse call" + receiveString, e);
        json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
    }

    String sendString = json_res.toString();

    // dump the received string
    if (log.isDebugEnabled()) {
        log.debug("service", "send: " + sendString);
        log.debug("service", "send: " + prettyPrintJson(sendString));
    }

    // Write the response
    byte[] bout = sendString.getBytes("UTF-8");

    // handle gzipping of the response if it is turned on
    if (JSONRPCServlet.GZIP_THRESHOLD != -1) {
        // if the request header says that the browser can take gzip
        // compressed output, then gzip the output
        // but only if the response is large enough to warrant it and if the
        // resultant compressed output is
        // actually smaller.
        if (acceptsGzip(request)) {
            if (bout.length > JSONRPCServlet.GZIP_THRESHOLD) {
                byte[] gzippedOut = gzip(bout);
                log.debug("service",
                        "gzipping! original size =  " + bout.length + "  gzipped size = " + gzippedOut.length);

                // if gzip didn't actually help, abort
                if (bout.length <= gzippedOut.length) {
                    log.warning("service", "gzipping resulted in a larger output size!  "
                            + "aborting (sending non-gzipped response)... "
                            + "you may want to increase the gzip threshold if this happens a lot!"
                            + " original size = " + bout.length + "  gzipped size = " + gzippedOut.length);
                } else {
                    // go with the gzipped output
                    bout = gzippedOut;
                    response.addHeader("Content-Encoding", "gzip");
                }
            } else {
                log.debug("service", "not gzipping because size is " + bout.length
                        + " (less than the GZIP_THRESHOLD of " + JSONRPCServlet.GZIP_THRESHOLD + " bytes)");
            }
        } else {
            // this should be rare with modern user agents
            log.debug("service", "not gzipping because user agent doesn't accept gzip encoding...");
        }
    }

    // Encode using UTF-8, although We are actually ASCII clean as
    // all unicode data is JSON escaped using backslash u. This is
    // less data efficient for foreign character sets but it is
    // needed to support naughty browsers such as Konqueror and Safari
    // which do not honour the charset set in the response
    response.setContentType("application/json;charset=utf-8");
    OutputStream out = response.getOutputStream();

    response.setIntHeader("Content-Length", bout.length);

    out.write(bout);
    out.flush();
    out.close();
}

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 ww.j ava  2 s  .c  o m*/
    bufWriter.flush();

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

From source file:onl.area51.httpd.action.Response.java

static Response create(Request request) {
    class State {

        private final String tag;
        private final boolean disableMini;
        private boolean body;

        public State(String tag, boolean disableMini) {
            this.tag = tag;
            this.disableMini = disableMini;
        }// ww  w.j a v a 2s .  com

        @Override
        public String toString() {
            return tag;
        }

    }

    CharArrayWriter writer = new CharArrayWriter();

    return new Response() {
        private ContentType contentType = ContentType.TEXT_HTML;

        private Deque<State> deque = new ArrayDeque<>();
        private State state;

        @Override
        public Response exec(Action a) throws IOException, HttpException {
            if (a != null) {
                // Ensure we have finished the current tag
                startBody();

                // Now preserve the stack & start a new one.
                // This means one action cannot affect the state of this one
                final Deque<State> orig = deque;
                deque = new ArrayDeque<>();
                try {
                    a.apply(request);
                } finally {
                    endAll();
                    deque = orig;
                }
            }
            return this;
        }

        @Override
        public Response setContentType(ContentType contentType) {
            this.contentType = contentType;
            return this;
        }

        @Override
        public HttpEntity getEntity() throws IOException {
            while (!deque.isEmpty()) {
                end();
            }
            return new StringEntity(writer.toString(), contentType);
        }

        private void startBody() {
            if (state != null && !state.body) {
                state.body = true;
                writer.append('>');
            }
        }

        private void tagOnly() {
            if (state == null || state.body) {
                throw new IllegalStateException("Not in tag");
            }
        }

        @Override
        public Response write(CharSequence seq, int s, int e) throws IOException {
            startBody();
            writer.append(seq, s, e);
            return this;
        }

        @Override
        public Response write(char[] v, int s, int l) throws IOException {
            startBody();
            writer.write(v, s, l);
            return this;
        }

        @Override
        public Response write(char v) throws IOException {
            startBody();
            writer.write(v);
            return this;
        }

        @Override
        public Response begin(String t, boolean disableMini) throws IOException {
            startBody();

            if (state != null) {
                deque.addLast(state);
            }

            state = new State(t, disableMini);

            writer.append('<');
            writer.write(state.tag);
            return this;
        }

        @Override
        public Response end() throws IOException {
            if (state == null) {
                throw new IllegalStateException("end() called outside of tag");
            }

            // elements like script mustn't be minified, i.e. <script/> is invalid must be <script></script>
            if (state.disableMini) {
                startBody();
            }

            if (state.body) {
                writer.append('<');
                writer.append('/');
                writer.append(state.tag);
                writer.append('>');
            } else {
                writer.append('/');
                writer.append('>');
            }

            state = deque.pollLast();

            return this;
        }

        @Override
        public Response endAll() throws IOException {
            while (!deque.isEmpty()) {
                end();
            }
            return this;
        }

        @Override
        public Response attr(String n, CharSequence seq) throws IOException {
            tagOnly();
            writer.append(' ');
            writer.append(n);
            writer.append('=');
            writer.append('"');
            writer.append(seq);
            writer.append('"');
            return this;
        }

        @Override
        public Response attr(String n, CharSequence seq, int s, int e) throws IOException {
            tagOnly();
            writer.append(' ');
            writer.append(n);
            writer.append('=');
            writer.append('"');
            writer.append(seq, s, e);
            writer.append('"');
            return this;
        }

        @Override
        public Response attr(String n, char[] v) throws IOException {
            tagOnly();
            writer.append(' ');
            writer.append(n);
            writer.append('=');
            writer.append('"');
            writer.write(v);
            writer.append('"');
            return this;
        }

        @Override
        public Response attr(String n, char[] v, int s, int l) throws IOException {
            tagOnly();
            writer.append(' ');
            writer.append(n);
            writer.append('=');
            writer.append('"');
            writer.write(v, s, l);
            writer.append('"');
            return this;
        }

    };
}