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.
9 import org.ibex.util.*;
12 * An XML-RPC client implemented as a JavaScript Host Object. See the
13 * Ibex 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 public class XMLRPC extends JS.Immutable {
35 public XMLRPC(String url, String method) {
36 this.http = url.startsWith("stdio:") ? HTTP.stdio : new HTTP(url);
40 public XMLRPC(String url, String method, XMLRPC httpSource) {
41 this.http = httpSource.http; this.url = url; this.method = method; }
42 public JS get(JS name) throws JSExn {
43 return new XMLRPC(url, (method.equals("") ? "" : method + ".") + JSU.toString(name), this); }
46 /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
47 protected PublicCharArrayWriter content = new PublicCharArrayWriter(100);
48 public static final class PublicCharArrayWriter extends CharArrayWriter {
49 public PublicCharArrayWriter(int i) { super(i); }
52 protected String url = null; ///< the url to connect to
53 protected String method = null; ///< the method name to invoke on the remove server
54 protected HTTP http = null; ///< the HTTP connection to use
55 private Basket.Map tracker; ///< used to detect multi-ref data
56 protected boolean fault = false; ///< True iff the return value is a fault (and should be thrown as an exception)
59 /** The object stack. As we process xml elements, pieces of the
60 * return value are pushed onto and popped off of this stack.
62 * The general protocol is that any time a <value> tag is
63 * encountered, an empty String ("") is pushed onto the stack. If
64 * the <value/> node has content (either an anonymous
65 * string or some other XML node), that content replaces the
68 * If an <array> tag is encountered, a null is pushed onto the
69 * stack. When a </data> is encountered, we search back on the
70 * stack to the last null, replace it with a NativeJSArray, and
71 * insert into it all elements above it on the stack.
73 * If a <struct> tag is encountered, a JSect is pushed
74 * onto the stack. If a <name> tag is encountered, its CDATA is
75 * pushed onto the stack. When a </member> is encountered, the
76 * name (second element on stack) and value (top of stack) are
77 * popped off the stack and inserted into the struct (third
80 protected Basket.Array objects = null;
81 private void setLast(Object o) { objects.set(objects.size() - 1, o); }
84 // Recieve ////////////////////////////////////////////////////////////////
86 private class Helper extends XML {
87 public Helper() { super(BUFFER_SIZE, true); }
89 public void startElement(Tree.Element c) {
91 //#switch(c.getLocalName())
92 case "fault": fault = true;
93 case "struct": setLast(new JS.Obj());
94 case "array": setLast(null);
95 case "value": objects.add("");
99 public void endElement(Tree.Element c) {
100 //#switch(c.getLocalName())
101 case "int": setLast(new Integer(new String(content.buf, 0, content.size())));
102 case "i4": setLast(new Integer(new String(content.buf, 0, content.size())));
103 case "boolean": setLast(content.buf[0] == '1' ? Boolean.TRUE : Boolean.FALSE);
104 case "string": setLast(new String(content.buf, 0, content.size()));
105 case "double": setLast(new Double(new String(content.buf, 0, content.size())));
107 setLast(new Fountain.ByteArray(Encode.fromBase64(new String(content.buf, 0, content.size())),
109 case "name": objects.add(new String(content.buf, 0, content.size()));
110 case "value": if ("".equals(objects.peek()))
111 setLast(new String(content.buf, 0, content.size()));
112 case "dateTime.iso8601":
113 String s = new String(content.buf, 0, content.size());
117 while(Character.isWhitespace(s.charAt(i))) i++;
118 if (i > 0) s = s.substring(i);
121 JSDate nd = new JSDate();
122 double date = JSDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
123 Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
124 Double.valueOf(s.substring(6, 8)).doubleValue(),
125 Double.valueOf(s.substring(9, 11)).doubleValue(),
126 Double.valueOf(s.substring(12, 14)).doubleValue(),
127 Double.valueOf(s.substring(15, 17)).doubleValue(),
130 nd.setTime(JSDate.internalUTC(date));
133 } catch (Exception e) {
134 throw new RuntimeException("ibex.net.rpc.xml.recieve.malformedDateTag" +
135 "the server sent a <dateTime.iso8601> tag which was malformed: " + s);
138 JS memberValue = (JS)objects.get(objects.size() - 1);
139 JS memberName = (JS)objects.get(objects.size() - 2);
140 JS struct = (JS)objects.get(objects.size() - 3);
142 struct.put(memberName, memberValue);
144 throw new Error("this should never happen");
150 for(i=objects.size() - 1; objects.get(i) != null; i--);
151 JSArray arr = new JSArray();
153 for(int j = i + 1; j<objects.size(); j++) arr.put(JSU.N(j - i - 1), (JS)objects.get(j));
155 throw new Error("this should never happen");
163 public void characters(char[] ch, int start, int length) {
164 try { content.write(ch, start, length); }
165 catch (Exception e) {
166 if (Log.on) Log.info(this, "Exception in XMLRPC.content() -- this should never happen");
167 if (Log.on) Log.info(this, e);
171 public void whitespace(char[] ch, int start, int length) {}
174 // Send ///////////////////////////////////////////////////////////////////////////
176 protected String buildRequest(JSArray args) throws JSExn, IOException {
177 StringBuffer content = new StringBuffer();
178 content.append("\r\n");
179 content.append("<?xml version=\"1.0\"?>\n");
180 content.append(" <methodCall>\n");
181 content.append(" <methodName>");
182 content.append(method);
183 content.append("</methodName>\n");
184 content.append(" <params>\n");
185 for(int i=0; i < args.size(); i++) {
186 content.append(" <param>\n");
187 appendObject(args.get(i), content);
188 content.append(" </param>\n");
190 content.append(" </params>\n");
191 content.append(" </methodCall>");
192 return content.toString();
195 /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
196 void appendObject(Object o, StringBuffer sb) throws JSExn {
199 throw new JSExn("attempted to send a null value via XML-RPC");
201 } else if (o instanceof Number) {
202 if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
203 sb.append(" <value><i4>");
204 sb.append(((Number)o).intValue());
205 sb.append("</i4></value>\n");
207 sb.append(" <value><double>");
209 sb.append("</double></value>\n");
212 } else if (o instanceof Boolean) {
213 sb.append(" <value><boolean>");
214 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
215 sb.append("</boolean></value>\n");
217 } else if (o instanceof Fountain) {
219 sb.append(" <value><base64>\n");
220 InputStream is = ((Fountain)o).getInputStream();
221 byte[] buf = new byte[54];
223 int numread = is.read(buf, 0, 54);
224 if (numread == -1) break;
225 byte[] writebuf = buf;
226 if (numread < buf.length) {
227 writebuf = new byte[numread];
228 System.arraycopy(buf, 0, writebuf, 0, numread);
231 sb.append(new String(Encode.toBase64(writebuf)));
234 sb.append("\n </base64></value>\n");
235 } catch (IOException e) {
236 if (Log.on) Log.info(this, "caught IOException while attempting to send a Fountain via XML-RPC");
237 if (Log.on) Log.info(this, e);
238 throw new JSExn("caught IOException while attempting to send a Fountain via XML-RPC");
241 } else if (o instanceof String) {
242 sb.append(" <value><string>");
243 String s = (String)o;
244 if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
247 char[] cbuf = s.toCharArray();
250 while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
251 sb.append(cbuf, oldi, i - oldi);
252 if (i >= cbuf.length) break;
253 if (cbuf[i] == '<') sb.append("<");
254 else if (cbuf[i] == '&') sb.append("&");
256 if (i >= cbuf.length) break;
259 sb.append("</string></value>\n");
261 } else if (o instanceof JSDate) {
262 sb.append(" <value><dateTime.iso8601>");
263 java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
264 sb.append(d.getYear() + 1900);
265 if (d.getMonth() + 1 < 10) sb.append('0');
266 sb.append(d.getMonth() + 1);
267 if (d.getDate() < 10) sb.append('0');
268 sb.append(d.getDate());
270 if (d.getHours() < 10) sb.append('0');
271 sb.append(d.getHours());
273 if (d.getMinutes() < 10) sb.append('0');
274 sb.append(d.getMinutes());
276 if (d.getSeconds() < 10) sb.append('0');
277 sb.append(d.getSeconds());
278 sb.append("</dateTime.iso8601></value>\n");
280 } else if (o instanceof JSArray) {
281 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
282 tracker.put(o, JSU.B(true));
283 sb.append(" <value><array><data>\n");
284 JSArray a = (JSArray)o;
285 for(int i=0; i < a.size(); i++) appendObject(a.get(i), sb);
286 sb.append(" </data></array></value>\n");
288 } else if (o instanceof JS) {
289 if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
290 tracker.put(o, JSU.B(true));
292 sb.append(" <value><struct>\n");
293 Enumeration e = j.keys();
294 while (e.hasNext()) {
295 Object key = e.next();
296 sb.append(" <member><name>" + key + "</name>\n");
297 appendObject(j.get((JS)key), sb);
298 sb.append(" </member>\n");
300 sb.append(" </struct></value>\n");
303 throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
309 // Call Sequence //////////////////////////////////////////////////////////////////////////
311 /* FIXME this has been disabled to make XMLRPC usable without Scheduler
312 public final Object call(JS a0, JS a1, JS a2, JS[] rest, int nargs) throws JSExn {
313 JSArray args = new JSArray();
314 for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
318 public final Object call(final JSArray args) throws JSExn {
320 final JS.UnpauseCallback callback = JS.pause();
321 new java.lang.Thread() { public void run() { call(callback, args); } }.start();
322 return null; // doesn't matter since we paused
323 } catch (NotPauseableException npe) {
324 throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
329 // FIXME need to reenable backgrounding logic
330 final Object call(final Pausable callback, final JSArray args) {
332 if (Log.rpc) Log.info(this, "call to " + url + " : " + method);
333 if (tracker == null) tracker = new Basket.HashMap();
334 if (objects == null) objects = new Basket.Array();
335 String request = buildRequest(args);
336 if (Log.rpc) Log.info(this, "send:\n" + request);
337 InputStream is = http.POST("text/xml", request, null, null);
338 BufferedReader br = new BufferedReader(new InputStreamReader(is));
340 new Helper().parse(br);
341 if (fault) throw new JSExn((JS)objects.get(0));
342 final JS result = (objects.size() == 0 ? (JS)null : ((JS)objects.get(0)));
343 return (new Callable() { public Object run(Object o) throws Exception {
344 return callback.run(result); }});
349 } catch (final JSExn e) {
350 return (new Callable() { public Object run(Object o) throws Exception {
351 return callback.run(e); }});
352 } catch (final IOException e) {
353 final String msg = e.getMessage();
354 return (new Callable() { public Object run(Object o) throws Exception {
355 return callback.run(new JSExn(msg)); }});