1 16 17 18 package org.apache.xmlrpc; 19 20 import java.io.ByteArrayOutputStream ; 21 import java.io.UnsupportedEncodingException ; 22 import java.io.IOException ; 23 import java.util.Hashtable ; 24 25 34 public class XmlRpcResponseProcessor 35 { 36 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; 37 38 41 public XmlRpcResponseProcessor() 42 { 43 } 44 45 53 public byte[] encodeResponse(Object responseParam, String encoding) 54 throws IOException , UnsupportedEncodingException , XmlRpcException 55 { 56 long now = 0; 57 if (XmlRpc.debug) 58 { 59 now = System.currentTimeMillis(); 60 } 61 62 try 63 { 64 ByteArrayOutputStream buffer = new ByteArrayOutputStream (); 65 XmlWriter writer = new XmlWriter(buffer, encoding); 66 writeResponse(responseParam, writer); 67 writer.flush(); 68 return buffer.toByteArray(); 69 } 70 finally 71 { 72 if (XmlRpc.debug) 73 { 74 System.out.println("Spent " + (System.currentTimeMillis() - now) 75 + " millis encoding response"); 76 } 77 } 78 } 79 80 89 public byte[] encodeException(Exception x, String encoding, int code) 90 { 91 if (XmlRpc.debug) 92 { 93 x.printStackTrace(); 94 } 95 ByteArrayOutputStream buffer = new ByteArrayOutputStream (); 101 102 XmlWriter writer = null; 103 try 104 { 105 writer = new XmlWriter(buffer, encoding); 106 } 107 catch (UnsupportedEncodingException encx) 108 { 109 System.err.println("XmlRpcServer attempted to use " 110 + "unsupported encoding: " + encx); 111 } 114 catch (IOException iox) 115 { 116 System.err.println("XmlRpcServer experienced I/O error " 117 + "writing error response: " + iox); 118 } 119 120 String message = x.toString(); 121 try 123 { 124 writeError(code, message, writer); 125 writer.flush(); 126 } 127 catch (Exception e) 128 { 129 System.err.println("Unable to send error response to " 132 + "client: " + e); 133 } 134 135 return (writer != null ? buffer.toByteArray() : EMPTY_BYTE_ARRAY); 136 } 137 138 146 public byte[] encodeException(Exception x, String encoding) 147 { 148 return encodeException(x, encoding, (x instanceof XmlRpcException) ? ((XmlRpcException) x).code : 0); 149 } 150 153 void writeResponse(Object param, XmlWriter writer) 154 throws XmlRpcException, IOException 155 { 156 writer.startElement("methodResponse"); 157 writer.startElement("params"); 159 writer.startElement("param"); 160 writer.writeObject(param); 161 writer.endElement("param"); 162 writer.endElement("params"); 163 writer.endElement("methodResponse"); 164 } 165 166 169 void writeError(int code, String message, XmlWriter writer) 170 throws XmlRpcException, IOException 171 { 172 Hashtable h = new Hashtable (); 174 h.put("faultCode", new Integer (code)); 175 h.put("faultString", message); 176 writer.startElement("methodResponse"); 177 writer.startElement("fault"); 178 writer.writeObject(h); 179 writer.endElement("fault"); 180 writer.endElement("methodResponse"); 181 } 182 } 183 | Popular Tags |