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:Main.java

public static void main(String[] args) {

    String str = "from java2s.com!";

    CharArrayWriter chw = new CharArrayWriter();

    // portion to be written to writer
    chw.write(str, 4, 9);

    // print the buffer as string
    System.out.println(chw.toString());

}

From source file:Main.java

public static void main(String[] args) {

    char[] ch = { 'A', 'B', 'C', 'D', 'E' };

    CharArrayWriter chw = new CharArrayWriter();

    // write character buffer to the writer
    chw.write(ch, 3, 2);

    String str = chw.toString();//from  w w w.  j  a v a 2 s .c  om

    System.out.print(str);

}

From source file:Main.java

/** Reads an <code>InputStream</code> into a string.
 * @param in The stream to read into a string.
 * @return The stream as a string//  w w w.j a v  a2s . c  o  m
 * @throws IOException
 */
public static String toString(InputStream in) throws IOException {
    if (in == null) {
        return null;
    }
    final Reader reader = new InputStreamReader(in);
    final char[] buffer = new char[100];
    final CharArrayWriter writer = new CharArrayWriter(1000);
    int read;
    while ((read = reader.read(buffer)) > -1)
        writer.write(buffer, 0, read);
    return writer.toString();
}

From source file:org.opennaas.extensions.ofertie.ncl.provisioner.components.UserManager.java

private static String readXMLFile(String filePath) throws IOException {

    log.debug("Reading content of file " + filePath);

    InputStreamReader reader = null;
    BufferedReader bufferReader = null;
    try {/*from ww  w.  j a  v a 2  s  . c o m*/
        URL url = new URL(filePath);
        reader = new InputStreamReader(url.openStream());
        bufferReader = new BufferedReader(reader);
    } catch (MalformedURLException ignore) {
        // They try a file
        File file = new File(filePath);
        bufferReader = new BufferedReader(new FileReader(file));
    }
    CharArrayWriter w = new CharArrayWriter();
    int n;
    char[] buf = new char[8192];
    while ((n = bufferReader.read(buf)) > 0) {
        w.write(buf, 0, n);
    }
    bufferReader.close();
    String fileContent = w.toString();
    log.debug("Readed content of file " + filePath);

    return fileContent;
}

From source file:Base64.java

