Example usage for java.io CharArrayWriter toString

List of usage examples for java.io CharArrayWriter toString

Introduction

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

Prototype

public String toString() 

Source Link

Document

Converts input data to a string.

Usage

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

String getText(Mark start, Mark stop) throws JasperException {
    Mark oldstart = mark();//from   ww w .  j a va2  s  . co  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.dd4t.core.util.XSLTransformer.java

public String transformSourceFromFilesource(String source, String resource, Map<String, Object> params)
        throws TransformerException {
    // attain writer to place result in
    CharArrayWriter caw = new CharArrayWriter();
    StreamResult result = new StreamResult(caw);

    // get XSL transformer
    Transformer trans = getTransformer(resource);
    for (Map.Entry<String, Object> entry : params.entrySet()) {
        trans.setParameter(entry.getKey(), entry.getValue());
    }/*from   w  w w. ja va  2 s.c om*/

    // if found, transform
    if (trans != null) {
        StringReader reader = new StringReader(source);
        StreamSource xmlSource = new StreamSource(reader);
        // transform
        trans.transform(xmlSource, result);
    }

    return caw.toString();
}

From source file:com.stratelia.silverpeas.silvertrace.SilverTrace.java

/**
 * Format the trace message for the Error and Fatal specific case
 *   /* ww w .  j av a 2  s  . co m*/
 * @param module
 * @param classe
 * @param messageID
 * @param extraInfos
 * @param ex
 * @return the built message
 */
static protected String formatErrorAndFatalMessage(String module, String classe, String messageID,
        String extraInfos, Throwable ex) {
    String extraParams;
    if (ex != null) {
        CharArrayWriter buffer = new CharArrayWriter();
        ex.printStackTrace(new PrintWriter(buffer));
        if (StringUtil.isDefined(extraInfos)) {
            extraParams = extraInfos + ", EXCEPTION : " + buffer.toString();
        } else {
            extraParams = "EXCEPTION : " + buffer.toString();
        }
    } else {
        extraParams = extraInfos;
    }
    return formatTraceMessage(module, classe, messageID, traceMessages.getMsgString(messageID), extraParams);
}

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 .  ja v  a  2  s .  c  o m
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.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   www  .j  a va 2  s .c  om
 * @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:com.rc.droid_stalker.components.NetworkStats.java

@Override
public String toString() {
    final CharArrayWriter writer = new CharArrayWriter();
    dump("", new PrintWriter(writer));
    return writer.toString();
}

From source file:org.apache.maven.doxia.DefaultConverter.java

/**
 * @param inputFile a not null existing file.
 * @param inputEncoding a not null supported encoding or {@link InputFileWrapper#AUTO_ENCODING}
 * @param inputFormat  a not null supported format or {@link InputFileWrapper#AUTO_FORMAT}
 * @param output not null OutputFileWrapper object
 * @throws ConverterException if any/*  w  ww  . ja va 2  s  . c  o m*/
 * @throws UnsupportedFormatException if any
 */
private void parse(File inputFile, String inputEncoding, String inputFormat, OutputFileWrapper output)
        throws ConverterException, UnsupportedFormatException {
    if (getLog().isDebugEnabled()) {
        getLog().debug("Parsing file from '" + inputFile.getAbsolutePath() + "' with the encoding '"
                + inputEncoding + "' to '" + output.getFile().getAbsolutePath() + "' with the encoding '"
                + output.getEncoding() + "'");
    }

    if (inputEncoding.equals(InputFileWrapper.AUTO_ENCODING)) {
        inputEncoding = autoDetectEncoding(inputFile);
        if (getLog().isDebugEnabled()) {
            getLog().debug("Auto detect encoding: " + inputEncoding);
        }
    }

    if (inputFormat.equals(InputFileWrapper.AUTO_FORMAT)) {
        inputFormat = autoDetectFormat(inputFile, inputEncoding);
        if (getLog().isDebugEnabled()) {
            getLog().debug("Auto detect input format: " + inputFormat);
        }
    }

    Parser parser;
    try {
        parser = ConverterUtil.getParser(plexus, inputFormat, SUPPORTED_FROM_FORMAT);
        parser.enableLogging(log);
    } catch (ComponentLookupException e) {
        throw new ConverterException("ComponentLookupException: " + e.getMessage(), e);
    }

    File outputFile;
    if (output.getFile().exists() && output.getFile().isDirectory()) {
        outputFile = new File(output.getFile(), inputFile.getName() + "." + output.getFormat());
    } else {
        if (!SelectorUtils.match("**.*", output.getFile().getName())) {
            // assume it is a directory
            output.getFile().mkdirs();
            outputFile = new File(output.getFile(), inputFile.getName() + "." + output.getFormat());
        } else {
            output.getFile().getParentFile().mkdirs();
            outputFile = output.getFile();
        }
    }

    Reader reader;
    try {
        if (inputEncoding != null) {
            if (parser.getType() == Parser.XML_TYPE) {
                reader = ReaderFactory.newXmlReader(inputFile);
            } else {
                reader = ReaderFactory.newReader(inputFile, inputEncoding);
            }
        } else {
            reader = ReaderFactory.newPlatformReader(inputFile);
        }
    } catch (IOException e) {
        throw new ConverterException("IOException: " + e.getMessage(), e);
    }

    SinkFactory sinkFactory;
    try {
        sinkFactory = ConverterUtil.getSinkFactory(plexus, output.getFormat(), SUPPORTED_TO_FORMAT);
    } catch (ComponentLookupException e) {
        throw new ConverterException("ComponentLookupException: " + e.getMessage(), e);
    }

    Sink sink;
    try {
        String outputEncoding;
        if (StringUtils.isEmpty(output.getEncoding())
                || output.getEncoding().equals(OutputFileWrapper.AUTO_ENCODING)) {
            outputEncoding = inputEncoding;
        } else {
            outputEncoding = output.getEncoding();
        }

        OutputStream out = new FileOutputStream(outputFile);
        sink = sinkFactory.createSink(out, outputEncoding);
    } catch (IOException e) {
        throw new ConverterException("IOException: " + e.getMessage(), e);
    }

    sink.enableLogging(log);

    if (getLog().isDebugEnabled()) {
        getLog().debug("Sink used: " + sink.getClass().getName());
    }

    parse(parser, reader, sink);

    if (formatOutput && (output.getFormat().equals(DOCBOOK_SINK) || output.getFormat().equals(FO_SINK)
            || output.getFormat().equals(ITEXT_SINK) || output.getFormat().equals(XDOC_SINK)
            || output.getFormat().equals(XHTML_SINK))) {
        // format all xml files excluding docbook which is buggy
        // TODO Add doc book format
        if (output.getFormat().equals(DOCBOOK_SINK) || inputFormat.equals(DOCBOOK_PARSER)) {
            return;
        }
        Reader r = null;
        Writer w = null;
        try {
            r = ReaderFactory.newXmlReader(outputFile);
            CharArrayWriter caw = new CharArrayWriter();
            XmlUtil.prettyFormat(r, caw);
            w = WriterFactory.newXmlWriter(outputFile);
            w.write(caw.toString());
        } catch (IOException e) {
            throw new ConverterException("IOException: " + e.getMessage(), e);
        } finally {
            IOUtil.close(r);
            IOUtil.close(w);
        }
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.transformer.CswQueryResponseTransformer.java

private String multiThreadedMarshal(List<Result> results, String recordSchema,
        final Map<String, Serializable> arguments) throws CatalogTransformerException {

    CompletionService<BinaryContent> completionService = new ExecutorCompletionService<>(queryExecutor);

    try {/*from w w w . j  av  a  2 s  . co m*/
        for (Result result : results) {
            final Metacard mc = result.getMetacard();

            final MetacardTransformer transformer = metacardTransformerManager
                    .getTransformerBySchema(recordSchema);

            if (transformer == null) {
                throw new CatalogTransformerException("Cannot find transformer for schema: " + recordSchema);
            }

            // the "current" thread will run submitted task when queueSize exceeded; effectively
            // blocking enqueue of more tasks.
            completionService.submit(new Callable<BinaryContent>() {
                @Override
                public BinaryContent call() throws Exception {
                    BinaryContent content = transformer.transform(mc, arguments);
                    return content;
                }
            });
        }

        int metacardCount = results.size();
        CharArrayWriter accum = new CharArrayWriter(ACCUM_INITIAL_SIZE);
        for (int i = 0; i < metacardCount; i++) {
            Future<BinaryContent> binaryContentFuture = completionService.take(); // blocks
            BinaryContent binaryContent = binaryContentFuture.get();
            IOUtils.copy(binaryContent.getInputStream(), accum);
        }

        return accum.toString();

    } catch (IOException | InterruptedException | ExecutionException xe) {
        throw new CatalogTransformerException(xe);
    }

}

From source file:org.apache.jmeter.save.CSVSaveService.java

/**
 * Reads from file and splits input into strings according to the delimiter,
 * taking note of quoted strings./*w w  w  . jav  a2  s  . c om*/
 * <p>
 * Handles DOS (CRLF), Unix (LF), and Mac (CR) line-endings equally.
 * <p>
 * A blank line - or a quoted blank line - both return an array containing
 * a single empty String.
 * @param infile
 *            input file - must support mark(1)
 * @param delim
 *            delimiter (e.g. comma)
 * @return array of strings, will be empty if there is no data, i.e. if the input is at EOF.
 * @throws IOException
 *             also for unexpected quote characters
 */
public static String[] csvReadFile(BufferedReader infile, char delim) throws IOException {
    int ch;
    ParserState state = ParserState.INITIAL;
    List<String> list = new ArrayList<>();
    CharArrayWriter baos = new CharArrayWriter(200);
    boolean push = false;
    while (-1 != (ch = infile.read())) {
        push = false;
        switch (state) {
        case INITIAL:
            if (ch == QUOTING_CHAR) {
                state = ParserState.QUOTED;
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
            } else {
                baos.write(ch);
                state = ParserState.PLAIN;
            }
            break;
        case PLAIN:
            if (ch == QUOTING_CHAR) {
                baos.write(ch);
                throw new IOException("Cannot have quote-char in plain field:[" + baos.toString() + "]");
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
                state = ParserState.INITIAL;
            } else {
                baos.write(ch);
            }
            break;
        case QUOTED:
            if (ch == QUOTING_CHAR) {
                state = ParserState.EMBEDDEDQUOTE;
            } else {
                baos.write(ch);
            }
            break;
        case EMBEDDEDQUOTE:
            if (ch == QUOTING_CHAR) {
                baos.write(QUOTING_CHAR); // doubled quote => quote
                state = ParserState.QUOTED;
            } else if (isDelimOrEOL(delim, ch)) {
                push = true;
                state = ParserState.INITIAL;
            } else {
                baos.write(QUOTING_CHAR);
                throw new IOException(
                        "Cannot have single quote-char in quoted field:[" + baos.toString() + "]");
            }
            break;
        default:
            throw new IllegalStateException("Unexpected state " + state);
        } // switch(state)
        if (push) {
            if (ch == '\r') {// Remove following \n if present
                infile.mark(1);
                if (infile.read() != '\n') {
                    infile.reset(); // did not find \n, put the character
                                    // back
                }
            }
            String s = baos.toString();
            list.add(s);
            baos.reset();
        }
        if ((ch == '\n' || ch == '\r') && state != ParserState.QUOTED) {
            break;
        }
    } // while not EOF
    if (ch == -1) {// EOF (or end of string) so collect any remaining data
        if (state == ParserState.QUOTED) {
            throw new IOException("Missing trailing quote-char in quoted field:[\"" + baos.toString() + "]");
        }
        // Do we have some data, or a trailing empty field?
        if (baos.size() > 0 // we have some data
                || push // we've started a field
                || state == ParserState.EMBEDDEDQUOTE // Just seen ""
        ) {
            list.add(baos.toString());
        }
    }
    return list.toArray(new String[list.size()]);
}

From source file:com.android.providers.downloads.DownloadInfo.java

@Override
public String toString() {
    final CharArrayWriter writer = new CharArrayWriter();
    dump(new IndentingPrintWriter(writer, "  "));
    return writer.toString();
}