preliminary core conversion
[org.ibex.core.git] / src / org / ibex / net / XMLRPC.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex.net;
3
4 import java.io.*;
5 import java.util.*;
6 import org.ibex.js.*;
7 import org.ibex.util.*;
8 import org.ibex.crypto.*;
9
10 /**
11  *  An XML-RPC client implemented as a JavaScript Host Object. See the
12  *  Ibex spec for information on its behavior.
13  *
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.
18  *
19  *  This client conforms to <a href="http://www.xmlrpc.com/spec">The
20  *  XML-RPC Spec</a>, subject to these limitations:
21  *  <ol>
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
29  *         convert.
30  *  </ol>
31  */
32 public class XMLRPC extends JS {
33
34     public XMLRPC(String url, String method) {
35         this.http = url.startsWith("stdio:") ? HTTP.stdio : new HTTP(url);
36         this.url = url;
37         this.method = method;
38     }
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); }
43
44
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)
52
53
54     /** The object stack. As we process xml elements, pieces of the
55      *  return value are pushed onto and popped off of this stack.
56      *
57      *  The general protocol is that any time a &lt;value&gt; tag is
58      *  encountered, an empty String ("") is pushed onto the stack. If
59      *  the &lt;value/&gt; node has content (either an anonymous
60      *  string or some other XML node), that content replaces the
61      *  empty string.
62      *
63      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
64      *  stack. When a &lt;/data&gt; 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.
67      *
68      *  If a &lt;struct&gt; tag is encountered, a JSect is pushed
69      *  onto the stack. If a &lt;name&gt; tag is encountered, its CDATA is
70      *  pushed onto the stack. When a &lt;/member&gt; 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
73      *  element on stack).
74      */
75     protected Vec objects = null;
76
77
78     // Recieve ////////////////////////////////////////////////////////////////
79
80     private class Helper extends XML {
81         public Helper() { super(BUFFER_SIZE); }
82
83         public void startElement(XML.Element c) {
84             content.reset();
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("");
90             //#end
91         }
92         
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);
100             case "base64":
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());
108                 
109                 // strip whitespace
110                 int i=0;
111                 while(Character.isWhitespace(s.charAt(i))) i++;
112                 if (i > 0) s = s.substring(i);
113                 
114                 try {
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(),
122                                                            (double)0
123                                                            );
124                     nd.setTime(JSDate.internalUTC(date));
125                     objects.setElementAt(nd, objects.size() - 1);
126                     
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);
130                 }
131             case "member":
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);
135                 try {
136                     struct.put(JS.S(memberName), memberValue);
137                 } catch (JSExn e) {
138                     throw new Error("this should never happen");
139                 }
140                 objects.setSize(objects.size() - 2);
141             case "data":
142                 int i;
143                 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
144                 JSArray arr = new JSArray();
145                 try {
146                     for(int j = i + 1; j<objects.size(); j++) arr.put(JS.N(j - i - 1), (JS)objects.elementAt(j));
147                 } catch (JSExn e) {
148                     throw new Error("this should never happen");
149                 }
150                 objects.setElementAt(arr, i);
151                 objects.setSize(i + 1);
152             //#end            
153             content.reset();
154         }
155         
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);
161             }
162         }
163         
164         public void whitespace(char[] ch, int start, int length) {}
165     }
166
167     // Send ///////////////////////////////////////////////////////////////////////////
168
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");
182         }
183         content.append("        </params>\n");
184         content.append("    </methodCall>");
185         return content.toString();
186     }
187
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");
192         /*if (o == null) {
193             throw new JSExn("attempted to send a null value via XML-RPC");
194
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");
200             } else {
201                 sb.append("                <value><double>");
202                 sb.append(o);
203                 sb.append("</double></value>\n");
204             }
205
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");
210
211         } else if (o instanceof Stream) {
212             try {
213                 sb.append("                <value><base64>\n");
214                 InputStream is = ((Stream)o).getInputStream();
215                 byte[] buf = new byte[54];
216                 while(true) {
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);
223                     }
224                     sb.append("              ");
225                     sb.append(new String(Base64.encode(writebuf)));
226                     sb.append("\n");
227                 }
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");
233             }
234
235         } else if (o instanceof String) {
236             sb.append("                <value><string>");
237             String s = (String)o;
238             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
239                 sb.append(s);
240             } else {
241                 char[] cbuf = s.toCharArray();
242                 int oldi = 0, i=0;
243                 while(true) {
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("&lt;");
248                     else if (cbuf[i] == '&') sb.append("&amp;");
249                     i = oldi = i + 1;
250                     if (i >= cbuf.length) break;
251                 }
252             }
253             sb.append("</string></value>\n");
254
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());
263             sb.append('T');
264             if (d.getHours() < 10) sb.append('0');
265             sb.append(d.getHours());
266             sb.append(':');
267             if (d.getMinutes() < 10) sb.append('0');
268             sb.append(d.getMinutes());
269             sb.append(':');
270             if (d.getSeconds() < 10) sb.append('0');
271             sb.append(d.getSeconds());
272             sb.append("</dateTime.iso8601></value>\n");
273
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");
281
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);
285             JS j = (JS)o;
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");
293             }
294             sb.append("                </struct></value>\n");
295
296         } else {
297             throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
298
299         }*/
300     }
301
302
303     // Call Sequence //////////////////////////////////////////////////////////////////////////
304
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]);
308         return call(args);
309     }
310
311     public final JS call(final JSArray args) throws JSExn {
312         try {
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");
318         }
319     }
320
321     final void call(final JS.UnpauseCallback callback, final JSArray args) {
322         try {
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));
330             try {
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); }});
335             } finally {
336                 tracker.clear();
337                 objects.setSize(0);
338             }
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())); }});
347         }
348     }
349 }