update Directory, Fountain, JSReflection, SOAP, XMLRPC to use baskets and new JS...
[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 org.ibex.net.*;
9 import org.ibex.util.*;
10
11 /**
12  *  An XML-RPC client implemented as a JavaScript Host Object. See the
13  *  Ibex spec for information on its behavior.
14  *
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.
19  *
20  *  This client conforms to <a href="http://www.xmlrpc.com/spec">The
21  *  XML-RPC Spec</a>, subject to these limitations:
22  *  <ol>
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
30  *         convert.
31  *  </ol>
32  */
33 public class XMLRPC extends JS.Immutable {
34
35     public XMLRPC(String url, String method) {
36         this.http = url.startsWith("stdio:") ? HTTP.stdio : new HTTP(url);
37         this.url = url;
38         this.method = method;
39     }
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 + ".") + Script.toString(name), this); }
44
45
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); }
50         public char[] buf;
51     };
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)
57
58
59     /** The object stack. As we process xml elements, pieces of the
60      *  return value are pushed onto and popped off of this stack.
61      *
62      *  The general protocol is that any time a &lt;value&gt; tag is
63      *  encountered, an empty String ("") is pushed onto the stack. If
64      *  the &lt;value/&gt; node has content (either an anonymous
65      *  string or some other XML node), that content replaces the
66      *  empty string.
67      *
68      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
69      *  stack. When a &lt;/data&gt; 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.
72      *
73      *  If a &lt;struct&gt; tag is encountered, a JSect is pushed
74      *  onto the stack. If a &lt;name&gt; tag is encountered, its CDATA is
75      *  pushed onto the stack. When a &lt;/member&gt; 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
78      *  element on stack).
79      */
80     protected Basket.Array objects = null;
81     private void setLast(Object o) { objects.set(objects.size() - 1, o); }
82
83
84     // Recieve ////////////////////////////////////////////////////////////////
85
86     private class Helper extends XML {
87         public Helper() { super(BUFFER_SIZE, true); }
88
89         public void startElement(Tree.Element c) {
90             content.reset();
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("");
96             //#end
97         }
98         
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())));
106             case "base64":
107                 setLast(new Fountain.ByteArray(Encode.fromBase64(new String(content.buf, 0, content.size())),
108                                                           null));
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());
114                 
115                 // strip whitespace
116                 int i=0;
117                 while(Character.isWhitespace(s.charAt(i))) i++;
118                 if (i > 0) s = s.substring(i);
119                 
120                 try {
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(),
128                                                            (double)0
129                                                            );
130                     nd.setTime(JSDate.internalUTC(date));
131                     setLast(nd);
132                     
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);
136                 }
137             case "member":
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);
141                 try {
142                     struct.put(memberName, memberValue);
143                 } catch (JSExn e) {
144                     throw new Error("this should never happen");
145                 }
146                 objects.pop();
147                 objects.pop();
148             case "data":
149                 int i;
150                 for(i=objects.size() - 1; objects.get(i) != null; i--);
151                 JSArray arr = new JSArray();
152                 try {
153                     for(int j = i + 1; j<objects.size(); j++) arr.put(Script.N(j - i - 1), (JS)objects.get(j));
154                 } catch (JSExn e) {
155                     throw new Error("this should never happen");
156                 }
157                 objects.set(i, arr);
158                 objects.add(null);
159             //#end            
160             content.reset();
161         }
162         
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);
168             }
169         }
170         
171         public void whitespace(char[] ch, int start, int length) {}
172     }
173
174     // Send ///////////////////////////////////////////////////////////////////////////
175
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");
189         }
190         content.append("        </params>\n");
191         content.append("    </methodCall>");
192         return content.toString();
193     }
194
195     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
196     void appendObject(Object o, StringBuffer sb) throws JSExn {
197
198         if (o == null) {
199             throw new JSExn("attempted to send a null value via XML-RPC");
200
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");
206             } else {
207                 sb.append("                <value><double>");
208                 sb.append(o);
209                 sb.append("</double></value>\n");
210             }
211
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");
216
217         } else if (o instanceof Fountain) {
218             try {
219                 sb.append("                <value><base64>\n");
220                 InputStream is = ((Fountain)o).getInputStream();
221                 byte[] buf = new byte[54];
222                 while(true) {
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);
229                     }
230                     sb.append("              ");
231                     sb.append(new String(Encode.toBase64(writebuf)));
232                     sb.append("\n");
233                 }
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");
239             }
240
241         } else if (o instanceof String) {
242             sb.append("                <value><string>");
243             String s = (String)o;
244             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
245                 sb.append(s);
246             } else {
247                 char[] cbuf = s.toCharArray();
248                 int oldi = 0, i=0;
249                 while(true) {
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("&lt;");
254                     else if (cbuf[i] == '&') sb.append("&amp;");
255                     i = oldi = i + 1;
256                     if (i >= cbuf.length) break;
257                 }
258             }
259             sb.append("</string></value>\n");
260
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());
269             sb.append('T');
270             if (d.getHours() < 10) sb.append('0');
271             sb.append(d.getHours());
272             sb.append(':');
273             if (d.getMinutes() < 10) sb.append('0');
274             sb.append(d.getMinutes());
275             sb.append(':');
276             if (d.getSeconds() < 10) sb.append('0');
277             sb.append(d.getSeconds());
278             sb.append("</dateTime.iso8601></value>\n");
279
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, Script.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");
287
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, Script.B(true));
291             JS j = (JS)o;
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");
299             }
300             sb.append("                </struct></value>\n");
301
302         } else {
303             throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
304
305         }
306     }
307
308
309     // Call Sequence //////////////////////////////////////////////////////////////////////////
310
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]);
315         return call(args);
316     }
317
318     public final Object call(final JSArray args) throws JSExn {
319         try {
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");
325         }
326     }
327     */
328
329     // FIXME need to reenable backgrounding logic
330     final Object call(final Pausable callback, final JSArray args) {
331         try {
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));
339             try {
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); }});
345             } finally {
346                 tracker.clear();
347                 objects.clear();
348             }
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)); }});
356         }
357     }
358 }