licensing update to APSL 2.0
[org.ibex.js.git] / src / org / ibex / js / XMLRPC.java
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.
4
5 package org.ibex.js;
6
7 import java.io.*;
8 import java.util.*;
9 import org.ibex.net.*;
10 import org.ibex.util.*;
11 import org.ibex.crypto.*;
12
13 /**
14  *  An XML-RPC client implemented as a JavaScript Host Object. See the
15  *  Ibex spec for information on its behavior.
16  *
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.
21  *
22  *  This client conforms to <a href="http://www.xmlrpc.com/spec">The
23  *  XML-RPC Spec</a>, subject to these limitations:
24  *  <ol>
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
32  *         convert.
33  *  </ol>
34  */
35 public class XMLRPC extends JS {
36
37     public XMLRPC(String url, String method) {
38         this.http = url.startsWith("stdio:") ? HTTP.stdio : new HTTP(url);
39         this.url = url;
40         this.method = method;
41     }
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); }
46
47
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)
55
56
57     /** The object stack. As we process xml elements, pieces of the
58      *  return value are pushed onto and popped off of this stack.
59      *
60      *  The general protocol is that any time a &lt;value&gt; tag is
61      *  encountered, an empty String ("") is pushed onto the stack. If
62      *  the &lt;value/&gt; node has content (either an anonymous
63      *  string or some other XML node), that content replaces the
64      *  empty string.
65      *
66      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
67      *  stack. When a &lt;/data&gt; 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.
70      *
71      *  If a &lt;struct&gt; tag is encountered, a JSect is pushed
72      *  onto the stack. If a &lt;name&gt; tag is encountered, its CDATA is
73      *  pushed onto the stack. When a &lt;/member&gt; 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
76      *  element on stack).
77      */
78     protected Vec objects = null;
79
80
81     // Recieve ////////////////////////////////////////////////////////////////
82
83     private class Helper extends XML {
84         public Helper() { super(BUFFER_SIZE); }
85
86         public void startElement(XML.Element c) {
87             content.reset();
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("");
93             //#end
94         }
95         
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);
103             case "base64":
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());
111                 
112                 // strip whitespace
113                 int i=0;
114                 while(Character.isWhitespace(s.charAt(i))) i++;
115                 if (i > 0) s = s.substring(i);
116                 
117                 try {
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(),
125                                                            (double)0
126                                                            );
127                     nd.setTime(JSDate.internalUTC(date));
128                     objects.setElementAt(nd, objects.size() - 1);
129                     
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);
133                 }
134             case "member":
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);
138                 try {
139                     struct.put(memberName, memberValue);
140                 } catch (JSExn e) {
141                     throw new Error("this should never happen");
142                 }
143                 objects.setSize(objects.size() - 2);
144             case "data":
145                 int i;
146                 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
147                 JSArray arr = new JSArray();
148                 try {
149                     for(int j = i + 1; j<objects.size(); j++) arr.put(JS.N(j - i - 1), (JS)objects.elementAt(j));
150                 } catch (JSExn e) {
151                     throw new Error("this should never happen");
152                 }
153                 objects.setElementAt(arr, i);
154                 objects.setSize(i + 1);
155             //#end            
156             content.reset();
157         }
158         
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);
164             }
165         }
166         
167         public void whitespace(char[] ch, int start, int length) {}
168     }
169
170     // Send ///////////////////////////////////////////////////////////////////////////
171
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");
185         }
186         content.append("        </params>\n");
187         content.append("    </methodCall>");
188         return content.toString();
189     }
190
191     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
192     void appendObject(Object o, StringBuffer sb) throws JSExn {
193
194         if (o == null) {
195             throw new JSExn("attempted to send a null value via XML-RPC");
196
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");
202             } else {
203                 sb.append("                <value><double>");
204                 sb.append(o);
205                 sb.append("</double></value>\n");
206             }
207
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");
212
213         } else if (o instanceof Fountain) {
214             try {
215                 sb.append("                <value><base64>\n");
216                 InputStream is = ((Fountain)o).getInputStream();
217                 byte[] buf = new byte[54];
218                 while(true) {
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);
225                     }
226                     sb.append("              ");
227                     sb.append(new String(Base64.encode(writebuf)));
228                     sb.append("\n");
229                 }
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");
235             }
236
237         } else if (o instanceof String) {
238             sb.append("                <value><string>");
239             String s = (String)o;
240             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
241                 sb.append(s);
242             } else {
243                 char[] cbuf = s.toCharArray();
244                 int oldi = 0, i=0;
245                 while(true) {
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("&lt;");
250                     else if (cbuf[i] == '&') sb.append("&amp;");
251                     i = oldi = i + 1;
252                     if (i >= cbuf.length) break;
253                 }
254             }
255             sb.append("</string></value>\n");
256
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());
265             sb.append('T');
266             if (d.getHours() < 10) sb.append('0');
267             sb.append(d.getHours());
268             sb.append(':');
269             if (d.getMinutes() < 10) sb.append('0');
270             sb.append(d.getMinutes());
271             sb.append(':');
272             if (d.getSeconds() < 10) sb.append('0');
273             sb.append(d.getSeconds());
274             sb.append("</dateTime.iso8601></value>\n");
275
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");
283
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));
287             JS j = (JS)o;
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");
295             }
296             sb.append("                </struct></value>\n");
297
298         } else {
299             throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
300
301         }
302     }
303
304
305     // Call Sequence //////////////////////////////////////////////////////////////////////////
306
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]);
311         return call(args);
312     }
313
314     public final Object call(final JSArray args) throws JSExn {
315         try {
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");
321         }
322     }
323     */
324
325     // FIXME need to reenable backgrounding logic
326     final Object call(final JS.UnpauseCallback callback, final JSArray args) {
327         try {
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));
335             try {
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); }});
340             } finally {
341                 tracker.clear();
342                 objects.setSize(0);
343             }
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())); }});
353         }
354     }
355 }