List of usage examples for java.io CharArrayWriter CharArrayWriter
public CharArrayWriter()
From source file:org.topazproject.ambra.auth.web.UsernameReplacementWithGuidFilter.java
private String dumpResponse(final CharResponseWrapper wrapper) throws IOException { log.debug("Response ContentType:" + wrapper.getContentType()); CharArrayWriter caw = new CharArrayWriter(); caw.write(wrapper.toString());//from www . j a v a 2 s. c o m final String response = caw.toString(); log.debug("Response generated:"); log.debug(response); return response; }
From source file:org.sakaiproject.search.component.adapter.contenthosting.XLContentDigester.java
public String getContent(ContentResource contentResource) { CharArrayWriter writer = new CharArrayWriter(); loadContent(writer, contentResource); return new String(writer.toCharArray()); }
From source file:org.milyn.SmooksStandaloneTest.java
public void test_Standalone_CodeConfig_2() throws SAXException, IOException { Smooks smooks = new Smooks(); // Add 2 useragents and configure them with profiles... SmooksUtil.registerProfileSet(/* www . ja v a 2s . c o m*/ DefaultProfileSet.create("message-target1", new String[] { "profile1", "profile2" }), smooks); SmooksUtil.registerProfileSet( DefaultProfileSet.create("message-target2", new String[] { "profile2", "profile3" }), smooks); // Create CDU configs and target them at the profiles... SmooksResourceConfiguration resourceConfig = new SmooksResourceConfiguration("ccc", "profile1 AND not:profile3", RenameElementTrans.class.getName()); resourceConfig.setParameter("new-name", "xxx"); SmooksUtil.registerResource(resourceConfig, smooks); resourceConfig = new SmooksResourceConfiguration("aaa", "profile2", RenameElementTrans.class.getName()); resourceConfig.setParameter("new-name", "zzz"); SmooksUtil.registerResource(resourceConfig, smooks); // Transform the same message for each useragent... String message = "<aaa><bbb>888</bbb><ccc>999</ccc></aaa>"; ExecutionContext context = smooks.createExecutionContext("message-target1"); CharArrayWriter writer = new CharArrayWriter(); smooks.filterSource(context, new StreamSource(new ByteArrayInputStream(message.getBytes())), new StreamResult(writer)); assertEquals("Unexpected transformation result", "<zzz><bbb>888</bbb><xxx>999</xxx></zzz>", writer.toString()); }
From source file:org.dhatim.SmooksStandaloneTest.java
@Test public void test_Standalone_CodeConfig_2() throws SAXException, IOException { Smooks smooks = new Smooks(); // Add 2 useragents and configure them with profiles... SmooksUtil.registerProfileSet(//from w ww .j a v a2s . c o m DefaultProfileSet.create("message-target1", new String[] { "profile1", "profile2" }), smooks); SmooksUtil.registerProfileSet( DefaultProfileSet.create("message-target2", new String[] { "profile2", "profile3" }), smooks); // Create CDU configs and target them at the profiles... SmooksResourceConfiguration resourceConfig = new SmooksResourceConfiguration("ccc", "profile1 AND not:profile3", RenameElementTrans.class.getName()); resourceConfig.setParameter("new-name", "xxx"); SmooksUtil.registerResource(resourceConfig, smooks); resourceConfig = new SmooksResourceConfiguration("aaa", "profile2", RenameElementTrans.class.getName()); resourceConfig.setParameter("new-name", "zzz"); SmooksUtil.registerResource(resourceConfig, smooks); // Transform the same message for each useragent... String message = "<aaa><bbb>888</bbb><ccc>999</ccc></aaa>"; ExecutionContext context = smooks.createExecutionContext("message-target1"); CharArrayWriter writer = new CharArrayWriter(); smooks.filterSource(context, new StreamSource(new ByteArrayInputStream(message.getBytes())), new StreamResult(writer)); assertEquals("Unexpected transformation result", "<zzz><bbb>888</bbb><xxx>999</xxx></zzz>", writer.toString()); }
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; }// w w w. jav a2 s . co m @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; } }; }
From source file:net.wastl.webmail.xml.XMLGenericModel.java
public synchronized void setException(Exception ex) { Element exception = root.createElement("EXCEPTION"); Element ex_message = root.createElement("EX_MESSAGE"); Element ex_stacktrace = root.createElement("EX_STACKTRACE"); exception.appendChild(ex_message);//from ww w. j av a 2s. c o m exception.appendChild(ex_stacktrace); Text msg = root.createTextNode(ex.getMessage()); ex_message.appendChild(msg); String my_stack = ""; CharArrayWriter cstream = new CharArrayWriter(); ex.printStackTrace(new PrintWriter(cstream)); my_stack = cstream.toString(); CDATASection stack = root.createCDATASection(my_stack); ex_stacktrace.appendChild(stack); NodeList nl = getNodeListXPath("//EXCEPTION"); if (nl.getLength() > 0) { statedata.replaceChild(exception, nl.item(0)); } else { statedata.appendChild(exception); } invalidateCache(); //XMLCommon.debugXML(root); }
From source file:com.nominanuda.solr.DataImportHandlerWs.java
private String toXml(DataObject o) { CharArrayWriter w = new CharArrayWriter(); pipe.build(new SAXSource(new JsonXmlReader(), new InputSource(new StringReader(o.toString()))), new StreamResult(w)).run(); return new String(w.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 .ja v a 2 s.c om*/ 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();/*from ww w. j av a 2s. c om*/ 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 readFileFromNode(Node fileNode) throws IOException, ValueFormatException, PathNotFoundException, RepositoryException { CharArrayWriter writer = null; InputStream in = null;/* w ww .j a va 2 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(); } } }