2003/11/27 05:05:09
[org.ibex.core.git] / src / org / xwt / XMLRPC.java
1 // Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.xwt;
3
4 import java.io.*;
5 import java.net.*;
6 import java.util.*;
7 import org.xwt.js.*;
8 import org.xwt.util.*;
9 import org.bouncycastle.util.encoders.Base64;
10
11 /**
12  *  An XML-RPC client implemented as a JavaScript Host Object. See the
13  *  XWT 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 class XMLRPC extends JS {
34
35     /** the url to connect to */
36     protected String url = null;
37
38     /** the method name to invoke on the remove server */
39     protected String methodname = null;
40
41     /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
42     protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
43
44     /** the HTTP connection to use */
45     protected HTTP http = null;
46
47     /** The object stack. As we process xml elements, pieces of the
48      *  return value are pushed onto and popped off of this stack.
49      *
50      *  The general protocol is that any time a &lt;value&gt; tag is
51      *  encountered, an empty String ("") is pushed onto the stack. If
52      *  the &lt;value/&gt; node has content (either an anonymous
53      *  string or some other XML node), that content replaces the
54      *  empty string.
55      *
56      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
57      *  stack. When a &lt;/data&gt; is encountered, we search back on the
58      *  stack to the last null, replace it with a NativeJSArray, and
59      *  insert into it all elements above it on the stack.
60      *
61      *  If a &lt;struct&gt; tag is encountered, a JSect is pushed
62      *  onto the stack. If a &lt;name&gt; tag is encountered, its CDATA is
63      *  pushed onto the stack. When a &lt;/member&gt; is encountered, the
64      *  name (second element on stack) and value (top of stack) are
65      *  popped off the stack and inserted into the struct (third
66      *  element on stack).
67      */
68     protected Vec objects = null;
69
70     /** used to detect multi-ref data */
71     private Hash tracker;
72
73     /** True iff the return value is a fault (and should be thrown as an exception) */
74     protected boolean fault = false;
75
76
77     // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
78
79     private class Helper extends XML {
80         public Helper() { super(BUFFER_SIZE); }
81
82         public void startElement(XML.Element c) {
83             content.reset();
84             //#switch(c.localName)
85             case "fault": fault = true;
86             case "struct": objects.setElementAt(new JS(), objects.size() - 1);
87             case "array": objects.setElementAt(null, objects.size() - 1);
88             case "value": objects.addElement("");
89             //#end
90         }
91         
92         public void endElement(XML.Element c) {
93             //#switch(c.localName)
94             case "int": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
95             case "i4": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
96             case "boolean": objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
97             case "string": objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
98             case "double": objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
99             case "base64": objects.setElementAt(new Res.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())),
100                                                                   null), objects.size() - 1);
101             case "name": objects.addElement(new String(content.getBuf(), 0, content.size()));
102             case "value": if ("".equals(objects.lastElement()))
103                 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
104             case "dateTime.iso8601":
105                 String s = new String(content.getBuf(), 0, content.size());
106                 
107                 // strip whitespace
108                 int i=0;
109                 while(Character.isWhitespace(s.charAt(i))) i++;
110                 if (i > 0) s = s.substring(i);
111                 
112                 try {
113                     JSDate nd = new JSDate();
114                     double date = JSDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
115                                                                     Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
116                                                                     Double.valueOf(s.substring(6, 8)).doubleValue(),
117                                                                     Double.valueOf(s.substring(9, 11)).doubleValue(),
118                                                                     Double.valueOf(s.substring(12, 14)).doubleValue(),
119                                                                     Double.valueOf(s.substring(15, 17)).doubleValue(),
120                                                                     (double)0
121                                                                     );
122                     nd.setTime(JSDate.internalUTC(date));
123                     objects.setElementAt(nd, objects.size() - 1);
124                     
125                 } catch (Exception e) {
126                     if (Log.on) Log.log(this, "error parsing date : " + s);
127                     if (Log.on) Log.log(this, e);
128                 }
129             case "member":
130                 Object memberValue = objects.elementAt(objects.size() - 1);
131                 String memberName = (String)objects.elementAt(objects.size() - 2);
132                 JS struct = (JS)objects.elementAt(objects.size() - 3);
133                 struct.put(memberName, memberValue);
134                 objects.setSize(objects.size() - 2);
135             case "data":
136                 int i;
137                 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
138                 JSArray arr = new JSArray();
139                 for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
140                 objects.setElementAt(arr, i);
141                 objects.setSize(i + 1);
142             //#end            
143             content.reset();
144         }
145         
146         public void characters(char[] ch, int start, int length) {
147             try { content.write(ch, start, length); }
148             catch (Exception e) { 
149                 if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
150                 if (Log.on) Log.log(this, e);
151             }
152         }
153         
154         public void whitespace(char[] ch, int start, int length) {}
155     }
156
157     // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
158
159     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
160     void appendObject(Object o, StringBuffer sb) throws JSExn {
161
162         if (o == null) {
163             throw new JSExn("attempted to send a null value via XML-RPC");
164
165         } else if (o instanceof Number) {
166             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
167                 sb.append("                <value><i4>");
168                 sb.append(((Number)o).intValue());
169                 sb.append("</i4></value>\n");
170             } else {
171                 sb.append("                <value><double>");
172                 sb.append(o);
173                 sb.append("</double></value>\n");
174             }
175
176         } else if (o instanceof Boolean) {
177             sb.append("                <value><boolean>");
178             sb.append(((Boolean)o).booleanValue() ? "1" : "0");
179             sb.append("</boolean></value>\n");
180
181         } else if (o instanceof Res) {
182             try {
183                 sb.append("                <value><base64>\n");
184                 InputStream is = ((Res)o).getInputStream();
185                 byte[] buf = new byte[54];
186                 while(true) {
187                     int numread = is.read(buf, 0, 54);
188                     if (numread == -1) break;
189                     byte[] writebuf = buf;
190                     if (numread < buf.length) {
191                         writebuf = new byte[numread];
192                         System.arraycopy(buf, 0, writebuf, 0, numread);
193                     }
194                     sb.append("              ");
195                     sb.append(new String(Base64.encode(writebuf)));
196                     sb.append("\n");
197                 }
198                 sb.append("\n              </base64></value>\n");
199             } catch (IOException e) {
200                 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
201                 if (Log.on) Log.log(this, e);
202                 throw new JSExn("caught IOException while attempting to send a ByteStream via XML-RPC");
203             }
204
205         } else if (o instanceof String) {
206             sb.append("                <value><string>");
207             String s = (String)o;
208             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
209                 sb.append(s);
210             } else {
211                 char[] cbuf = s.toCharArray();
212                 int oldi = 0, i=0;
213                 while(true) {
214                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
215                     sb.append(cbuf, oldi, i - oldi);
216                     if (i >= cbuf.length) break;
217                     if (cbuf[i] == '<') sb.append("&lt;");
218                     else if (cbuf[i] == '&') sb.append("&amp;");
219                     i = oldi = i + 1;
220                     if (i >= cbuf.length) break;
221                 }
222             }
223             sb.append("</string></value>\n");
224
225         } else if (o instanceof JSDate) {
226             sb.append("                <value><dateTime.iso8601>");
227             java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
228             sb.append(d.getYear() + 1900);
229             if (d.getMonth() + 1 < 10) sb.append('0');
230             sb.append(d.getMonth() + 1);
231             if (d.getDate() < 10) sb.append('0');
232             sb.append(d.getDate());
233             sb.append('T');
234             if (d.getHours() < 10) sb.append('0');
235             sb.append(d.getHours());
236             sb.append(':');
237             if (d.getMinutes() < 10) sb.append('0');
238             sb.append(d.getMinutes());
239             sb.append(':');
240             if (d.getSeconds() < 10) sb.append('0');
241             sb.append(d.getSeconds());
242             sb.append("</dateTime.iso8601></value>\n");
243
244         } else if (o instanceof JSArray) {
245             if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
246             tracker.put(o, Boolean.TRUE);
247             sb.append("                <value><array><data>\n");
248             JSArray a = (JSArray)o;
249             for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
250             sb.append("                </data></array></value>\n");
251
252         } else if (o instanceof JS) {
253             if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
254             tracker.put(o, Boolean.TRUE);
255             JS j = (JS)o;
256             sb.append("                <value><struct>\n");
257             Enumeration e = j.keys();
258             while(e.hasMoreElements()) {
259                 Object key = e.nextElement();
260                 sb.append("                <member><name>" + key + "</name>\n");
261                 appendObject(j.get(key), sb);
262                 sb.append("                </member>\n");
263             }
264             sb.append("                </struct></value>\n");
265
266         } else {
267             throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
268
269         }
270     }
271
272     public Object call_(JSArray args) throws JSExn, IOException {
273         if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
274
275         if (tracker == null) tracker = new Hash();
276         else tracker.clear();
277
278         if (objects == null) objects = new Vec();
279         else objects.setSize(0);
280
281         final String content = send(args, http);
282         if (Log.verbose) {
283             String s;
284             BufferedReader br2 = new BufferedReader(new StringReader(content));
285             while ((s = br2.readLine()) != null) Log.log(this, "send: " + s);
286         }
287
288         InputStream is = http.POST("text/xml", content);
289         try {
290             BufferedReader br = !Log.verbose ?
291                 new BufferedReader(new InputStreamReader(is)) :
292                 new BufferedReader(new FilterReader(new InputStreamReader(is)) {
293                         public int read() throws IOException {
294                             int i = super.read();
295                             if (Log.on) Log.log(this, "recv: " + ((char)i));
296                             return i;
297                         }
298                         public int read(char[] c, int off, int len) throws IOException {
299                             int ret = super.read(c, off, len);
300                             if (ret == -1) return ret;
301                             String s;
302                             BufferedReader br2 = new BufferedReader(new StringReader(new String(c, off, ret)));
303                             while ((s = br2.readLine()) != null) Log.log(this, "recv: " + s);
304                             return ret;
305                         }
306                     });
307             return null;
308         } finally {
309             is.close();
310         }
311     }
312
313     protected String send(JSArray args, HTTP http) throws JSExn, IOException {
314         StringBuffer content = new StringBuffer();
315         content.append("\r\n");
316         content.append("<?xml version=\"1.0\"?>\n");
317         content.append("    <methodCall>\n");
318         content.append("        <methodName>");
319         content.append(methodname);
320         content.append("</methodName>\n");
321         content.append("        <params>\n");
322         for(int i=0; i<args.length(); i++) {
323             content.append("            <param>\n");
324             appendObject(args.elementAt(i), content);
325             content.append("            </param>\n");
326         }
327         content.append("        </params>\n");
328         content.append("    </methodCall>");
329         return content.toString();
330     }
331         
332     protected Object recieve(BufferedReader br) throws JSExn, IOException {
333         // parse XML reply
334         try {
335             new Helper().parse(br);
336         } catch (XML.XMLException e) {
337             if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
338             throw new JSExn("reply from server was not well-formed XML: " + e);
339         }
340         
341         if (fault) throw new JSExn(objects.elementAt(0));
342         if (objects.size() == 0) return null;
343         return objects.elementAt(0);
344     }
345
346     public final Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
347         JSArray args = new JSArray();
348         for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
349         return call(args);
350     }
351     public final Object call(final JSArray args) throws JSExn {
352         try {
353             final JS.UnpauseCallback callback = JS.pause();
354             new java.lang.Thread() {
355                 public void run() {
356                     try {
357                         final Object ret = call_(args);
358                         Scheduler.add(new Scheduler.Task() {
359                                 public void perform() {
360                                     try {
361                                         callback.unpause(null);
362                                     } catch (JS.PausedException pe) {
363                                         // okay
364                                     }
365                                 }
366                             });
367                     } catch (IOException se) {
368                         if (Log.on) Log.log(this, se);
369                         throw new JSExn("socket exception: " + se);
370                     }
371                 } }.start();
372             return null;
373         } catch (NotPauseableException npe) {
374             throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
375         }
376     }
377
378     /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
379     public Object get(Object name) {
380         return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name.toString(), http);
381     }
382
383     public XMLRPC(String url, String methodname) {
384         this(url, methodname, new HTTP(url));
385     }
386
387     public XMLRPC(String url, String methodname, HTTP http) {
388         this.http = http;
389         this.url = url;
390         this.methodname = methodname;
391     }
392
393
394     // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
395
396     /** CharArrayWriter that lets us touch its buffer */
397     protected static class AccessibleCharArrayWriter extends CharArrayWriter {
398         public char[] getBuf() { return buf; }
399         public AccessibleCharArrayWriter(int i) { super(i); }
400     }
401
402 }