List of usage examples for java.io CharArrayWriter toString
public String 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(// www .j a v a2s . com 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.apache.solr.client.solrj.impl.BackupRequestLBHttpSolrServer.java
@Override protected Exception addZombie(HttpSolrServer server, Exception e) { CharArrayWriter cw = new CharArrayWriter(); PrintWriter pw = new PrintWriter(cw); e.printStackTrace(pw);//from w ww . ja v a2 s .c o m pw.flush(); String stack = cw.toString(); log.info("Server :{} did not respond correctly or timed out, the server is zombied. {}", server.baseUrl, e.toString() + stack); return super.addZombie(server, e); }
From source file:org.milyn.delivery.dom.SmooksVisitorPhaseTest.java
public void test_filtering() throws IOException, SAXException { Smooks smooks = new Smooks(); BasicExecutionEventListener eventListener = new BasicExecutionEventListener(); smooks.addConfigurations("config2.xml", getClass().getResourceAsStream("config2.xml")); // Create an exec context - no profiles.... ExecutionContext executionContext = smooks.createExecutionContext(); CharArrayWriter outputWriter = new CharArrayWriter(); // Filter the input message to the outputWriter, using the execution context... executionContext.setEventListener(eventListener); smooks.filterSource(executionContext, new StreamSource(getClass().getResourceAsStream("testxml1.xml")), new StreamResult(outputWriter)); log.debug(outputWriter.toString()); byte[] expected = StreamUtils.readStream(getClass().getResourceAsStream("testxml1-expected.xml")); assertTrue(StreamUtils.compareCharStreams(new ByteArrayInputStream(expected), new ByteArrayInputStream(outputWriter.toString().getBytes()))); assertEquals(32, eventListener.getEvents().size()); }
From source file:org.dhatim.delivery.dom.SmooksVisitorPhaseTest.java
@Test public void test_filtering() throws IOException, SAXException { Smooks smooks = new Smooks(); BasicExecutionEventListener eventListener = new BasicExecutionEventListener(); smooks.addConfigurations("config2.xml", getClass().getResourceAsStream("config2.xml")); // Create an exec context - no profiles.... ExecutionContext executionContext = smooks.createExecutionContext(); CharArrayWriter outputWriter = new CharArrayWriter(); // Filter the input message to the outputWriter, using the execution context... executionContext.setEventListener(eventListener); smooks.filterSource(executionContext, new StreamSource(getClass().getResourceAsStream("testxml1.xml")), new StreamResult(outputWriter)); log.debug(outputWriter.toString()); byte[] expected = StreamUtils.readStream(getClass().getResourceAsStream("testxml1-expected.xml")); assertTrue(StreamUtils.compareCharStreams(new ByteArrayInputStream(expected), new ByteArrayInputStream(outputWriter.toString().getBytes()))); assertEquals(32, eventListener.getEvents().size()); }
From source file:org.rhq.plugins.agent.AgentServerComponent.java
public OperationResult invokeOperation(String name, Configuration params) { OperationResult result = null;// w w w .j av a 2 s . co m // I know all operation names have identical MBean operations on the agent management MBean // I also know about all operations that have void and non-void parameters try { if ((params == null) || (params.getProperties().size() == 0)) { result = (OperationResult) getAgentBean().getOperation(name).invoke(); } else { if (name.equals("retrievePluginInfo")) { String pluginToUpdate = params.getSimple("pluginName").getStringValue(); result = (OperationResult) getAgentBean().getOperation(name).invoke(pluginToUpdate); } else if (name.equals("executeAvailabilityScan")) { Boolean changesOnly = params.getSimple("changesOnly").getBooleanValue(); result = (OperationResult) getAgentBean().getOperation(name).invoke(changesOnly); } else if (name.equals("retrieveCurrentDateTime")) { String timeZone = params.getSimple("timeZone").getStringValue(); result = new OperationResult(); result.getComplexResults().put( new PropertySimple("dateTime", getAgentBean().getOperation(name).invoke(timeZone))); } else if (name.equals("setDebugMode")) { Boolean enabled = params.getSimple("enabled").getBooleanValue(); Boolean traceMessaging = params.getSimple("traceMessaging").getBooleanValue(); result = new OperationResult(); getAgentBean().getOperation(name).invoke(enabled, traceMessaging); } else if (name.equals("executePromptCommand")) { String command = params.getSimple("command").getStringValue(); result = new OperationResult(); try { Object output = getAgentBean().getOperation(name).invoke(command); result.getComplexResults().put(new PropertySimple("output", output)); } catch (EmsInvocationException eie) { if (eie.getCause() instanceof MBeanException && eie.getCause().getCause() instanceof ExecutionException) { // the prompt command threw the exception - in this case: // the message is the prompt output and the cause is the actual prompt exception ExecutionException ee = (ExecutionException) eie.getCause().getCause(); String output = ee.getMessage(); CharArrayWriter caw = new CharArrayWriter(); ee.getCause().printStackTrace(new PrintWriter(caw)); String error = caw.toString(); result.getComplexResults().put(new PropertySimple("output", output)); result.getComplexResults().put(new PropertySimple("error", error)); } else { throw eie; } } } else if (name.equals("switchToServer")) { String server = params.getSimpleValue("server", null); getAgentBean().getOperation(name).invoke(server); } else { // this should really never happen throw new IllegalArgumentException("Operation [" + name + "] does not support params"); } } } catch (Exception e) { throw new RuntimeException("Failed to invoke operation [" + name + "]", e); } return result; }
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;// w w w . j ava2s .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:org.jabsorb.JSONRPCResult.java
public String toString() { JSONObject o = new JSONObject(); try {//from w w w.ja va 2 s . co m if (errorCode == CODE_SUCCESS) { o.put("id", id); o.put("result", result); if (fixUps != null && fixUps.size() > 0) { JSONArray fixups = new JSONArray(); for (Iterator i = fixUps.iterator(); i.hasNext();) { FixUp fixup = (FixUp) i.next(); fixups.put(fixup.toJSONArray()); } o.put("fixups", fixups); } } else if (errorCode == CODE_REMOTE_EXCEPTION) { o.put("id", id); if (result instanceof Throwable) { Throwable e = (Throwable) result; CharArrayWriter caw = new CharArrayWriter(); e.printStackTrace(new PrintWriter(caw)); JSONObject err = new JSONObject(); err.put("code", new Integer(errorCode)); err.put("msg", e.getMessage()); err.put("trace", caw.toString()); o.put("error", err); } else { // When using a customized implementation of ExceptionTransformer // an error result may be something other than Throwable. In this // case, it has to be a JSON compatible object, we will just store it // to the 'error' property of the response. o.put("error", result); } } else { JSONObject err = new JSONObject(); err.put("code", new Integer(errorCode)); err.put("msg", result); o.put("id", id); o.put("error", err); } } catch (JSONException e) { // this would have been a null pointer exception in the previous json.org library. throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e); } return o.toString(); }
From source file:org.jabsorb.ng.JSONRPCResult.java
@Override public String toString() { final JSONObject o = new JSONObject(); try {/*from ww w .j a v a 2 s . c o m*/ if (errorCode == CODE_SUCCESS) { o.put("id", id); o.put("result", result); if (fixUps != null && fixUps.size() > 0) { final JSONArray fixups = new JSONArray(); for (final Iterator<FixUp> i = fixUps.iterator(); i.hasNext();) { final FixUp fixup = i.next(); fixups.put(fixup.toJSONArray()); } o.put("fixups", fixups); } } else if (errorCode == CODE_REMOTE_EXCEPTION) { o.put("id", id); if (result instanceof Throwable) { final Throwable e = (Throwable) result; final CharArrayWriter caw = new CharArrayWriter(); e.printStackTrace(new PrintWriter(caw)); final JSONObject err = new JSONObject(); err.put("code", new Integer(errorCode)); err.put("message", e.getMessage()); err.put("trace", caw.toString()); // PATCH: Add the Java exception class hint err.put("javaClass", e.getClass().getName()); o.put("error", err); } else { // When using a customized implementation of // ExceptionTransformer // an error result may be something other than Throwable. In // this // case, it has to be a JSON compatible object, we will just // store it // to the 'error' property of the response. o.put("error", result); } } else { final JSONObject err = new JSONObject(); err.put("code", new Integer(errorCode)); err.put("message", result); o.put("id", id); o.put("error", err); } } catch (final JSONException e) { // this would have been a null pointer exception in the previous // json.org library. throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e); } return o.toString(); }
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 w w w. ja va 2 s. 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:org.apache.solr.client.solrj.impl.BackupRequestLBHttpSolrClient.java
@Override protected Exception addZombie(HttpSolrClient server, Exception e) { CharArrayWriter cw = new CharArrayWriter(); PrintWriter pw = new PrintWriter(cw); e.printStackTrace(pw);/* www. ja v a2s . co m*/ pw.flush(); String stack = cw.toString(); log.info("Server :{} did not respond correctly or timed out, the server is zombied. {}", server.getBaseURL(), e.toString() + stack); return super.addZombie(server, e); }