1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
7 import org.ibex.util.*;
8 import org.ibex.crypto.*;
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 public 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.O(), 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(JS.N(Integer.parseInt(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
96 case "i4": objects.setElementAt(JS.N(Integer.parseInt(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
97 case "boolean": objects.setElementAt(content.getBuf()[0] == '1' ? JS.T : JS.F, objects.size() - 1);
98 case "string": objects.setElementAt(JS.S(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
99 case "double": objects.setElementAt(JS.N(Double.parseDouble(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(JS.S(new String(content.getBuf(), 0, content.size())));
104 case "value": if ("".equals(objects.lastElement()))
105 objects.setElementAt(JS.S(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 JS memberValue = (JS) 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(JS.S(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(JS.N(j - i - 1), (JS)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(JS o, StringBuffer sb) throws JSExn {
190 // FIXME: Update for new api
191 throw new Error("FIXME");
193 throw new JSExn("attempted to send a null value via XML-RPC");
195 } else if (o instanceof Number) {
196 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
197 sb.append(" <value><i4>");
198 sb.append(((Number)o).intValue());
199 sb.append("</i4></value>\n");
201 sb.append(" <value><double>");
203 sb.append("</double></value>\n");
206 } else if (o instanceof Boolean) {
207 sb.append(" <value><boolean>");
208 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
209 sb.append("</boolean></value>\n");
211 } else if (o instanceof Stream) {
213 sb.append(" <value><base64>\n");
214 InputStream is = ((Stream)o).getInputStream();
215 byte[] buf = new byte[54];
217 int numread = is.read(buf, 0, 54);
218 if (numread == -1) break;
219 byte[] writebuf = buf;
220 if (numread < buf.length) {
221 writebuf = new byte[numread];
222 System.arraycopy(buf, 0, writebuf, 0, numread);
225 sb.append(new String(Base64.encode(writebuf)));
228 sb.append("\n </base64></value>\n");
229 } catch (IOException e) {
230 if (Log.on) Log.info(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
231 if (Log.on) Log.info(this, e);
232 throw new JSExn("caught IOException while attempting to send a ByteStream via XML-RPC");
235 } else if (o instanceof String) {
236 sb.append(" <value><string>");
237 String s = (String)o;
238 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
241 char[] cbuf = s.toCharArray();
244 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
245 sb.append(cbuf, oldi, i - oldi);
246 if (i >= cbuf.length) break;
247 if (cbuf[i] == '<') sb.append("<");
248 else if (cbuf[i] == '&') sb.append("&");
250 if (i >= cbuf.length) break;
253 sb.append("</string></value>\n");
255 } else if (o instanceof JSDate) {
256 sb.append(" <value><dateTime.iso8601>");
257 java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
258 sb.append(d.getYear() + 1900);
259 if (d.getMonth() + 1 < 10) sb.append('0');
260 sb.append(d.getMonth() + 1);
261 if (d.getDate() < 10) sb.append('0');
262 sb.append(d.getDate());
264 if (d.getHours() < 10) sb.append('0');
265 sb.append(d.getHours());
267 if (d.getMinutes() < 10) sb.append('0');
268 sb.append(d.getMinutes());
270 if (d.getSeconds() < 10) sb.append('0');
271 sb.append(d.getSeconds());
272 sb.append("</dateTime.iso8601></value>\n");
274 } else if (o instanceof JSArray) {
275 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
276 tracker.put(o, Boolean.TRUE);
277 sb.append(" <value><array><data>\n");
278 JSArray a = (JSArray)o;
279 for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
280 sb.append(" </data></array></value>\n");
282 } else if (o instanceof JS) {
283 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
284 tracker.put(o, Boolean.TRUE);
286 sb.append(" <value><struct>\n");
287 Enumeration e = j.keys();
288 while(e.hasMoreElements()) {
289 Object key = e.nextElement();
290 sb.append(" <member><name>" + key + "</name>\n");
291 appendObject(j.get(key), sb);
292 sb.append(" </member>\n");
294 sb.append(" </struct></value>\n");
297 throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
303 // Call Sequence //////////////////////////////////////////////////////////////////////////
305 public final JS call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
306 JSArray args = new JSArray();
307 for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
311 public final JS call(final JSArray args) throws JSExn {
313 final JS.UnpauseCallback callback = JS.pause();
314 new java.lang.Thread() { public void run() { call(callback, args); } }.start();
315 return null; // doesn't matter since we paused
316 } catch (NotPauseableException npe) {
317 throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
321 final void call(final JS.UnpauseCallback callback, final JSArray args) {
323 if (Log.rpc) Log.info(this, "call to " + url + " : " + method);
324 if (tracker == null) tracker = new Hash();
325 if (objects == null) objects = new Vec();
326 String request = buildRequest(args);
327 if (Log.rpc) Log.info(this, "send:\n" + request);
328 InputStream is = http.POST("text/xml", request);
329 BufferedReader br = new BufferedReader(new InputStreamReader(is));
331 new Helper().parse(br);
332 final JSExn exn = fault ? new JSExn(objects.elementAt(0).toString()) : null;
333 final JS result = fault ? null : objects.size() == 0 ? null : (JS) objects.elementAt(0);
334 Scheduler.add(new Task() { public void perform() throws JSExn { if(fault) callback.unpause(exn); else callback.unpause(result); }});
339 } catch (final JSExn e) {
340 Scheduler.add(new Task() { public void perform() throws JSExn { callback.unpause(e); }});
341 } catch (final IOException e) {
342 final Exception e2 = e;
343 Scheduler.add(new Task() { public void perform() throws JSExn { callback.unpause(new JSExn(e2.toString())); }});
344 } catch (final XML.Exn e) {
345 final Exception e2 = e;
346 Scheduler.add(new Task() { public void perform() throws JSExn { callback.unpause(new JSExn(e2.toString())); }});