1 // Copyright 2000-2005 the Contributors, as shown in the revision logs.
2 // Licensed under the Apache Public Source License 2.0 ("the License").
3 // You may not use this file except in compliance with the License.
10 import org.ibex.util.*;
11 import org.ibex.crypto.*;
14 * An XML-RPC client implemented as a JavaScript Host Object. See the
15 * Ibex spec for information on its behavior.
17 * NOTE: this client is EXTREMELY lenient in the responses it will
18 * accept; there are many, many invalid responses that it will
19 * successfully parse and return. Do NOT use this to determine the
20 * validity of your server.
22 * This client conforms to <a href="http://www.xmlrpc.com/spec">The
23 * XML-RPC Spec</a>, subject to these limitations:
25 * <li> XMLRPC cannot invoke methods that require a <base64/> argument
26 * <li> if a return value contains a <base64/>, it will be returned as a string
27 * <li> The decision to pass a number as <i4/> or <double/> is based
28 * entirely on whether or not the argument is fractional. Thus, it
29 * is impossible to pass a non-fractional number to an xmlrpc
30 * method that insists on being called with a <double/> element. We
31 * hope that most xml-rpc servers will be able to automatically
35 public class XMLRPC extends JS {
37 public XMLRPC(String url, String method) {
38 this.http = url.startsWith("stdio:") ? HTTP.stdio : new HTTP(url);
42 public XMLRPC(String url, String method, XMLRPC httpSource) {
43 this.http = httpSource.http; this.url = url; this.method = method; }
44 public JS get(JS name) throws JSExn {
45 return new XMLRPC(url, (method.equals("") ? "" : method + ".") + JS.toString(name), this); }
48 /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
49 protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
50 protected String url = null; ///< the url to connect to
51 protected String method = null; ///< the method name to invoke on the remove server
52 protected HTTP http = null; ///< the HTTP connection to use
53 private Hash tracker; ///< used to detect multi-ref data
54 protected boolean fault = false; ///< True iff the return value is a fault (and should be thrown as an exception)
57 /** The object stack. As we process xml elements, pieces of the
58 * return value are pushed onto and popped off of this stack.
60 * The general protocol is that any time a <value> tag is
61 * encountered, an empty String ("") is pushed onto the stack. If
62 * the <value/> node has content (either an anonymous
63 * string or some other XML node), that content replaces the
66 * If an <array> tag is encountered, a null is pushed onto the
67 * stack. When a </data> is encountered, we search back on the
68 * stack to the last null, replace it with a NativeJSArray, and
69 * insert into it all elements above it on the stack.
71 * If a <struct> tag is encountered, a JSect is pushed
72 * onto the stack. If a <name> tag is encountered, its CDATA is
73 * pushed onto the stack. When a </member> is encountered, the
74 * name (second element on stack) and value (top of stack) are
75 * popped off the stack and inserted into the struct (third
78 protected Vec objects = null;
81 // Recieve ////////////////////////////////////////////////////////////////
83 private class Helper extends XML {
84 public Helper() { super(BUFFER_SIZE); }
86 public void startElement(XML.Element c) {
88 //#switch(c.getLocalName())
89 case "fault": fault = true;
90 case "struct": objects.setElementAt(new JS.O(), objects.size() - 1);
91 case "array": objects.setElementAt(null, objects.size() - 1);
92 case "value": objects.addElement("");
96 public void endElement(XML.Element c) {
97 //#switch(c.getLocalName())
98 case "int": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
99 case "i4": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
100 case "boolean": objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
101 case "string": objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
102 case "double": objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
104 objects.setElementAt(new Fountain.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())),
105 null), objects.size() - 1);
106 case "name": objects.addElement(new String(content.getBuf(), 0, content.size()));
107 case "value": if ("".equals(objects.lastElement()))
108 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
109 case "dateTime.iso8601":
110 String s = new String(content.getBuf(), 0, content.size());
114 while(Character.isWhitespace(s.charAt(i))) i++;
115 if (i > 0) s = s.substring(i);
118 JSDate nd = new JSDate();
119 double date = JSDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
120 Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
121 Double.valueOf(s.substring(6, 8)).doubleValue(),
122 Double.valueOf(s.substring(9, 11)).doubleValue(),
123 Double.valueOf(s.substring(12, 14)).doubleValue(),
124 Double.valueOf(s.substring(15, 17)).doubleValue(),
127 nd.setTime(JSDate.internalUTC(date));
128 objects.setElementAt(nd, objects.size() - 1);
130 } catch (Exception e) {
131 throw new RuntimeException("ibex.net.rpc.xml.recieve.malformedDateTag" +
132 "the server sent a <dateTime.iso8601> tag which was malformed: " + s);
135 JS memberValue = (JS)objects.elementAt(objects.size() - 1);
136 JS memberName = (JS)objects.elementAt(objects.size() - 2);
137 JS struct = (JS)objects.elementAt(objects.size() - 3);
139 struct.put(memberName, memberValue);
141 throw new Error("this should never happen");
143 objects.setSize(objects.size() - 2);
146 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
147 JSArray arr = new JSArray();
149 for(int j = i + 1; j<objects.size(); j++) arr.put(JS.N(j - i - 1), (JS)objects.elementAt(j));
151 throw new Error("this should never happen");
153 objects.setElementAt(arr, i);
154 objects.setSize(i + 1);
159 public void characters(char[] ch, int start, int length) {
160 try { content.write(ch, start, length); }
161 catch (Exception e) {
162 if (Log.on) Log.info(this, "Exception in XMLRPC.content() -- this should never happen");
163 if (Log.on) Log.info(this, e);
167 public void whitespace(char[] ch, int start, int length) {}
170 // Send ///////////////////////////////////////////////////////////////////////////
172 protected String buildRequest(JSArray args) throws JSExn, IOException {
173 StringBuffer content = new StringBuffer();
174 content.append("\r\n");
175 content.append("<?xml version=\"1.0\"?>\n");
176 content.append(" <methodCall>\n");
177 content.append(" <methodName>");
178 content.append(method);
179 content.append("</methodName>\n");
180 content.append(" <params>\n");
181 for(int i=0; i<args.length(); i++) {
182 content.append(" <param>\n");
183 appendObject(args.elementAt(i), content);
184 content.append(" </param>\n");
186 content.append(" </params>\n");
187 content.append(" </methodCall>");
188 return content.toString();
191 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
192 void appendObject(Object o, StringBuffer sb) throws JSExn {
195 throw new JSExn("attempted to send a null value via XML-RPC");
197 } else if (o instanceof Number) {
198 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
199 sb.append(" <value><i4>");
200 sb.append(((Number)o).intValue());
201 sb.append("</i4></value>\n");
203 sb.append(" <value><double>");
205 sb.append("</double></value>\n");
208 } else if (o instanceof Boolean) {
209 sb.append(" <value><boolean>");
210 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
211 sb.append("</boolean></value>\n");
213 } else if (o instanceof Fountain) {
215 sb.append(" <value><base64>\n");
216 InputStream is = ((Fountain)o).getInputStream();
217 byte[] buf = new byte[54];
219 int numread = is.read(buf, 0, 54);
220 if (numread == -1) break;
221 byte[] writebuf = buf;
222 if (numread < buf.length) {
223 writebuf = new byte[numread];
224 System.arraycopy(buf, 0, writebuf, 0, numread);
227 sb.append(new String(Base64.encode(writebuf)));
230 sb.append("\n </base64></value>\n");
231 } catch (IOException e) {
232 if (Log.on) Log.info(this, "caught IOException while attempting to send a Fountain via XML-RPC");
233 if (Log.on) Log.info(this, e);
234 throw new JSExn("caught IOException while attempting to send a Fountain via XML-RPC");
237 } else if (o instanceof String) {
238 sb.append(" <value><string>");
239 String s = (String)o;
240 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
243 char[] cbuf = s.toCharArray();
246 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
247 sb.append(cbuf, oldi, i - oldi);
248 if (i >= cbuf.length) break;
249 if (cbuf[i] == '<') sb.append("<");
250 else if (cbuf[i] == '&') sb.append("&");
252 if (i >= cbuf.length) break;
255 sb.append("</string></value>\n");
257 } else if (o instanceof JSDate) {
258 sb.append(" <value><dateTime.iso8601>");
259 java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
260 sb.append(d.getYear() + 1900);
261 if (d.getMonth() + 1 < 10) sb.append('0');
262 sb.append(d.getMonth() + 1);
263 if (d.getDate() < 10) sb.append('0');
264 sb.append(d.getDate());
266 if (d.getHours() < 10) sb.append('0');
267 sb.append(d.getHours());
269 if (d.getMinutes() < 10) sb.append('0');
270 sb.append(d.getMinutes());
272 if (d.getSeconds() < 10) sb.append('0');
273 sb.append(d.getSeconds());
274 sb.append("</dateTime.iso8601></value>\n");
276 } else if (o instanceof JSArray) {
277 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
278 tracker.put(o, JS.B(true));
279 sb.append(" <value><array><data>\n");
280 JSArray a = (JSArray)o;
281 for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
282 sb.append(" </data></array></value>\n");
284 } else if (o instanceof JS) {
285 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
286 tracker.put(o, JS.B(true));
288 sb.append(" <value><struct>\n");
289 Enumeration e = j.keys();
290 while(e.hasMoreElements()) {
291 Object key = e.nextElement();
292 sb.append(" <member><name>" + key + "</name>\n");
293 appendObject(j.get((JS)key), sb);
294 sb.append(" </member>\n");
296 sb.append(" </struct></value>\n");
299 throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
305 // Call Sequence //////////////////////////////////////////////////////////////////////////
307 /* FIXME this has been disabled to make XMLRPC usable without Scheduler
308 public final Object call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
309 JSArray args = new JSArray();
310 for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
314 public final Object call(final JSArray args) throws JSExn {
316 final JS.UnpauseCallback callback = JS.pause();
317 new java.lang.Thread() { public void run() { call(callback, args); } }.start();
318 return null; // doesn't matter since we paused
319 } catch (NotPauseableException npe) {
320 throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
325 // FIXME need to reenable backgrounding logic
326 final Object call(final JS.UnpauseCallback callback, final JSArray args) {
328 if (Log.rpc) Log.info(this, "call to " + url + " : " + method);
329 if (tracker == null) tracker = new Hash();
330 if (objects == null) objects = new Vec();
331 String request = buildRequest(args);
332 if (Log.rpc) Log.info(this, "send:\n" + request);
333 InputStream is = http.POST("text/xml", request, null, null);
334 BufferedReader br = new BufferedReader(new InputStreamReader(is));
336 new Helper().parse(br);
337 if (fault) throw new JSExn((JS)objects.elementAt(0));
338 final JS result = (objects.size() == 0 ? (JS)null : ((JS)objects.elementAt(0)));
339 return (new Task() { public void perform() throws JSExn { callback.unpause(result); }});
344 } catch (final JSExn e) {
345 final Exception e2 = e;
346 return (new Task() { public void perform() throws JSExn { callback.unpause((JSExn)e2); }});
347 } catch (final IOException e) {
348 final Exception e2 = e;
349 return (new Task() { public void perform() throws JSExn { callback.unpause(new JSExn(e2.getMessage())); }});
350 } catch (final XML.Exn e) {
351 final Exception e2 = e;
352 return (new Task() { public void perform() throws JSExn { callback.unpause(new JSExn(e2.getMessage())); }});