private static char[] readChars(File file) {
    CharArrayWriter caw = new CharArrayWriter();
    try {//w w  w. j  a va 2 s  . co  m
        Reader fr = new FileReader(file);
        Reader in = new BufferedReader(fr);
        int count = 0;
        char[] buf = new char[16384];
        while ((count = in.read(buf)) != -1) {
            if (count > 0)
                caw.write(buf, 0, count);
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return caw.toCharArray();
}

From source file:Base64.java

private static char[] readChars(final File file) {
    final CharArrayWriter caw = new CharArrayWriter();
    try {// w ww .  ja v  a 2s.  c om
        final Reader fr = new FileReader(file);
        final Reader in = new BufferedReader(fr);
        int count;
        final char[] buf = new char[16384];
        while ((count = in.read(buf)) != -1) {
            if (count > 0) {
                caw.write(buf, 0, count);
            }
        }
        in.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

    return caw.toCharArray();
}

From source file:com.metaparadigm.jsonrpc.JSONRPCServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ClassCastException {
    // Find the JSONRPCBridge for this session or create one
    // if it doesn't exist
    HttpSession session = request.getSession();
    JSONRPCBridge json_bridge = null;/*from w  w w .  jav  a 2s  .  com*/
    json_bridge = (JSONRPCBridge) session.getAttribute("JSONRPCBridge");
    if (json_bridge == null) {
        // Only create a new bridge if not disabled in config
        if (!auto_session_bridge) {
            // Use the global bridge only, and don't set on session.
            json_bridge = JSONRPCBridge.getGlobalBridge();
            if (json_bridge.isDebug())
                log.info("Using global bridge.");
        } else {
            json_bridge = new JSONRPCBridge();
            session.setAttribute("JSONRPCBridge", json_bridge);
            if (json_bridge.isDebug())
                log.info("Created a bridge for this session.");
        }
    }

    // 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("text/plain;charset=utf-8");
    OutputStream out = response.getOutputStream();

    // 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));

    // 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);
    if (json_bridge.isDebug())
        log.fine("recieve: " + data.toString());

    // Process the request
    JSONObject json_req = null;
    JSONRPCResult json_res = null;
    try {
        json_req = new JSONObject(data.toString());
        json_res = json_bridge.call(new Object[] { request }, json_req);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    // Write the response
    if (json_bridge.isDebug())
        log.fine("send: " + json_res.toString());
    byte[] bout = json_res.toString().getBytes("UTF-8");
    if (keepalive) {
        response.setIntHeader("Content-Length", bout.length);
    }

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

From source file:com.orange.mmp.api.ws.jsonrpc.MMPJsonRpcServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response) throws IOException {

    ExecutionContext executionContext = ExecutionContext.newInstance(request);
    executionContext.setName("JSON-RCP Request");

    executionContext.executionStart();/*w w  w. j  av a  2s.  c o  m*/
    String requestInfo = "";
    try {

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

        // 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");
        response.setCharacterEncoding(Constants.DEFAULT_ENCODING);
        OutputStream out = response.getOutputStream();

        // 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 = Constants.DEFAULT_ENCODING;
        }

        String receiveString = null;

        // Test HTTP GET
        if (request.getQueryString() != null) {
            String id = request.getParameter(HTTP_PARAM_ID);
            if (id != null) {
                executionContext.setApiName(id);

                StringBuilder receiveStringBuilder = new StringBuilder("{\"id\":").append(id)
                        .append(",\"method\":\"");
                String method = request.getParameter(HTTP_PARAM_METHOD);
                // Get params
                if (method != null) {
                    executionContext.setMethodName(method);

                    receiveStringBuilder.append(method);
                    String param = request.getParameter(HTTP_PARAM_PARAM);
                    // There is parameters
                    if (param != null) {
                        receiveStringBuilder.append("\",\"params\":").append(param).append("}");
                    }
                    // Empty params
                    else {
                        receiveStringBuilder.append("\",\"params\":[]}");
                    }
                }
                // Default method (list API)
                else {
                    receiveStringBuilder.append("system.listMethods\",\"params\":[]}");
                }

                // Set JSON-RPC call string
                receiveString = receiveStringBuilder.toString();

                //Trace request
                executionContext.setName("JSON-RCP Request: " + receiveString);
            }
        }

        // Test HTTP POST
        if (receiveString == null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream(), charset));

            // Read the request
            CharArrayWriter data = new CharArrayWriter();
            char buf[] = new char[4096];
            int ret;
            while ((ret = in.read(buf, 0, 4096)) != -1) {
                data.write(buf, 0, ret);
            }

            receiveString = data.toString();
            requestInfo = 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) {
            json_res = new JSONRPCResult(JSONRPCResult.CODE_ERR_PARSE, null, JSONRPCResult.MSG_ERR_PARSE);
        }

        String sendString = json_res.toString();

        // Write the response
        byte[] bout = sendString.getBytes(Constants.DEFAULT_ENCODING);

        // 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.
        String ae = request.getHeader("accept-encoding");
        if (ae != null && ae.indexOf("gzip") != -1) {
            byte[] gzippedOut = gzip(bout);

            // if gzip didn't actually help, abort
            if (bout.length > gzippedOut.length) {
                bout = gzippedOut;
                response.addHeader("Content-Encoding", "gzip");
            }
        }

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

        out.write(bout);

    } catch (Throwable error) {
        //Catch exception
        throw new IOExceptionWithCause("Error during request processing", error);
    } finally {
        executionContext.executionStop();
        printMonitoredRequest(requestInfo);
        executionContext.close();
    }
}

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  .  ja  v a 2  s.  c  o 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;//ww  w  .  j  a  va  2s  . c om
    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();
        }
    }
}