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) { this(url, method, new HTTP(url)); }
35 public XMLRPC(String url, String method, HTTP http) { this.http = http; this.url = url; this.method = method; }
36 public Object get(Object name) { return new XMLRPC(url, (method.equals("") ? "" : method + ".") + name.toString(), http); }
39 /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
40 protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
41 protected String url = null; ///< the url to connect to
42 protected String method = null; ///< the method name to invoke on the remove server
43 protected HTTP http = null; ///< the HTTP connection to use
44 private Hash tracker; ///< used to detect multi-ref data
45 protected boolean fault = false; ///< True iff the return value is a fault (and should be thrown as an exception)
48 /** The object stack. As we process xml elements, pieces of the
49 * return value are pushed onto and popped off of this stack.
51 * The general protocol is that any time a <value> tag is
52 * encountered, an empty String ("") is pushed onto the stack. If
53 * the <value/> node has content (either an anonymous
54 * string or some other XML node), that content replaces the
57 * If an <array> tag is encountered, a null is pushed onto the
58 * stack. When a </data> is encountered, we search back on the
59 * stack to the last null, replace it with a NativeJSArray, and
60 * insert into it all elements above it on the stack.
62 * If a <struct> tag is encountered, a JSect is pushed
63 * onto the stack. If a <name> tag is encountered, its CDATA is
64 * pushed onto the stack. When a </member> is encountered, the
65 * name (second element on stack) and value (top of stack) are
66 * popped off the stack and inserted into the struct (third
69 protected Vec objects = null;
72 // Recieve ////////////////////////////////////////////////////////////////
74 private class Helper extends XML {
75 public Helper() { super(BUFFER_SIZE); }
77 public void startElement(XML.Element c) {
79 //#switch(c.getLocalName())
80 case "fault": fault = true;
81 case "struct": objects.setElementAt(new JS(), objects.size() - 1);
82 case "array": objects.setElementAt(null, objects.size() - 1);
83 case "value": objects.addElement("");
87 public void endElement(XML.Element c) {
88 //#switch(c.getLocalName())
89 case "int": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
90 case "i4": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
91 case "boolean": objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
92 case "string": objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
93 case "double": objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
95 objects.setElementAt(new Stream.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())),
96 null), objects.size() - 1);
97 case "name": objects.addElement(new String(content.getBuf(), 0, content.size()));
98 case "value": if ("".equals(objects.lastElement()))
99 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
100 case "dateTime.iso8601":
101 String s = new String(content.getBuf(), 0, content.size());
105 while(Character.isWhitespace(s.charAt(i))) i++;
106 if (i > 0) s = s.substring(i);
109 JSDate nd = new JSDate();
110 double date = JSDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
111 Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
112 Double.valueOf(s.substring(6, 8)).doubleValue(),
113 Double.valueOf(s.substring(9, 11)).doubleValue(),
114 Double.valueOf(s.substring(12, 14)).doubleValue(),
115 Double.valueOf(s.substring(15, 17)).doubleValue(),
118 nd.setTime(JSDate.internalUTC(date));
119 objects.setElementAt(nd, objects.size() - 1);
121 } catch (Exception e) {
122 throw new RuntimeException("ibex.net.rpc.xml.recieve.malformedDateTag" +
123 "the server sent a <dateTime.iso8601> tag which was malformed: " + s);
126 Object memberValue = objects.elementAt(objects.size() - 1);
127 String memberName = (String)objects.elementAt(objects.size() - 2);
128 JS struct = (JS)objects.elementAt(objects.size() - 3);
130 struct.put(memberName, memberValue);
132 throw new Error("this should never happen");
134 objects.setSize(objects.size() - 2);
137 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
138 JSArray arr = new JSArray();
140 for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
142 throw new Error("this should never happen");
144 objects.setElementAt(arr, i);
145 objects.setSize(i + 1);
150 public void characters(char[] ch, int start, int length) {
151 try { content.write(ch, start, length); }
152 catch (Exception e) {
153 if (Log.on) Log.info(this, "Exception in XMLRPC.content() -- this should never happen");
154 if (Log.on) Log.info(this, e);
158 public void whitespace(char[] ch, int start, int length) {}
161 // Send ///////////////////////////////////////////////////////////////////////////
163 protected String buildRequest(JSArray args) throws JSExn, IOException {
164 StringBuffer content = new StringBuffer();
165 content.append("\r\n");
166 content.append("<?xml version=\"1.0\"?>\n");
167 content.append(" <methodCall>\n");
168 content.append(" <method>");
169 content.append(method);
170 content.append("</method>\n");
171 content.append(" <params>\n");
172 for(int i=0; i<args.length(); i++) {
173 content.append(" <param>\n");
174 appendObject(args.elementAt(i), content);
175 content.append(" </param>\n");
177 content.append(" </params>\n");
178 content.append(" </methodCall>");
179 return content.toString();
182 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
183 void appendObject(Object o, StringBuffer sb) throws JSExn {
186 throw new JSExn("attempted to send a null value via XML-RPC");
188 } else if (o instanceof Number) {
189 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
190 sb.append(" <value><i4>");
191 sb.append(((Number)o).intValue());
192 sb.append("</i4></value>\n");
194 sb.append(" <value><double>");
196 sb.append("</double></value>\n");
199 } else if (o instanceof Boolean) {
200 sb.append(" <value><boolean>");
201 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
202 sb.append("</boolean></value>\n");
204 } else if (o instanceof Stream) {
206 sb.append(" <value><base64>\n");
207 InputStream is = ((Stream)o).getInputStream();
208 byte[] buf = new byte[54];
210 int numread = is.read(buf, 0, 54);
211 if (numread == -1) break;
212 byte[] writebuf = buf;
213 if (numread < buf.length) {
214 writebuf = new byte[numread];
215 System.arraycopy(buf, 0, writebuf, 0, numread);
218 sb.append(new String(Base64.encode(writebuf)));
221 sb.append("\n </base64></value>\n");
222 } catch (IOException e) {
223 if (Log.on) Log.info(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
224 if (Log.on) Log.info(this, e);
225 throw new JSExn("caught IOException while attempting to send a ByteStream via XML-RPC");
228 } else if (o instanceof String) {
229 sb.append(" <value><string>");
230 String s = (String)o;
231 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
234 char[] cbuf = s.toCharArray();
237 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
238 sb.append(cbuf, oldi, i - oldi);
239 if (i >= cbuf.length) break;
240 if (cbuf[i] == '<') sb.append("<");
241 else if (cbuf[i] == '&') sb.append("&");
243 if (i >= cbuf.length) break;
246 sb.append("</string></value>\n");
248 } else if (o instanceof JSDate) {
249 sb.append(" <value><dateTime.iso8601>");
250 java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
251 sb.append(d.getYear() + 1900);
252 if (d.getMonth() + 1 < 10) sb.append('0');
253 sb.append(d.getMonth() + 1);
254 if (d.getDate() < 10) sb.append('0');
255 sb.append(d.getDate());
257 if (d.getHours() < 10) sb.append('0');
258 sb.append(d.getHours());
260 if (d.getMinutes() < 10) sb.append('0');
261 sb.append(d.getMinutes());
263 if (d.getSeconds() < 10) sb.append('0');
264 sb.append(d.getSeconds());
265 sb.append("</dateTime.iso8601></value>\n");
267 } else if (o instanceof JSArray) {
268 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
269 tracker.put(o, Boolean.TRUE);
270 sb.append(" <value><array><data>\n");
271 JSArray a = (JSArray)o;
272 for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
273 sb.append(" </data></array></value>\n");
275 } else if (o instanceof JS) {
276 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
277 tracker.put(o, Boolean.TRUE);
279 sb.append(" <value><struct>\n");
280 Enumeration e = j.keys();
281 while(e.hasMoreElements()) {
282 Object key = e.nextElement();
283 sb.append(" <member><name>" + key + "</name>\n");
284 appendObject(j.get(key), sb);
285 sb.append(" </member>\n");
287 sb.append(" </struct></value>\n");
290 throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
296 // Call Sequence //////////////////////////////////////////////////////////////////////////
298 public final Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
299 JSArray args = new JSArray();
300 for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
304 public final Object call(final JSArray args) throws JSExn {
306 final JS.UnpauseCallback callback = JS.pause();
307 new java.lang.Thread() { public void run() { call(callback, args); } }.start();
308 return null; // doesn't matter since we paused
309 } catch (NotPauseableException npe) {
310 throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
314 final void call(final JS.UnpauseCallback callback, final JSArray args) {
316 if (Log.verbose) Log.info(this, "call to " + url + " : " + method);
317 if (tracker == null) tracker = new Hash();
318 if (objects == null) objects = new Vec();
319 String request = buildRequest(args);
320 if (Log.verbose) Log.info(this, "send:\n" + request);
321 InputStream is = http.POST("text/xml", request);
322 BufferedReader br = new BufferedReader(new InputStreamReader(is));
324 new Helper().parse(br);
325 final Object result = fault ? new JSExn(objects.elementAt(0)) : objects.size() == 0 ? null : objects.elementAt(0);
326 Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn { callback.unpause(result); }});
331 } catch (final JSExn e) {
332 final Exception e2 = e;
333 Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn { callback.unpause(e2); }});
334 } catch (final IOException e) {
335 final Exception e2 = e;
336 Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn { callback.unpause(new JSExn(e2)); }});
337 } catch (final XML.Exn e) {
338 final Exception e2 = e;
339 Scheduler.add(new Scheduler.Task() { public void perform() throws JSExn { callback.unpause(new JSExn(e2)); }});