43654c7f2a5a6c15168015d5e86258401a7a5739
[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 JSCallable {
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 JSObject 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             if (c.localName.equals("fault")) fault = true;
85             else if (c.localName.equals("struct")) objects.setElementAt(new JSObj(), objects.size() - 1);
86             else if (c.localName.equals("array")) objects.setElementAt(null, objects.size() - 1);
87             else if (c.localName.equals("value")) objects.addElement("");
88         }
89         
90         public void endElement(XML.Element c) {
91             
92             if (c.localName.equals("int") || c.localName.equals("i4"))
93                 objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
94             
95             else if (c.localName.equals("boolean"))
96                 objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
97             
98             else if (c.localName.equals("string"))
99                 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
100             
101             else if (c.localName.equals("double"))
102                 objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
103             
104             else if (c.localName.equals("base64"))
105                 objects.setElementAt(new Res.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())), null), objects.size() - 1);
106
107             else if (c.localName.equals("name"))
108                 objects.addElement(new String(content.getBuf(), 0, content.size()));
109             
110             else if (c.localName.equals("value") && "".equals(objects.lastElement()))
111                 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
112             
113             else if (c.localName.equals("dateTime.iso8601")) {
114                 String s = new String(content.getBuf(), 0, content.size());
115                 
116                 // strip whitespace
117                 int i=0;
118                 while(Character.isWhitespace(s.charAt(i))) i++;
119                 if (i > 0) s = s.substring(i);
120                 
121                 try {
122                     JSDate nd = new JSDate();
123                     double date = JSDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
124                                                                     Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
125                                                                     Double.valueOf(s.substring(6, 8)).doubleValue(),
126                                                                     Double.valueOf(s.substring(9, 11)).doubleValue(),
127                                                                     Double.valueOf(s.substring(12, 14)).doubleValue(),
128                                                                     Double.valueOf(s.substring(15, 17)).doubleValue(),
129                                                                     (double)0
130                                                                     );
131                     nd.jsJSFunction_setTime(JSDate.internalUTC(date));
132                     objects.setElementAt(nd, objects.size() - 1);
133                     
134                 } catch (Exception e) {
135                     if (Log.on) Log.log(this, "error parsing date : " + s);
136                     if (Log.on) Log.log(this, e);
137                 }
138                 
139             } else if (c.localName.equals("member")) {
140                 Object memberValue = objects.elementAt(objects.size() - 1);
141                 String memberName = (String)objects.elementAt(objects.size() - 2);
142                 JS struct = (JS)objects.elementAt(objects.size() - 3);
143                 struct.put(memberName, memberValue);
144                 objects.setSize(objects.size() - 2);
145                 
146             } else if (c.localName.equals("data")) {
147                 int i;
148                 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
149                 JSArray arr = new JSArray();
150                 for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
151                 objects.setElementAt(arr, i);
152                 objects.setSize(i + 1);
153                 
154             }
155             
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.log(this, "Exception in XMLRPC.content() -- this should never happen");
163                 if (Log.on) Log.log(this, e);
164             }
165         }
166         
167         public void whitespace(char[] ch, int start, int length) {}
168     }
169
170     // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
171
172     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
173     void appendObject(Object o, StringBuffer sb) throws JS.Exn {
174
175         if (o == null) {
176             throw new JS.Exn("attempted to send a null value via XML-RPC");
177
178         } else if (o instanceof Number) {
179             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
180                 sb.append("                <value><i4>");
181                 sb.append(((Number)o).intValue());
182                 sb.append("</i4></value>\n");
183             } else {
184                 sb.append("                <value><double>");
185                 sb.append(o);
186                 sb.append("</double></value>\n");
187             }
188
189         } else if (o instanceof Boolean) {
190             sb.append("                <value><boolean>");
191             sb.append(((Boolean)o).booleanValue() ? "1" : "0");
192             sb.append("</boolean></value>\n");
193
194         } else if (o instanceof Res) {
195             try {
196                 sb.append("                <value><base64>\n");
197                 InputStream is = ((Res)o).getInputStream();
198                 byte[] buf = new byte[54];
199                 while(true) {
200                     int numread = is.read(buf, 0, 54);
201                     if (numread == -1) break;
202                     byte[] writebuf = buf;
203                     if (numread < buf.length) {
204                         writebuf = new byte[numread];
205                         System.arraycopy(buf, 0, writebuf, 0, numread);
206                     }
207                     sb.append("              ");
208                     sb.append(new String(Base64.encode(writebuf)));
209                     sb.append("\n");
210                 }
211                 sb.append("\n              </base64></value>\n");
212             } catch (IOException e) {
213                 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
214                 if (Log.on) Log.log(this, e);
215                 throw new JS.Exn("caught IOException while attempting to send a ByteStream via XML-RPC");
216             }
217
218         } else if (o instanceof String) {
219             sb.append("                <value><string>");
220             String s = (String)o;
221             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
222                 sb.append(s);
223             } else {
224                 char[] cbuf = s.toCharArray();
225                 int oldi = 0, i=0;
226                 while(true) {
227                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
228                     sb.append(cbuf, oldi, i - oldi);
229                     if (i >= cbuf.length) break;
230                     if (cbuf[i] == '<') sb.append("&lt;");
231                     else if (cbuf[i] == '&') sb.append("&amp;");
232                     i = oldi = i + 1;
233                     if (i >= cbuf.length) break;
234                 }
235             }
236             sb.append("</string></value>\n");
237
238         } else if (o instanceof JSDate) {
239             sb.append("                <value><dateTime.iso8601>");
240             java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
241             sb.append(d.getYear() + 1900);
242             if (d.getMonth() + 1 < 10) sb.append('0');
243             sb.append(d.getMonth() + 1);
244             if (d.getDate() < 10) sb.append('0');
245             sb.append(d.getDate());
246             sb.append('T');
247             if (d.getHours() < 10) sb.append('0');
248             sb.append(d.getHours());
249             sb.append(':');
250             if (d.getMinutes() < 10) sb.append('0');
251             sb.append(d.getMinutes());
252             sb.append(':');
253             if (d.getSeconds() < 10) sb.append('0');
254             sb.append(d.getSeconds());
255             sb.append("</dateTime.iso8601></value>\n");
256
257         } else if (o instanceof JSArray) {
258             if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
259             tracker.put(o, Boolean.TRUE);
260             sb.append("                <value><array><data>\n");
261             JSArray a = (JSArray)o;
262             for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
263             sb.append("                </data></array></value>\n");
264
265         } else if (o instanceof JS) {
266             if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
267             tracker.put(o, Boolean.TRUE);
268             JS j = (JS)o;
269             sb.append("                <value><struct>\n");
270             Enumeration e = j.keys();
271             while(e.hasMoreElements()) {
272                 Object key = e.nextElement();
273                 sb.append("                <member><name>" + key + "</name>\n");
274                 appendObject(j.get(key), sb);
275                 sb.append("                </member>\n");
276             }
277             sb.append("                </struct></value>\n");
278
279         } else {
280             throw new JS.Exn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
281
282         }
283     }
284
285     public Object call_(JSArray args) throws JS.Exn, IOException {
286         if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
287
288         if (tracker == null) tracker = new Hash();
289         else tracker.clear();
290
291         if (objects == null) objects = new Vec();
292         else objects.setSize(0);
293
294         final String content = send(args, http);
295         if (Log.verbose) {
296             String s;
297             BufferedReader br2 = new BufferedReader(new StringReader(content));
298             while ((s = br2.readLine()) != null) Log.log(this, "send: " + s);
299         }
300
301         InputStream is = http.POST("text/xml", content);
302         try {
303             BufferedReader br = !Log.verbose ?
304                 new BufferedReader(new InputStreamReader(is)) :
305                 new BufferedReader(new FilterReader(new InputStreamReader(is)) {
306                         public int read() throws IOException {
307                             int i = super.read();
308                             if (Log.on) Log.log(this, "recv: " + ((char)i));
309                             return i;
310                         }
311                         public int read(char[] c, int off, int len) throws IOException {
312                             int ret = super.read(c, off, len);
313                             if (ret == -1) return ret;
314                             String s;
315                             BufferedReader br2 = new BufferedReader(new StringReader(new String(c, off, ret)));
316                             while ((s = br2.readLine()) != null) Log.log(this, "recv: " + s);
317                             return ret;
318                         }
319                     });
320             return null;
321         } finally {
322             is.close();
323         }
324     }
325
326     protected String send(JSArray args, HTTP http) throws JS.Exn, IOException {
327         StringBuffer content = new StringBuffer();
328         content.append("\r\n");
329         content.append("<?xml version=\"1.0\"?>\n");
330         content.append("    <methodCall>\n");
331         content.append("        <methodName>");
332         content.append(methodname);
333         content.append("</methodName>\n");
334         content.append("        <params>\n");
335         for(int i=0; i<args.length(); i++) {
336             content.append("            <param>\n");
337             appendObject(args.elementAt(i), content);
338             content.append("            </param>\n");
339         }
340         content.append("        </params>\n");
341         content.append("    </methodCall>");
342         return content.toString();
343     }
344         
345     protected Object recieve(BufferedReader br) throws JS.Exn, IOException {
346         // parse XML reply
347         try {
348             new Helper().parse(br);
349         } catch (XML.XMLException e) {
350             if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
351             throw new JS.Exn("reply from server was not well-formed XML: " + e);
352         }
353         
354         if (fault) throw new JS.Exn(objects.elementAt(0));
355         if (objects.size() == 0) return null;
356         return objects.elementAt(0);
357     }
358
359     public final Object call(final JSArray args) throws JS.Exn {
360         final Callback callback = JSContext.pause();
361         new java.lang.Thread() {
362             public void run() {
363                 try {
364                     final Object ret = call_(args);
365                     Scheduler.add(new Scheduler.Task() { public void perform() { callback.call(ret); } });
366                 } catch (IOException se) {
367                     if (Log.on) Log.log(this, se);
368                     throw new JS.Exn("socket exception: " + se);
369                 }
370         } }.start();
371         return null;
372     }
373
374     /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
375     public Object get(Object name) {
376         return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name.toString(), http);
377     }
378
379     public XMLRPC(String url, String methodname) {
380         this(url, methodname, new HTTP(url));
381     }
382
383     public XMLRPC(String url, String methodname, HTTP http) {
384         this.http = http;
385         this.url = url;
386         this.methodname = methodname;
387     }
388
389
390     // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
391
392     /** CharArrayWriter that lets us touch its buffer */
393     protected static class AccessibleCharArrayWriter extends CharArrayWriter {
394         public char[] getBuf() { return buf; }
395         public AccessibleCharArrayWriter(int i) { super(i); }
396     }
397
398 }