4d541fd87d27832ffae28c43b4911b45be026941
[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                 try {
134                     struct.put(memberName, memberValue);
135                 } catch (JSExn e) {
136                     throw new Error("this should never happen");
137                 }
138                 objects.setSize(objects.size() - 2);
139             case "data":
140                 int i;
141                 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
142                 JSArray arr = new JSArray();
143                 try {
144                     for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
145                 } catch (JSExn e) {
146                     throw new Error("this should never happen");
147                 }
148                 objects.setElementAt(arr, i);
149                 objects.setSize(i + 1);
150             //#end            
151             content.reset();
152         }
153         
154         public void characters(char[] ch, int start, int length) {
155             try { content.write(ch, start, length); }
156             catch (Exception e) { 
157                 if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
158                 if (Log.on) Log.log(this, e);
159             }
160         }
161         
162         public void whitespace(char[] ch, int start, int length) {}
163     }
164
165     // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
166
167     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
168     void appendObject(Object o, StringBuffer sb) throws JSExn {
169
170         if (o == null) {
171             throw new JSExn("attempted to send a null value via XML-RPC");
172
173         } else if (o instanceof Number) {
174             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
175                 sb.append("                <value><i4>");
176                 sb.append(((Number)o).intValue());
177                 sb.append("</i4></value>\n");
178             } else {
179                 sb.append("                <value><double>");
180                 sb.append(o);
181                 sb.append("</double></value>\n");
182             }
183
184         } else if (o instanceof Boolean) {
185             sb.append("                <value><boolean>");
186             sb.append(((Boolean)o).booleanValue() ? "1" : "0");
187             sb.append("</boolean></value>\n");
188
189         } else if (o instanceof Res) {
190             try {
191                 sb.append("                <value><base64>\n");
192                 InputStream is = ((Res)o).getInputStream();
193                 byte[] buf = new byte[54];
194                 while(true) {
195                     int numread = is.read(buf, 0, 54);
196                     if (numread == -1) break;
197                     byte[] writebuf = buf;
198                     if (numread < buf.length) {
199                         writebuf = new byte[numread];
200                         System.arraycopy(buf, 0, writebuf, 0, numread);
201                     }
202                     sb.append("              ");
203                     sb.append(new String(Base64.encode(writebuf)));
204                     sb.append("\n");
205                 }
206                 sb.append("\n              </base64></value>\n");
207             } catch (IOException e) {
208                 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
209                 if (Log.on) Log.log(this, e);
210                 throw new JSExn("caught IOException while attempting to send a ByteStream via XML-RPC");
211             }
212
213         } else if (o instanceof String) {
214             sb.append("                <value><string>");
215             String s = (String)o;
216             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
217                 sb.append(s);
218             } else {
219                 char[] cbuf = s.toCharArray();
220                 int oldi = 0, i=0;
221                 while(true) {
222                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
223                     sb.append(cbuf, oldi, i - oldi);
224                     if (i >= cbuf.length) break;
225                     if (cbuf[i] == '<') sb.append("&lt;");
226                     else if (cbuf[i] == '&') sb.append("&amp;");
227                     i = oldi = i + 1;
228                     if (i >= cbuf.length) break;
229                 }
230             }
231             sb.append("</string></value>\n");
232
233         } else if (o instanceof JSDate) {
234             sb.append("                <value><dateTime.iso8601>");
235             java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
236             sb.append(d.getYear() + 1900);
237             if (d.getMonth() + 1 < 10) sb.append('0');
238             sb.append(d.getMonth() + 1);
239             if (d.getDate() < 10) sb.append('0');
240             sb.append(d.getDate());
241             sb.append('T');
242             if (d.getHours() < 10) sb.append('0');
243             sb.append(d.getHours());
244             sb.append(':');
245             if (d.getMinutes() < 10) sb.append('0');
246             sb.append(d.getMinutes());
247             sb.append(':');
248             if (d.getSeconds() < 10) sb.append('0');
249             sb.append(d.getSeconds());
250             sb.append("</dateTime.iso8601></value>\n");
251
252         } else if (o instanceof JSArray) {
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             sb.append("                <value><array><data>\n");
256             JSArray a = (JSArray)o;
257             for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
258             sb.append("                </data></array></value>\n");
259
260         } else if (o instanceof JS) {
261             if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
262             tracker.put(o, Boolean.TRUE);
263             JS j = (JS)o;
264             sb.append("                <value><struct>\n");
265             Enumeration e = j.keys();
266             while(e.hasMoreElements()) {
267                 Object key = e.nextElement();
268                 sb.append("                <member><name>" + key + "</name>\n");
269                 appendObject(j.get(key), sb);
270                 sb.append("                </member>\n");
271             }
272             sb.append("                </struct></value>\n");
273
274         } else {
275             throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
276
277         }
278     }
279
280     public Object call_(JSArray args) throws JSExn, IOException {
281         if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
282
283         if (tracker == null) tracker = new Hash();
284         else tracker.clear();
285
286         if (objects == null) objects = new Vec();
287         else objects.setSize(0);
288
289         final String content = send(args, http);
290         if (Log.verbose) {
291             String s;
292             BufferedReader br2 = new BufferedReader(new StringReader(content));
293             while ((s = br2.readLine()) != null) Log.log(this, "send: " + s);
294         }
295
296         InputStream is = http.POST("text/xml", content);
297         try {
298             BufferedReader br = !Log.verbose ?
299                 new BufferedReader(new InputStreamReader(is)) :
300                 new BufferedReader(new FilterReader(new InputStreamReader(is)) {
301                         public int read() throws IOException {
302                             int i = super.read();
303                             if (Log.on) Log.log(this, "recv: " + ((char)i));
304                             return i;
305                         }
306                         public int read(char[] c, int off, int len) throws IOException {
307                             int ret = super.read(c, off, len);
308                             if (ret == -1) return ret;
309                             String s;
310                             BufferedReader br2 = new BufferedReader(new StringReader(new String(c, off, ret)));
311                             while ((s = br2.readLine()) != null) Log.log(this, "recv: " + s);
312                             return ret;
313                         }
314                     });
315             return null;
316         } finally {
317             is.close();
318         }
319     }
320
321     protected String send(JSArray args, HTTP http) throws JSExn, IOException {
322         StringBuffer content = new StringBuffer();
323         content.append("\r\n");
324         content.append("<?xml version=\"1.0\"?>\n");
325         content.append("    <methodCall>\n");
326         content.append("        <methodName>");
327         content.append(methodname);
328         content.append("</methodName>\n");
329         content.append("        <params>\n");
330         for(int i=0; i<args.length(); i++) {
331             content.append("            <param>\n");
332             appendObject(args.elementAt(i), content);
333             content.append("            </param>\n");
334         }
335         content.append("        </params>\n");
336         content.append("    </methodCall>");
337         return content.toString();
338     }
339         
340     protected Object recieve(BufferedReader br) throws JSExn, IOException {
341         // parse XML reply
342         try {
343             new Helper().parse(br);
344         } catch (XML.XMLException e) {
345             if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
346             throw new JSExn("reply from server was not well-formed XML: " + e);
347         }
348         
349         if (fault) throw new JSExn(objects.elementAt(0));
350         if (objects.size() == 0) return null;
351         return objects.elementAt(0);
352     }
353
354     public final Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
355         JSArray args = new JSArray();
356         for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
357         return call(args);
358     }
359     public final Object call(final JSArray args) throws JSExn {
360         try {
361             final JS.UnpauseCallback callback = JS.pause();
362             new java.lang.Thread() {
363                 public void run() {
364                     try {
365                         try {
366                             final Object ret = call_(args);
367                             Scheduler.add(new Scheduler.Task() {
368                                     public void perform() {
369                                         try {
370                                             callback.unpause(null);
371                                         } catch (JS.PausedException pe) {
372                                             // okay
373                                         } catch (JSExn e) {
374                                             // FIXME
375                                             throw new Error("FIXME");
376                                         }
377                                     }
378                                 });
379                         } catch (IOException se) {
380                             if (Log.on) Log.log(this, se);
381                             throw new JSExn("socket exception: " + se);
382                         }
383                     } catch (JSExn e) {
384                         // FIXME
385                         throw new Error("FIXME");
386                     }
387                 } }.start();
388             return null;
389         } catch (NotPauseableException npe) {
390             throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
391         }
392     }
393
394     /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
395     public Object get(Object name) {
396         return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name.toString(), http);
397     }
398
399     public XMLRPC(String url, String methodname) {
400         this(url, methodname, new HTTP(url));
401     }
402
403     public XMLRPC(String url, String methodname, HTTP http) {
404         this.http = http;
405         this.url = url;
406         this.methodname = methodname;
407     }
408
409
410     // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
411
412     /** CharArrayWriter that lets us touch its buffer */
413     protected static class AccessibleCharArrayWriter extends CharArrayWriter {
414         public char[] getBuf() { return buf; }
415         public AccessibleCharArrayWriter(int i) { super(i); }
416     }
417
418 }