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 object stack. As we process xml elements, pieces of the
45 * return value are pushed onto and popped off of this stack.
47 * The general protocol is that any time a <value> tag is
48 * encountered, an empty String ("") is pushed onto the stack. If
49 * the <value/> node has content (either an anonymous
50 * string or some other XML node), that content replaces the
53 * If an <array> tag is encountered, a null is pushed onto the
54 * stack. When a </data> is encountered, we search back on the
55 * stack to the last null, replace it with a NativeArray, and
56 * insert into it all elements above it on the stack.
58 * If a <struct> tag is encountered, a JSObject is pushed
59 * onto the stack. If a <name> tag is encountered, its CDATA is
60 * pushed onto the stack. When a </member> is encountered, the
61 * name (second element on stack) and value (top of stack) are
62 * popped off the stack and inserted into the struct (third
65 protected Vec objects = null;
67 /** used to detect multi-ref data */
70 /** True iff the return value is a fault (and should be thrown as an exception) */
71 protected boolean fault = false;
74 // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
76 public void startElement(String name, String[] keys, Object[] vals, int line, int col) {
77 if (name.equals("fault")) fault = true;
78 else if (name.equals("struct")) objects.setElementAt(new JSObject(false), objects.size() - 1);
79 else if (name.equals("array")) objects.setElementAt(null, objects.size() - 1);
80 else if (name.equals("value")) objects.addElement("");
83 public void endElement(String name, int line, int col) {
85 if (name.equals("int") || name.equals("i4"))
86 objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
88 else if (name.equals("boolean"))
89 objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
91 else if (name.equals("string"))
92 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
94 else if (name.equals("double"))
95 objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
97 else if (name.equals("base64"))
98 objects.setElementAt(new String(Base64.decode(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
100 else if (name.equals("name"))
101 objects.addElement(new String(content.getBuf(), 0, content.size()));
103 else if (name.equals("value") && "".equals(objects.lastElement()))
104 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
106 else if (name.equals("dateTime.iso8601")) {
107 String s = new String(content.getBuf(), 0, content.size());
111 while(Character.isWhitespace(s.charAt(i))) i++;
112 if (i > 0) s = s.substring(i);
115 NativeDate nd = (NativeDate)Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date");
116 double date = NativeDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
117 Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
118 Double.valueOf(s.substring(6, 8)).doubleValue(),
119 Double.valueOf(s.substring(9, 11)).doubleValue(),
120 Double.valueOf(s.substring(12, 14)).doubleValue(),
121 Double.valueOf(s.substring(15, 17)).doubleValue(),
124 nd.jsFunction_setTime(NativeDate.internalUTC(date));
125 objects.setElementAt(nd, objects.size() - 1);
127 } catch (Exception e) {
128 if (Log.on) Log.log(this, "error parsing date : " + s);
129 if (Log.on) Log.log(this, e);
132 } else if (name.equals("member")) {
133 Object memberValue = objects.elementAt(objects.size() - 1);
134 String memberName = (String)objects.elementAt(objects.size() - 2);
135 Scriptable struct = (Scriptable)objects.elementAt(objects.size() - 3);
136 struct.put(memberName, struct, memberValue);
137 objects.setSize(objects.size() - 2);
139 } else if (name.equals("data")) {
141 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
142 Object[] arr = new Object[objects.size() - i - 1];
143 for(int j = i + 1; j<objects.size(); j++) arr[j - i - 1] = objects.elementAt(j);
144 objects.setElementAt(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, arr), i);
145 objects.setSize(i + 1);
152 public void content(char[] ch, int start, int length, int line, int col) {
153 try { content.write(ch, start, length); }
154 catch (Exception e) {
155 if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
156 if (Log.on) Log.log(this, e);
161 // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
163 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
164 void appendObject(Object o, StringBuffer sb) throws JavaScriptException {
167 throw new JavaScriptException("attempted to send a null value via XML-RPC");
169 } else if (o instanceof Number) {
170 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
171 sb.append(" <value><i4>");
172 sb.append(((Number)o).intValue());
173 sb.append("</i4></value>\n");
175 sb.append(" <value><double>");
177 sb.append("</double></value>\n");
180 } else if (o instanceof Boolean) {
181 sb.append(" <value><boolean>");
182 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
183 sb.append("</boolean></value>\n");
185 } else if (o instanceof String) {
186 sb.append(" <value><string>");
187 String s = (String)o;
188 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
191 char[] cbuf = s.toCharArray();
194 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
195 sb.append(cbuf, oldi, i - oldi);
196 if (i >= cbuf.length) break;
197 if (cbuf[i] == '<') sb.append("<");
198 else if (cbuf[i] == '&') sb.append("&");
200 if (i >= cbuf.length) break;
203 sb.append("</string></value>\n");
205 } else if (o instanceof NativeArray) {
206 if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
207 tracker.put(o, Boolean.TRUE);
208 sb.append(" <value><array><data>\n");
209 NativeArray na = (NativeArray)o;
210 for(int i=0; i<na.jsGet_length(); i++)
211 appendObject(na.get(i, na), sb);
212 sb.append(" </data></array></value>\n");
214 } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
215 if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
216 tracker.put(o, Boolean.TRUE);
217 Scriptable s = (Scriptable)o;
218 sb.append(" <value><struct>\n");
219 Object[] ids = s.getIds();
220 for(int i=0; i<ids.length; i++) {
221 sb.append(" <member><name>" + ids[i] + "</name>\n");
222 appendObject(s.get(ids[i].toString(), s), sb);
223 sb.append(" </member>\n");
225 sb.append(" </struct></value>\n");
228 throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
233 // this is synchronized in case multiple threads try to make a call on the same object... in the future, change this
234 // behavior to use pipelining.
235 public synchronized Object call(Object[] args) throws JavaScriptException, IOException {
236 if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
238 if (tracker == null) tracker = new Hash();
239 else tracker.clear();
241 if (objects == null) objects = new Vec();
242 else objects.setSize(0);
244 HTTP http = new HTTP(url);
245 String content = send(args, http);
246 OutputStream os = new BufferedOutputStream(http.getOutputStream(content.length(), "text/xml"), 4000);
247 PrintWriter ps = !Log.verbose ?
248 new PrintWriter(os) :
249 new PrintWriter(new FilterWriter(new OutputStreamWriter(os)) {
250 public void write(int i) throws IOException {
252 if (Log.on) Log.log(this, "send: " + ((char)i));
254 public void write(String s, int start, int len) throws IOException {
255 super.write(s, start, len);
256 if (Log.on) Log.log(this, "send: " + s.substring(start, start + len));
258 public void write(char[] c, int start, int len) throws IOException {
259 super.write(c, start, len);
260 if (Log.on) Log.log(this, "send: " + new String(c, start, len));
263 ps.print(content.toString());
266 BufferedReader br = !Log.verbose ?
267 new BufferedReader(new InputStreamReader(new Filter(http.getInputStream()))) :
268 new BufferedReader(new FilterReader(new InputStreamReader(new Filter(http.getInputStream()))) {
269 public int read() throws IOException {
270 int i = super.read();
271 System.out.println("X " + i);
272 if (Log.on) Log.log(this, "recv: " + ((char)i));
275 public int read(char[] c, int off, int len) throws IOException {
276 int ret = super.read(c, off, len);
277 System.out.println("Y " + ret);
278 if (ret == -1) return ret;
279 if (Log.on) Log.log(this, "recv: " + new String(c, off, ret));
286 protected String send(Object[] args, HTTP http) throws JavaScriptException, IOException {
287 StringBuffer content = new StringBuffer();
288 content.append("<?xml version=\"1.0\"?>\n");
289 content.append(" <methodCall>\n");
290 content.append(" <methodName>");
291 content.append(methodname);
292 content.append("</methodName>\n");
293 if (args.length > 0) {
294 content.append(" <params>\n");
295 for(int i=0; i<args.length; i++) {
296 content.append(" <param>\n");
297 appendObject(args[i], content);
298 content.append(" </param>\n");
300 content.append(" </params>\n");
302 content.append(" </methodCall>");
303 return content.toString();
306 protected Object recieve(BufferedReader br) throws JavaScriptException, IOException {
310 } catch (XML.SAXException e) {
311 if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
312 throw new JavaScriptException("reply from server was not well-formed XML: " + e);
315 if (fault) throw new JavaScriptException(objects.elementAt(0));
316 if (objects.size() == 0) return null;
317 return objects.elementAt(0);
320 public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
322 // put ourselves in the background
323 Thread thread = Thread.currentThread();
324 if (!(thread instanceof ThreadMessage)) {
325 if (Log.on) Log.log(this, "RPC calls may only be made from background threads");
328 ThreadMessage mythread = (ThreadMessage)thread;
329 mythread.setPriority(Thread.MIN_PRIORITY);
330 mythread.done.release();
335 } catch (IOException se) {
336 if (Log.on) Log.log(this, se);
337 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
338 throw new JavaScriptException("socket exception: " + se);
340 } catch (JavaScriptException jse) {
341 Object val = jse.getValue();
342 if (val instanceof String) {
343 if (Log.on) Log.log(this, val.toString());
344 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
349 // okay, let ourselves be brought to the foreground
350 MessageQueue.add(mythread);
351 mythread.setPriority(Thread.NORM_PRIORITY);
357 /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
358 public Object get(String name, Scriptable start) {
359 return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name);
362 public XMLRPC(String url, String methodname) {
364 this.methodname = methodname;
368 // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
370 /** CharArrayWriter that lets us touch its buffer */
371 protected static class AccessibleCharArrayWriter extends CharArrayWriter {
372 public char[] getBuf() { return buf; }
373 public AccessibleCharArrayWriter(int i) { super(i); }
376 /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
377 private static class Filter extends FilterInputStream {
378 public Filter(InputStream is) { super(is); }
379 public int read() throws IOException {
381 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
384 public int read(byte[] b) throws IOException {
386 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
387 return super.read(b);
389 public int read(byte[] b, int i, int j) throws IOException {
391 while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
392 return super.read(b, i, j);
397 // Methods Required by Rhino ////////////////////////////////////////////////////////
399 public String getClassName() { return "XMLRPC"; }
400 public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
401 public void delete(String name) { }
402 public Scriptable getParentScope() { return null; }
403 public void setParentScope(Scriptable p) { }
404 public boolean hasInstance(Scriptable value) { return false; }
405 public Scriptable getPrototype() { return null; }
406 public void setPrototype(Scriptable p) { }
407 public void delete(int i) { }
408 public Object getDefaultValue(Class hint) { return "XML-RPC"; }
409 public void put(int i, Scriptable start, Object value) { }
410 public Object get(int i, Scriptable start) { return null; }
411 public void put(String name, Scriptable start, Object value) { }
412 public boolean has(String name, Scriptable start) { return true; }
413 public boolean has(int i, Scriptable start) { return false; }
414 public Object[] getIds() { return new Object[] { }; }