1 // Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
7 import org.mozilla.javascript.*;
9 import org.bouncycastle.util.encoders.Base64;
12 * An XML-RPC client implemented as a Rhino JavaScript Host
13 * Object. See the XWT spec for information on its behavior.
15 * NOTE: this client is EXTREMELY lenient in the responses it will
16 * accept; there are many, many invalid responses that it will
17 * successfully parse and return. Do NOT use this to determine the
18 * validity of your server.
20 * This client conforms to <a href="http://www.xmlrpc.com/spec">The
21 * XML-RPC Spec</a>, subject to these limitations:
23 * <li> XMLRPC cannot invoke methods that require a <base64/> argument
24 * <li> if a return value contains a <base64/>, it will be returned as a string
25 * <li> The decision to pass a number as <i4/> or <double/> is based
26 * entirely on whether or not the argument is fractional. Thus, it
27 * is impossible to pass a non-fractional number to an xmlrpc
28 * method that insists on being called with a <double/> element. We
29 * hope that most xml-rpc servers will be able to automatically
33 class XMLRPC extends XML implements Function {
35 /** the url to connect to */
36 protected String url = null;
38 /** the method name to invoke on the remove server */
39 protected String methodname = null;
41 /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
42 protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
44 /** the HTTP connection to use */
45 protected HTTP http = null;
47 /** The object stack. As we process xml elements, pieces of the
48 * return value are pushed onto and popped off of this stack.
50 * The general protocol is that any time a <value> tag is
51 * encountered, an empty String ("") is pushed onto the stack. If
52 * the <value/> node has content (either an anonymous
53 * string or some other XML node), that content replaces the
56 * If an <array> tag is encountered, a null is pushed onto the
57 * stack. When a </data> is encountered, we search back on the
58 * stack to the last null, replace it with a NativeArray, and
59 * insert into it all elements above it on the stack.
61 * If a <struct> tag is encountered, a JSObject is pushed
62 * onto the stack. If a <name> tag is encountered, its CDATA is
63 * pushed onto the stack. When a </member> is encountered, the
64 * name (second element on stack) and value (top of stack) are
65 * popped off the stack and inserted into the struct (third
68 protected Vec objects = null;
70 /** used to detect multi-ref data */
73 /** True iff the return value is a fault (and should be thrown as an exception) */
74 protected boolean fault = false;
77 // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
79 public void startElement(String name, String[] keys, Object[] vals, int line, int col) {
81 if (name.equals("fault")) fault = true;
82 else if (name.equals("struct")) objects.setElementAt(new JSObject(false), objects.size() - 1);
83 else if (name.equals("array")) objects.setElementAt(null, objects.size() - 1);
84 else if (name.equals("value")) objects.addElement("");
87 public void endElement(String name, int line, int col) {
89 if (name.equals("int") || name.equals("i4"))
90 objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
92 else if (name.equals("boolean"))
93 objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
95 else if (name.equals("string"))
96 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
98 else if (name.equals("double"))
99 objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
101 else if (name.equals("base64"))
102 objects.setElementAt(new ByteStream(Base64.decode(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
104 else if (name.equals("name"))
105 objects.addElement(new String(content.getBuf(), 0, content.size()));
107 else if (name.equals("value") && "".equals(objects.lastElement()))
108 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
110 else if (name.equals("dateTime.iso8601")) {
111 String s = new String(content.getBuf(), 0, content.size());
115 while(Character.isWhitespace(s.charAt(i))) i++;
116 if (i > 0) s = s.substring(i);
119 NativeDate nd = (NativeDate)Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date");
120 double date = NativeDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
121 Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
122 Double.valueOf(s.substring(6, 8)).doubleValue(),
123 Double.valueOf(s.substring(9, 11)).doubleValue(),
124 Double.valueOf(s.substring(12, 14)).doubleValue(),
125 Double.valueOf(s.substring(15, 17)).doubleValue(),
128 nd.jsFunction_setTime(NativeDate.internalUTC(date));
129 objects.setElementAt(nd, objects.size() - 1);
131 } catch (Exception e) {
132 if (Log.on) Log.log(this, "error parsing date : " + s);
133 if (Log.on) Log.log(this, e);
136 } else if (name.equals("member")) {
137 Object memberValue = objects.elementAt(objects.size() - 1);
138 String memberName = (String)objects.elementAt(objects.size() - 2);
139 Scriptable struct = (Scriptable)objects.elementAt(objects.size() - 3);
140 struct.put(memberName, struct, memberValue);
141 objects.setSize(objects.size() - 2);
143 } else if (name.equals("data")) {
145 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
146 Object[] arr = new Object[objects.size() - i - 1];
147 for(int j = i + 1; j<objects.size(); j++) arr[j - i - 1] = objects.elementAt(j);
148 objects.setElementAt(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, arr), i);
149 objects.setSize(i + 1);
156 public void content(char[] ch, int start, int length, int line, int col) {
157 try { content.write(ch, start, length); }
158 catch (Exception e) {
159 if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
160 if (Log.on) Log.log(this, e);
165 // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
167 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
168 void appendObject(Object o, StringBuffer sb) throws JavaScriptException {
171 throw new JavaScriptException("attempted to send a null value via XML-RPC");
173 } else if (o instanceof Number) {
174 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
175 sb.append(" <value><i4>");
176 sb.append(((Number)o).intValue());
177 sb.append("</i4></value>\n");
179 sb.append(" <value><double>");
181 sb.append("</double></value>\n");
184 } else if (o instanceof Boolean) {
185 sb.append(" <value><boolean>");
186 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
187 sb.append("</boolean></value>\n");
189 } else if (o instanceof ByteStream) {
191 sb.append(" <value><base64>\n");
192 InputStream is = ((ByteStream)o).getInputStream();
193 byte[] buf = new byte[54];
195 int numread = is.read(buf, 0, 54);
196 if (numread == -1) break;
197 byte[] writebuf = buf;
198 if (numread < buf.length) {
199 writebuf = new byte[numread];
200 System.arraycopy(buf, 0, writebuf, 0, numread);
203 sb.append(new String(Base64.encode(writebuf)));
206 sb.append("\n </base64></value>\n");
207 } catch (IOException e) {
208 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
209 if (Log.on) Log.log(this, e);
210 throw new JavaScriptException("caught IOException while attempting to send a ByteStream via XML-RPC");
213 } else if (o instanceof String) {
214 sb.append(" <value><string>");
215 String s = (String)o;
216 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
219 char[] cbuf = s.toCharArray();
222 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
223 sb.append(cbuf, oldi, i - oldi);
224 if (i >= cbuf.length) break;
225 if (cbuf[i] == '<') sb.append("<");
226 else if (cbuf[i] == '&') sb.append("&");
228 if (i >= cbuf.length) break;
231 sb.append("</string></value>\n");
233 } else if (o instanceof NativeDate) {
234 sb.append(" <value><dateTime.iso8601>");
235 NativeDate nd = (NativeDate)o;
236 Date d = new Date(nd.getRawTime());
237 sb.append(d.getYear() + 1900);
238 if (d.getMonth() + 1 < 10) sb.append('0');
239 sb.append(d.getMonth() + 1);
240 if (d.getDate() < 10) sb.append('0');
241 sb.append(d.getDate());
243 if (d.getHours() < 10) sb.append('0');
244 sb.append(d.getHours());
246 if (d.getMinutes() < 10) sb.append('0');
247 sb.append(d.getMinutes());
249 if (d.getSeconds() < 10) sb.append('0');
250 sb.append(d.getSeconds());
251 sb.append("</dateTime.iso8601></value>\n");
253 } else if (o instanceof NativeArray) {
254 if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
255 tracker.put(o, Boolean.TRUE);
256 sb.append(" <value><array><data>\n");
257 NativeArray na = (NativeArray)o;
258 for(int i=0; i<na.jsGet_length(); i++)
259 appendObject(na.get(i, na), sb);
260 sb.append(" </data></array></value>\n");
262 } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
263 if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
264 tracker.put(o, Boolean.TRUE);
265 Scriptable s = (Scriptable)o;
266 sb.append(" <value><struct>\n");
267 Object[] ids = s.getIds();
268 for(int i=0; i<ids.length; i++) {
269 sb.append(" <member><name>" + ids[i] + "</name>\n");
270 appendObject(s.get(ids[i].toString(), s), sb);
271 sb.append(" </member>\n");
273 sb.append(" </struct></value>\n");
276 throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
281 // this is synchronized in case multiple threads try to make a call on the same object... in the future, change this
282 // behavior to use pipelining.
283 public synchronized Object call(Object[] args) throws JavaScriptException, IOException {
284 if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
286 if (tracker == null) tracker = new Hash();
287 else tracker.clear();
289 if (objects == null) objects = new Vec();
290 else objects.setSize(0);
292 String content = send(args, http);
295 BufferedReader br2 = new BufferedReader(new StringReader(content));
296 while ((s = br2.readLine()) != null) Log.log(this, "send: " + s);
299 HTTP.HTTPInputStream is = http.POST("text/xml", content);
301 BufferedReader br = !Log.verbose ?
302 new BufferedReader(new InputStreamReader(new Filter(is))) :
303 new BufferedReader(new FilterReader(new InputStreamReader(new Filter(is))) {
304 public int read() throws IOException {
305 int i = super.read();
306 if (Log.on) Log.log(this, "recv: " + ((char)i));
309 public int read(char[] c, int off, int len) throws IOException {
310 int ret = super.read(c, off, len);
311 if (ret == -1) return ret;
313 BufferedReader br2 = new BufferedReader(new StringReader(new String(c, off, ret)));
314 while ((s = br2.readLine()) != null) Log.log(this, "recv: " + s);
324 protected String send(Object[] args, HTTP http) throws JavaScriptException, IOException {
325 StringBuffer content = new StringBuffer();
326 content.append("\r\n");
327 content.append("<?xml version=\"1.0\"?>\n");
328 content.append(" <methodCall>\n");
329 content.append(" <methodName>");
330 content.append(methodname);
331 content.append("</methodName>\n");
332 content.append(" <params>\n");
333 for(int i=0; i<args.length; i++) {
334 content.append(" <param>\n");
335 appendObject(args[i], content);
336 content.append(" </param>\n");
338 content.append(" </params>\n");
339 content.append(" </methodCall>");
340 return content.toString();
343 protected Object recieve(BufferedReader br) throws JavaScriptException, IOException {
347 } catch (XML.SAXException e) {
348 if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
349 throw new JavaScriptException("reply from server was not well-formed XML: " + e);
352 if (fault) throw new JavaScriptException(objects.elementAt(0));
353 if (objects.size() == 0) return null;
354 return objects.elementAt(0);
357 public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
359 if (!ThreadMessage.suspendThread()) return null;
363 } catch (IOException se) {
364 if (Log.on) Log.log(this, se);
365 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
366 throw new JavaScriptException("socket exception: " + se);
368 } catch (JavaScriptException jse) {
369 Object val = jse.getValue();
370 if (val instanceof String) {
371 if (Log.on) Log.log(this, val.toString());
372 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
376 ThreadMessage.resumeThread();
381 /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
382 public Object get(String name, Scriptable start) {
383 return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name, http);
386 public XMLRPC(String url, String methodname) {
387 this(url, methodname, new HTTP(url));
390 public XMLRPC(String url, String methodname, HTTP http) {
393 this.methodname = methodname;
397 // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
399 /** CharArrayWriter that lets us touch its buffer */
400 protected static class AccessibleCharArrayWriter extends CharArrayWriter {
401 public char[] getBuf() { return buf; }
402 public AccessibleCharArrayWriter(int i) { super(i); }
405 /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
406 private static class Filter extends FilterInputStream {
407 public Filter(InputStream is) { super(is); }
408 public int read() throws IOException {
410 while(MessageQueue.nonThreadEventsInQueue > 0) try { Thread.sleep(100); } catch (Exception e) { };
413 public int read(byte[] b) throws IOException {
415 while(MessageQueue.nonThreadEventsInQueue > 0) try { Thread.sleep(100); } catch (Exception e) { };
416 return super.read(b);
418 public int read(byte[] b, int i, int j) throws IOException {
420 while(MessageQueue.nonThreadEventsInQueue > 0) try { Thread.sleep(100); } catch (Exception e) { };
421 return super.read(b, i, j);
426 // Methods Required by Rhino ////////////////////////////////////////////////////////
428 public String getClassName() { return "XMLRPC"; }
429 public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
430 public void delete(String name) { }
431 public Scriptable getParentScope() { return null; }
432 public void setParentScope(Scriptable p) { }
433 public boolean hasInstance(Scriptable value) { return false; }
434 public Scriptable getPrototype() { return null; }
435 public void setPrototype(Scriptable p) { }
436 public void delete(int i) { }
437 public Object getDefaultValue(Class hint) { return "XML-RPC"; }
438 public void put(int i, Scriptable start, Object value) { }
439 public Object get(int i, Scriptable start) { return null; }
440 public void put(String name, Scriptable start, Object value) { }
441 public boolean has(String name, Scriptable start) { return true; }
442 public boolean has(int i, Scriptable start) { return false; }
443 public Object[] getIds() { return new Object[] { }; }