1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
9 import org.bouncycastle.util.encoders.Base64;
12 * An XML-RPC client implemented as a JavaScript Host Object. See the
13 * 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 JS.Callable {
35 public Object[] keys() { throw new Error("not implemented"); }
37 /** the url to connect to */
38 protected String url = null;
40 /** the method name to invoke on the remove server */
41 protected String methodname = null;
43 /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
44 protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
46 /** the HTTP connection to use */
47 protected HTTP http = null;
49 /** The object stack. As we process xml elements, pieces of the
50 * return value are pushed onto and popped off of this stack.
52 * The general protocol is that any time a <value> tag is
53 * encountered, an empty String ("") is pushed onto the stack. If
54 * the <value/> node has content (either an anonymous
55 * string or some other XML node), that content replaces the
58 * If an <array> tag is encountered, a null is pushed onto the
59 * stack. When a </data> is encountered, we search back on the
60 * stack to the last null, replace it with a NativeJS.Array, and
61 * insert into it all elements above it on the stack.
63 * If a <struct> tag is encountered, a JSObject is pushed
64 * onto the stack. If a <name> tag is encountered, its CDATA is
65 * pushed onto the stack. When a </member> is encountered, the
66 * name (second element on stack) and value (top of stack) are
67 * popped off the stack and inserted into the struct (third
70 protected Vec objects = null;
72 /** used to detect multi-ref data */
75 /** True iff the return value is a fault (and should be thrown as an exception) */
76 protected boolean fault = false;
79 // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
81 private class Helper extends XML {
82 public Helper() { super(BUFFER_SIZE); }
84 public void startElement(XML.Element c) {
86 if (c.localName.equals("fault")) fault = true;
87 else if (c.localName.equals("struct")) objects.setElementAt(new JS.Obj(), objects.size() - 1);
88 else if (c.localName.equals("array")) objects.setElementAt(null, objects.size() - 1);
89 else if (c.localName.equals("value")) objects.addElement("");
92 public void endElement(XML.Element c) {
94 if (c.localName.equals("int") || c.localName.equals("i4"))
95 objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
97 else if (c.localName.equals("boolean"))
98 objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
100 else if (c.localName.equals("string"))
101 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
103 else if (c.localName.equals("double"))
104 objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
106 else if (c.localName.equals("base64"))
107 objects.setElementAt(new Res.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
109 else if (c.localName.equals("name"))
110 objects.addElement(new String(content.getBuf(), 0, content.size()));
112 else if (c.localName.equals("value") && "".equals(objects.lastElement()))
113 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
115 else if (c.localName.equals("dateTime.iso8601")) {
116 throw new Error("not implemented");
118 String s = new String(content.getBuf(), 0, content.size());
122 while(Character.isWhitespace(s.charAt(i))) i++;
123 if (i > 0) s = s.substring(i);
126 NativeDate nd = (NativeDate)JS.Thread.enter().newObject(org.xwt.util.JS.Obj.defaultObjects, "Date");
127 double date = NativeDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
128 Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
129 Double.valueOf(s.substring(6, 8)).doubleValue(),
130 Double.valueOf(s.substring(9, 11)).doubleValue(),
131 Double.valueOf(s.substring(12, 14)).doubleValue(),
132 Double.valueOf(s.substring(15, 17)).doubleValue(),
135 nd.jsFunction_setTime(NativeDate.internalUTC(date));
136 objects.setElementAt(nd, objects.size() - 1);
138 } catch (Exception e) {
139 if (Log.on) Log.log(this, "error parsing date : " + s);
140 if (Log.on) Log.log(this, e);
144 } else if (c.localName.equals("member")) {
145 Object memberValue = objects.elementAt(objects.size() - 1);
146 String memberName = (String)objects.elementAt(objects.size() - 2);
147 JS struct = (JS)objects.elementAt(objects.size() - 3);
148 struct.put(memberName, memberValue);
149 objects.setSize(objects.size() - 2);
151 } else if (c.localName.equals("data")) {
153 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
154 JS.Array arr = new JS.Array();
155 for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
156 objects.setElementAt(arr, i);
157 objects.setSize(i + 1);
164 public void characters(char[] ch, int start, int length) {
165 try { content.write(ch, start, length); }
166 catch (Exception e) {
167 if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
168 if (Log.on) Log.log(this, e);
172 public void whitespace(char[] ch, int start, int length) {}
175 // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
177 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
178 void appendObject(Object o, StringBuffer sb) throws JS.Exn {
181 throw new JS.Exn("attempted to send a null value via XML-RPC");
183 } else if (o instanceof Number) {
184 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
185 sb.append(" <value><i4>");
186 sb.append(((Number)o).intValue());
187 sb.append("</i4></value>\n");
189 sb.append(" <value><double>");
191 sb.append("</double></value>\n");
194 } else if (o instanceof Boolean) {
195 sb.append(" <value><boolean>");
196 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
197 sb.append("</boolean></value>\n");
199 } else if (o instanceof Res) {
201 sb.append(" <value><base64>\n");
202 InputStream is = ((Res)o).getInputStream();
203 byte[] buf = new byte[54];
205 int numread = is.read(buf, 0, 54);
206 if (numread == -1) break;
207 byte[] writebuf = buf;
208 if (numread < buf.length) {
209 writebuf = new byte[numread];
210 System.arraycopy(buf, 0, writebuf, 0, numread);
213 sb.append(new String(Base64.encode(writebuf)));
216 sb.append("\n </base64></value>\n");
217 } catch (IOException e) {
218 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
219 if (Log.on) Log.log(this, e);
220 throw new JS.Exn("caught IOException while attempting to send a ByteStream via XML-RPC");
223 } else if (o instanceof String) {
224 sb.append(" <value><string>");
225 String s = (String)o;
226 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
229 char[] cbuf = s.toCharArray();
232 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
233 sb.append(cbuf, oldi, i - oldi);
234 if (i >= cbuf.length) break;
235 if (cbuf[i] == '<') sb.append("<");
236 else if (cbuf[i] == '&') sb.append("&");
238 if (i >= cbuf.length) break;
241 sb.append("</string></value>\n");
244 } else if (o instanceof org.xwt.js.Date) {
245 sb.append(" <value><dateTime.iso8601>");
246 org.xwt.js.Date d = (org.xwt.js.Date)o;
247 Date d = new Date(nd.getRawTime());
248 sb.append(d.getYear() + 1900);
249 if (d.getMonth() + 1 < 10) sb.append('0');
250 sb.append(d.getMonth() + 1);
251 if (d.getDate() < 10) sb.append('0');
252 sb.append(d.getDate());
254 if (d.getHours() < 10) sb.append('0');
255 sb.append(d.getHours());
257 if (d.getMinutes() < 10) sb.append('0');
258 sb.append(d.getMinutes());
260 if (d.getSeconds() < 10) sb.append('0');
261 sb.append(d.getSeconds());
262 sb.append("</dateTime.iso8601></value>\n");
265 } else if (o instanceof JS.Array) {
266 if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
267 tracker.put(o, Boolean.TRUE);
268 sb.append(" <value><array><data>\n");
269 JS.Array a = (JS.Array)o;
270 for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
271 sb.append(" </data></array></value>\n");
273 } else if (o instanceof JS) {
274 if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
275 tracker.put(o, Boolean.TRUE);
277 sb.append(" <value><struct>\n");
278 Object[] ids = j.keys();
279 for(int i=0; i<ids.length; i++) {
280 sb.append(" <member><name>" + ids[i] + "</name>\n");
281 appendObject(j.get(ids[i].toString()), sb);
282 sb.append(" </member>\n");
284 sb.append(" </struct></value>\n");
287 throw new JS.Exn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
292 // this is synchronized in case multiple threads try to make a call on the same object... in the future, change this
293 // behavior to use pipelining.
294 public synchronized Object call2(JS.Array args) throws JS.Exn, IOException {
295 if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
297 if (tracker == null) tracker = new Hash();
298 else tracker.clear();
300 if (objects == null) objects = new Vec();
301 else objects.setSize(0);
303 String content = send(args, http);
306 BufferedReader br2 = new BufferedReader(new StringReader(content));
307 while ((s = br2.readLine()) != null) Log.log(this, "send: " + s);
310 InputStream is = http.POST("text/xml", content);
312 BufferedReader br = !Log.verbose ?
313 new BufferedReader(new InputStreamReader(new Filter(is))) :
314 new BufferedReader(new FilterReader(new InputStreamReader(new Filter(is))) {
315 public int read() throws IOException {
316 int i = super.read();
317 if (Log.on) Log.log(this, "recv: " + ((char)i));
320 public int read(char[] c, int off, int len) throws IOException {
321 int ret = super.read(c, off, len);
322 if (ret == -1) return ret;
324 BufferedReader br2 = new BufferedReader(new StringReader(new String(c, off, ret)));
325 while ((s = br2.readLine()) != null) Log.log(this, "recv: " + s);
335 protected String send(JS.Array args, HTTP http) throws JS.Exn, IOException {
336 StringBuffer content = new StringBuffer();
337 content.append("\r\n");
338 content.append("<?xml version=\"1.0\"?>\n");
339 content.append(" <methodCall>\n");
340 content.append(" <methodName>");
341 content.append(methodname);
342 content.append("</methodName>\n");
343 content.append(" <params>\n");
344 for(int i=0; i<args.length(); i++) {
345 content.append(" <param>\n");
346 appendObject(args.elementAt(i), content);
347 content.append(" </param>\n");
349 content.append(" </params>\n");
350 content.append(" </methodCall>");
351 return content.toString();
354 protected Object recieve(BufferedReader br) throws JS.Exn, IOException {
357 new Helper().parse(br);
358 } catch (XML.XMLException e) {
359 if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
360 throw new JS.Exn("reply from server was not well-formed XML: " + e);
363 if (fault) throw new JS.Exn(objects.elementAt(0));
364 if (objects.size() == 0) return null;
365 return objects.elementAt(0);
368 public final Object call(JS.Array args) throws JS.Exn {
370 if (!ThreadMessage.suspendThread()) return null;
374 } catch (IOException se) {
375 if (Log.on) Log.log(this, se);
376 throw new JS.Exn("socket exception: " + se);
378 } catch (JS.Exn jse) {
379 if (Log.on) Log.log(this, jse.toString());
382 ThreadMessage.resumeThread();
387 /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
388 public Object get(Object name) {
389 return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name.toString(), http);
392 public XMLRPC(String url, String methodname) {
393 this(url, methodname, new HTTP(url));
396 public XMLRPC(String url, String methodname, HTTP http) {
399 this.methodname = methodname;
403 // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
405 /** CharArrayWriter that lets us touch its buffer */
406 protected static class AccessibleCharArrayWriter extends CharArrayWriter {
407 public char[] getBuf() { return buf; }
408 public AccessibleCharArrayWriter(int i) { super(i); }
411 /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
412 private static class Filter extends FilterInputStream {
413 public Filter(InputStream is) { super(is); }
414 public int read() throws IOException {
415 java.lang.Thread.yield();
416 while(Message.Q.nonThreadEventsInQueue > 0) try { java.lang.Thread.sleep(100); } catch (Exception e) { };
419 public int read(byte[] b) throws IOException {
420 java.lang.Thread.yield();
421 while(Message.Q.nonThreadEventsInQueue > 0) try { java.lang.Thread.sleep(100); } catch (Exception e) { };
422 return super.read(b);
424 public int read(byte[] b, int i, int j) throws IOException {
425 java.lang.Thread.yield();
426 while(Message.Q.nonThreadEventsInQueue > 0) try { java.lang.Thread.sleep(100); } catch (Exception e) { };
427 return super.read(b, i, j);