Apache-XMLRrpc-3.1.3加入日誌監聽器

來源:互聯網
上載者:User

        Apache XML-RPC 是 一個 Java 語言對 XML-RPC 協議的封裝。XML-RPC協議是通過HTTP之上傳輸XML片段來實現遠程方法調用。

        在使用apache-xmlrpc-3.1.3作為XML-RPC用戶端時無法在日誌查看訊息互動的碼流,只能通過抓包工具抓包分析,所以修改了下apache-xmlrpc的源碼,以支援通過日誌來顯示互動XML碼流資訊。

        加入監聽器:

package org.apache.xmlrpc;/** * XmlRpc訊息監聽器 *  * @author Administrator<br/> * @version <br/> * @email: zcg@suntektech.com<br/> * @datetime: 2012-8-28 <br/> */public interface XmlRpcMessageListener {/** * 回調,包括用戶端請求和服務端響應的XML字串內容 *  * @param xmlContent */void onMessage(String xmlContent);}

        用戶端修改:

public Object sendRequest(XmlRpcRequest pRequest) throws XmlRpcException {XmlRpcStreamRequestConfig config = (XmlRpcStreamRequestConfig) pRequest.getConfig();boolean closed = false;try {ReqWriter reqWriter = newReqWriter(pRequest);// added by zcg 2012-08-28,用戶端顯示發送請求的XML日誌if (reqWriter instanceof XmlRpcHttpTransport.ByteArrayReqWriter && getListener() != null) {XmlRpcHttpTransport.ByteArrayReqWriter tmpWriter = (XmlRpcHttpTransport.ByteArrayReqWriter) reqWriter;// System.out.println(tmpWriter.getContentString());getListener().onMessage(tmpWriter.getContentString());}writeRequest(reqWriter);InputStream istream = getInputStream();if (isResponseGzipCompressed(config)) {istream = new GZIPInputStream(istream);}Object result = readResponse(config, istream);closed = true;close();return result;} catch (IOException e) {throw new XmlRpcException("Failed to read server's response: " + e.getMessage(), e);} catch (SAXException e) {Exception ex = e.getException();if (ex != null && ex instanceof XmlRpcException) {throw (XmlRpcException) ex;}throw new XmlRpcException("Failed to generate request: " + e.getMessage(), e);} finally {if (!closed) {try {close();} catch (Throwable ignore) {}}}}protected Object readResponse(XmlRpcStreamRequestConfig pConfig, InputStream pStream) throws XmlRpcException {// added by zcg 2012-09-06 用戶端顯示收到響應的XML日誌if (getListener() != null) {StringBuilder builder = new StringBuilder();BufferedReader r = null;try {r = new BufferedReader(new InputStreamReader(pStream));String line = "";while ((line = r.readLine()) != null) {builder.append(line).append("\n");}getListener().onMessage(builder.toString());} catch (Exception e) {e.printStackTrace();} finally {if (r != null) {try {r.close();} catch (IOException e) {}}}String str = builder.toString();pStream = new ByteArrayInputStream(str.getBytes());}InputSource isource = new InputSource(pStream);XMLReader xr = newXMLReader();XmlRpcResponseParser xp;try {xp = new XmlRpcResponseParser(pConfig, getClient().getTypeFactory());xr.setContentHandler(xp);xr.parse(isource);} catch (SAXException e) {throw new XmlRpcClientException("Failed to parse server's response: " + e.getMessage(), e);} catch (IOException e) {throw new XmlRpcClientException("Failed to read server's response: " + e.getMessage(), e);}if (xp.isSuccess()) {return xp.getResult();}Throwable t = xp.getErrorCause();if (t == null) {throw new XmlRpcException(xp.getErrorCode(), xp.getErrorMessage());}if (t instanceof XmlRpcException) {throw (XmlRpcException) t;}if (t instanceof RuntimeException) {throw (RuntimeException) t;}throw new XmlRpcException(xp.getErrorCode(), xp.getErrorMessage(), t);}

         服務端修改:

/** * Returns, whether the /** Processes a "connection". The "connection" is an * opaque object, which is being handled by the subclasses. *  * @param pConfig *            The request configuration. * @param pConnection *            The "connection" being processed. * @throws XmlRpcException *             Processing the request failed. */public void execute(XmlRpcStreamRequestConfig pConfig, ServerStreamConnection pConnection) throws XmlRpcException {log.debug("execute: ->");try {Object result;Throwable error;InputStream istream = null;try {istream = getInputStream(pConfig, pConnection);{// added by zcg 2012-09-06if (getListener() != null) {StringBuilder builder = new StringBuilder();BufferedReader r = null;try {r = new BufferedReader(new InputStreamReader(istream));String line = "";while ((line = r.readLine()) != null) {builder.append(line).append("\n");}getListener().onMessage(builder.toString());} catch (Exception e) {e.printStackTrace();} finally {if (r != null) {r.close();}}String str = builder.toString();istream = new ByteArrayInputStream(str.getBytes());}}XmlRpcRequest request = getRequest(pConfig, istream);result = execute(request);istream.close();istream = null;error = null;log.debug("execute: Request performed successfully");} catch (Throwable t) {logError(t);result = null;error = t;} finally {if (istream != null) {try {istream.close();} catch (Throwable ignore) {}}}boolean contentLengthRequired = isContentLengthRequired(pConfig);ByteArrayOutputStream baos;OutputStream ostream;if (contentLengthRequired) {baos = new ByteArrayOutputStream();ostream = baos;} else {baos = null;ostream = pConnection.newOutputStream();}ostream = getOutputStream(pConnection, pConfig, ostream);try {if (error == null) {writeResponse(pConfig, ostream, result);} else {writeError(pConfig, ostream, error);}ostream.close();ostream = null;} finally {if (ostream != null) {try {ostream.close();} catch (Throwable ignore) {}}}if (baos != null) {// added by zcg 2012-08-28if (getListener() != null) {getListener().onMessage(new String(baos.toByteArray()));}OutputStream dest = getOutputStream(pConfig, pConnection, baos.size());try {baos.writeTo(dest);dest.close();dest = null;} finally {if (dest != null) {try {dest.close();} catch (Throwable ignore) {}}}}pConnection.close();pConnection = null;} catch (IOException e) {throw new XmlRpcException("I/O error while processing request: " + e.getMessage(), e);} finally {if (pConnection != null) {try {pConnection.close();} catch (Throwable ignore) {}}}log.debug("execute: <-");}

        用戶端使用方法:

XmlRpcClient instance = new XmlRpcClient();// apache xmlrpc用戶端配置資訊XmlRpcClientConfigImpl config = new XmlRpcClientConfigImpl();config.setServerURL(new URL(url));config.setConnectionTimeout(2 * 1000);config.setReplyTimeout(30 * 1000);// 允許使用apache xmlrpc的擴充功能config.setEnabledForExtensions(true);// 設定為true,服務端拋出異常用戶端將能夠捕捉到config.setEnabledForExceptions(true);// 產生xmlrpc用戶端instance.setTransportFactory(new XmlRpcLite14HttpTransportFactory(instance));instance.setConfig(config);instance.setListener(new VvmgwXmlRpcClientHandler());

        服務端使用方法:

public class XmlRpcServerServlet extends XmlRpcServlet implements XmlRpcMessageListener {private static LogProxy logger = LogHandler.getLogger();/** * Creates a new handler mapping. The default implementation loads a * property file from the resource <code>/XmlRpcServlet.properties</code> */protected XmlRpcHandlerMapping newXmlRpcHandlerMapping() throws XmlRpcException {URL url = XmlRpcServerServlet.class.getResource("/resources/xmlrpc-config.properties");if (url == null) {throw new XmlRpcException("Failed to locate resource xmlrpc-config.properties");}try {return newPropertyHandlerMapping(url);} catch (IOException e) {throw new XmlRpcException("Failed to load resource " + url + ": " + e.getMessage(), e);}}public void onMessage(String xmlContent) {if (logger.isTraceEnabled()) {logger.trace("Response: " + xmlContent);}}public XmlRpcMessageListener getListener() {return this;}}




聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.