1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
7 import org.ibex.util.*;
8 import org.bouncycastle.util.encoders.Base64;
11 * An XML-RPC client implemented as a JavaScript Host Object. See the
12 * Ibex spec for information on its behavior.
14 * NOTE: this client is EXTREMELY lenient in the responses it will
15 * accept; there are many, many invalid responses that it will
16 * successfully parse and return. Do NOT use this to determine the
17 * validity of your server.
19 * This client conforms to <a href="http://www.xmlrpc.com/spec">The
20 * XML-RPC Spec</a>, subject to these limitations:
22 * <li> XMLRPC cannot invoke methods that require a <base64/> argument
23 * <li> if a return value contains a <base64/>, it will be returned as a string
24 * <li> The decision to pass a number as <i4/> or <double/> is based
25 * entirely on whether or not the argument is fractional. Thus, it
26 * is impossible to pass a non-fractional number to an xmlrpc
27 * method that insists on being called with a <double/> element. We
28 * hope that most xml-rpc servers will be able to automatically
32 class XMLRPC extends JS {
34 public XMLRPC(String url, String method) {
35 this.http = url.startsWith("stdio:") ? HTTP.stdio : new HTTP(url);
39 public XMLRPC(String url, String method, XMLRPC httpSource) {
40 this.http = httpSource.http; this.url = url; this.method = method; }
41 public Object get(Object name) {
42 return new XMLRPC(url, (method.equals("") ? "" : method + ".") + name.toString(), this); }
45 /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
46 protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
47 protected String url = null; ///< the url to connect to
48 protected String method = null; ///< the method name to invoke on the remove server
49 protected HTTP http = null; ///< the HTTP connection to use
50 private Hash tracker; ///< used to detect multi-ref data
51 protected boolean fault = false; ///< True iff the return value is a fault (and should be thrown as an exception)
54 /** The object stack. As we process xml elements, pieces of the
55 * return value are pushed onto and popped off of this stack.
57 * The general protocol is that any time a <value> tag is
58 * encountered, an empty String ("") is pushed onto the stack. If
59 * the <value/> node has content (either an anonymous
60 * string or some other XML node), that content replaces the
63 * If an <array> tag is encountered, a null is pushed onto the
64 * stack. When a </data> is encountered, we search back on the
65 * stack to the last null, replace it with a NativeJSArray, and
66 * insert into it all elements above it on the stack.
68 * If a <struct> tag is encountered, a JSect is pushed
69 * onto the stack. If a <name> tag is encountered, its CDATA is
70 * pushed onto the stack. When a </member> is encountered, the
71 * name (second element on stack) and value (top of stack) are
72 * popped off the stack and inserted into the struct (third
75 protected Vec objects = null;
78 // Recieve ////////////////////////////////////////////////////////////////
80 private class Helper extends XML {
81 public Helper() { super(BUFFER_SIZE); }
83 public void startElement(XML.Element c) {
85 //#switch(c.getLocalName())
86 case "fault": fault = true;
87 case "struct": objects.setElementAt(new JS(), objects.size() - 1);
88 case "array": objects.setElementAt(null, objects.size() - 1);
89 case "value": objects.addElement("");
93 public void endElement(XML.Element c) {
94 //#switch(c.getLocalName())
95 case "int": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
96 case "i4": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
97 case "boolean": objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
98 case "string": objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
99 case "double": objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
101 objects.setElementAt(new Stream.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())),
102 null), objects.size() - 1);
103 case "name": objects.addElement(new String(content.getBuf(), 0, content.size()));
104 case "value": if ("".equals(objects.lastElement()))
105 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
106 case "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 JSDate nd = new JSDate();
116 double date = JSDate.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.setTime(JSDate.internalUTC(date));
125 objects.setElementAt(nd, objects.size() - 1);
127 } catch (Exception e) {
128 throw new RuntimeException("ibex.net.rpc.xml.recieve.malformedDateTag" +
129 "the server sent a <dateTime.iso8601> tag which was malformed: " + s);
132 Object memberValue = objects.elementAt(objects.size() - 1);
133 String memberName = (String)objects.elementAt(objects.size() - 2);
134 JS struct = (JS)objects.elementAt(objects.size() - 3);
136 struct.put(memberName, memberValue);
138 throw new Error("this should never happen");
140 objects.setSize(objects.size() - 2);
143 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
144 JSArray arr = new JSArray();
146 for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
148 throw new Error("this should never happen");
150 objects.setElementAt(arr, i);
151 objects.setSize(i + 1);
156 public void characters(char[] ch, int start, int length) {
157 try { content.write(ch, start, length); }
158 catch (Exception e) {
159 if (Log.on) Log.info(this, "Exception in XMLRPC.content() -- this should never happen");
160 if (Log.on) Log.info(this, e);
164 public void whitespace(char[] ch, int start, int length) {}
167 // Send ///////////////////////////////////////////////////////////////////////////
169 protected String buildRequest(JSArray args) throws JSExn, IOException {
170 StringBuffer content = new StringBuffer();
171 content.append("\r\n");
172 content.append("<?xml version=\"1.0\"?>\n");
173 content.append(" <methodCall>\n");
174 content.append(" <methodName>");
175 content.append(method);
176 content.append("</methodName>\n");
177 content.append(" <params>\n");
178 for(int i=0; i<args.length(); i++) {
179 content.append(" <param>\n");
180 appendObject(args.elementAt(i), content);
181 content.append(" </param>\n");
183 content.append(" </params>\n");
184 content.append(" </methodCall>");
185 return content.toString();
188 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
189 void appendObject(Object o, StringBuffer sb) throws JSExn {
192 throw new JSExn("attempted to send a null value via XML-RPC");
194 } else if (o instanceof Number) {
195 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
196 sb.append(" <value><i4>");
197 sb.append(((Number)o).intValue());
198 sb.append("</i4></value>\n");
200 sb.append(" <value><double>");
202 sb.append("</double></value>\n");
205 } else if (o instanceof Boolean) {
206 sb.append(" <value><boolean>");
207 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
208 sb.append("</boolean></value>\n");
210 } else if (o instanceof Stream) {
212 sb.append(" <value><base64>\n");
213 InputStream is = ((Stream)o).getInputStream();
214 byte[] buf = new byte[54];
216 int numread = is.read(buf, 0, 54);
217 if (numread == -1) break;
218 byte[] writebuf = buf;
219 if (numread < buf.length) {
220 writebuf = new byte[numread];
221 System.arraycopy(buf, 0, writebuf, 0, numread);
224 sb.append(new String(Base64.encode(writebuf)));
227 sb.append("\n </base64></value>\n");
228 } catch (IOException e) {
229 if (Log.on) Log.info(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
230 if (Log.on) Log.info(this, e);
231 throw new JSExn("caught IOException while attempting to send a ByteStream via XML-RPC");
234 } else if (o instanceof String) {
235 sb.append(" <value><string>");
236 String s = (String)o;
237 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
240 char[] cbuf = s.toCharArray();
243 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
244 sb.append(cbuf, oldi, i - oldi);
245 if (i >= cbuf.length) break;
246 if (cbuf[i] == '<') sb.append("<");
247 else if (cbuf[i] == '&') sb.append("&");
249 if (i >= cbuf.length) break;
252 sb.append("</string></value>\n");
254 } else if (o instanceof JSDate) {
255 sb.append(" <value><dateTime.iso8601>");
256 java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
257 sb.append(d.getYear() + 1900);
258 if (d.getMonth() + 1 < 10) sb.append('0');
259 sb.append(d.getMonth() + 1);
260 if (d.getDate() < 10) sb.append('0');
261 sb.append(d.getDate());
263 if (d.getHours() < 10) sb.append('0');
264 sb.append(d.getHours());
266 if (d.getMinutes() < 10) sb.append('0');
267 sb.append(d.getMinutes());
269 if (d.getSeconds() < 10) sb.append('0');
270 sb.append(d.getSeconds());
271 sb.append("</dateTime.iso8601></value>\n");
273 } else if (o instanceof JSArray) {
274 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
275 tracker.put(o, Boolean.TRUE);
276 sb.append(" <value><array><data>\n");
277 JSArray a = (JSArray)o;
278 for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
279 sb.append(" </data></array></value>\n");
281 } else if (o instanceof JS) {
282 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
283 tracker.put(o, Boolean.TRUE);
285 sb.append(" <value><struct>\n");
286 Enumeration e = j.keys();
287 while(e.hasMoreElements()) {
288 Object key = e.nextElement();
289 sb.append(" <member><name>" + key + "</name>\n");
290 appendObject(j.get(key), sb);
291 sb.append(" </member>\n");
293 sb.append(" </struct></value>\n");
296 throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
302 // Call Sequence //////////////////////////////////////////////////////////////////////////
304 public final Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
305 JSArray args = new JSArray();
306 for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
310 public final Object call(final JSArray args) throws JSExn {
312 final JS.UnpauseCallback callback = JS.pause();
313 new java.lang.Thread() { public void run() { call(callback, args); } }.start();
314 return null; // doesn't matter since we paused
315 } catch (NotPauseableException npe) {
316 throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
320 final void call(final JS.UnpauseCallback callback, final JSArray args) {
322 if (Log.rpc) Log.info(this, "call to " + url + " : " + method);
323 if (tracker == null) tracker = new Hash();
324 if (objects == null) objects = new Vec();
325 String request = buildRequest(args);
326 if (Log.rpc) Log.info(this, "send:\n" + request);
327 InputStream is = http.POST("text/xml", request);
328 BufferedReader br = new BufferedReader(new InputStreamReader(is));
330 new Helper().parse(br);
331 final Object result = fault ? new JSExn(objects.elementAt(0)) : objects.size() == 0 ? null : objects.elementAt(0);
332 Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn { callback.unpause(result); }});
337 } catch (final JSExn e) {
338 final Exception e2 = e;
339 Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn { callback.unpause(e2); }});
340 } catch (final IOException e) {
341 final Exception e2 = e;
342 Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn { callback.unpause(new JSExn(e2)); }});
343 } catch (final XML.Exn e) {
344 final Exception e2 = e;
345 Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn { callback.unpause(new JSExn(e2)); }});