2002/06/05 19:54:01
[org.ibex.core.git] / src / org / xwt / XMLRPC.java
1 // Copyright 2002 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.mozilla.javascript.*;
8 import org.xwt.util.*;
9 import org.bouncycastle.util.encoders.Base64;
10
11 /**
12  *  An XML-RPC client implemented as a Rhino JavaScript Host
13  *  Object. See the 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 XML implements Function {
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 object stack. As we process xml elements, pieces of the
45      *  return value are pushed onto and popped off of this stack.
46      *
47      *  The general protocol is that any time a &lt;value&gt; tag is
48      *  encountered, an empty String ("") is pushed onto the stack. If
49      *  the &lt;value/&gt; node has content (either an anonymous
50      *  string or some other XML node), that content replaces the
51      *  empty string.
52      *
53      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
54      *  stack. When a &lt;/data&gt; is encountered, we search back on the
55      *  stack to the last null, replace it with a NativeArray, and
56      *  insert into it all elements above it on the stack.
57      *
58      *  If a &lt;struct&gt; tag is encountered, a JSObject is pushed
59      *  onto the stack. If a &lt;name&gt; tag is encountered, its CDATA is
60      *  pushed onto the stack. When a &lt;/member&gt; is encountered, the
61      *  name (second element on stack) and value (top of stack) are
62      *  popped off the stack and inserted into the struct (third
63      *  element on stack).
64      */
65     protected Vec objects = null;
66
67     /** used to detect multi-ref data */
68     private Hash tracker;
69
70     /** True iff the return value is a fault (and should be thrown as an exception) */
71     protected boolean fault = false;
72
73
74     // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
75
76     public void startElement(String name, String[] keys, Object[] vals, int line, int col) {
77         if (name.equals("fault")) fault = true;
78         else if (name.equals("struct")) objects.setElementAt(new JSObject(false), objects.size() - 1);
79         else if (name.equals("array")) objects.setElementAt(null, objects.size() - 1);
80         else if (name.equals("value")) objects.addElement("");
81     }
82
83     public void endElement(String name, int line, int col) {
84
85         if (name.equals("int") || name.equals("i4"))
86             objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
87
88         else if (name.equals("boolean"))
89             objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
90
91         else if (name.equals("string"))
92             objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
93
94         else if (name.equals("double"))
95             objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
96
97         else if (name.equals("base64"))
98             objects.setElementAt(new ByteStream(Base64.decode(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
99
100         else if (name.equals("name"))
101             objects.addElement(new String(content.getBuf(), 0, content.size()));
102
103         else if (name.equals("value") && "".equals(objects.lastElement()))
104             objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
105
106         else if (name.equals("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                 NativeDate nd = (NativeDate)Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date");
116                 double date = NativeDate.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.jsFunction_setTime(NativeDate.internalUTC(date));
125                 objects.setElementAt(nd, objects.size() - 1);
126
127             } catch (Exception e) {
128                 if (Log.on) Log.log(this, "error parsing date : " + s);
129                 if (Log.on) Log.log(this, e);
130             }
131
132         } else if (name.equals("member")) {
133             Object memberValue = objects.elementAt(objects.size() - 1);
134             String memberName = (String)objects.elementAt(objects.size() - 2);
135             Scriptable struct = (Scriptable)objects.elementAt(objects.size() - 3);
136             struct.put(memberName, struct, memberValue);
137             objects.setSize(objects.size() - 2);
138
139         } else if (name.equals("data")) {
140             int i;
141             for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
142             Object[] arr = new Object[objects.size() - i - 1];
143             for(int j = i + 1; j<objects.size(); j++) arr[j - i - 1] = objects.elementAt(j);
144             objects.setElementAt(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, arr), i);
145             objects.setSize(i + 1);
146
147         }
148
149         content.reset();
150     }
151
152     public void content(char[] ch, int start, int length, int line, int col) {
153         try { content.write(ch, start, length); }
154         catch (Exception e) { 
155             if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
156             if (Log.on) Log.log(this, e);
157         }
158     }
159
160
161     // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
162
163     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
164     void appendObject(Object o, StringBuffer sb) throws JavaScriptException {
165
166         if (o == null) {
167             throw new JavaScriptException("attempted to send a null value via XML-RPC");
168
169         } else if (o instanceof Number) {
170             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
171                 sb.append("                <value><i4>");
172                 sb.append(((Number)o).intValue());
173                 sb.append("</i4></value>\n");
174             } else {
175                 sb.append("                <value><double>");
176                 sb.append(o);
177                 sb.append("</double></value>\n");
178             }
179
180         } else if (o instanceof Boolean) {
181             sb.append("                <value><boolean>");
182             sb.append(((Boolean)o).booleanValue() ? "1" : "0");
183             sb.append("</boolean></value>\n");
184
185         } else if (o instanceof ByteStream) {
186             try {
187                 sb.append("                <value><base64>\n");
188                 InputStream is = ((ByteStream)o).getInputStream();
189                 byte[] buf = new byte[54];
190                 while(true) {
191                     int numread = is.read(buf, 0, 54);
192                     if (numread == -1) break;
193                     byte[] writebuf = buf;
194                     if (numread < buf.length) {
195                         writebuf = new byte[numread];
196                         System.arraycopy(buf, 0, writebuf, 0, numread);
197                     }
198                     sb.append("              ");
199                     sb.append(new String(Base64.encode(writebuf)));
200                     sb.append("\n");
201                 }
202                 sb.append("\n              </base64></value>\n");
203             } catch (IOException e) {
204                 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
205                 if (Log.on) Log.log(this, e);
206                 throw new JavaScriptException("caught IOException while attempting to send a ByteStream via XML-RPC");
207             }
208
209         } else if (o instanceof String) {
210             sb.append("                <value><string>");
211             String s = (String)o;
212             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
213                 sb.append(s);
214             } else {
215                 char[] cbuf = s.toCharArray();
216                 int oldi = 0, i=0;
217                 while(true) {
218                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
219                     sb.append(cbuf, oldi, i - oldi);
220                     if (i >= cbuf.length) break;
221                     if (cbuf[i] == '<') sb.append("&lt;");
222                     else if (cbuf[i] == '&') sb.append("&amp;");
223                     i = oldi = i + 1;
224                     if (i >= cbuf.length) break;
225                 }
226             }
227             sb.append("</string></value>\n");
228
229         } else if (o instanceof NativeArray) {
230             if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
231             tracker.put(o, Boolean.TRUE);
232             sb.append("                <value><array><data>\n");
233             NativeArray na = (NativeArray)o;
234             for(int i=0; i<na.jsGet_length(); i++)
235                 appendObject(na.get(i, na), sb);
236             sb.append("                </data></array></value>\n");
237
238         } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
239             if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
240             tracker.put(o, Boolean.TRUE);
241             Scriptable s = (Scriptable)o;
242             sb.append("                <value><struct>\n");
243             Object[] ids = s.getIds();
244             for(int i=0; i<ids.length; i++) {
245                 sb.append("                <member><name>" + ids[i] + "</name>\n");
246                 appendObject(s.get(ids[i].toString(), s), sb);
247                 sb.append("                </member>\n");
248             }
249             sb.append("                </struct></value>\n");
250
251         } else {
252             throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
253
254         }
255     }
256
257     // this is synchronized in case multiple threads try to make a call on the same object... in the future, change this
258     // behavior to use pipelining.
259     public synchronized Object call(Object[] args) throws JavaScriptException, IOException {
260         if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
261
262         if (tracker == null) tracker = new Hash();
263         else tracker.clear();
264
265         if (objects == null) objects = new Vec();
266         else objects.setSize(0);
267
268         HTTP http = new HTTP(url);
269         String content = send(args, http);
270         OutputStream os = new BufferedOutputStream(http.getOutputStream(content.length(), "text/xml"), 4000);
271         PrintWriter ps = !Log.verbose ?
272             new PrintWriter(os) :
273             new PrintWriter(new FilterWriter(new OutputStreamWriter(os)) {
274                     public void write(int i) throws IOException {
275                         super.write(i);
276                         if (Log.on) Log.log(this, "send: " + ((char)i));
277                     }
278                     public void write(String s, int start, int len) throws IOException {
279                         super.write(s, start, len);
280                         if (Log.on) Log.log(this, "send: " + s.substring(start, start + len));
281                     }
282                     public void write(char[] c, int start, int len) throws IOException {
283                         super.write(c, start, len);
284                         if (Log.on) Log.log(this, "send: " + new String(c, start, len));
285                     }
286                 });
287         ps.print(content.toString());
288         ps.flush();
289         
290         BufferedReader br = !Log.verbose ?
291             new BufferedReader(new InputStreamReader(new Filter(http.getInputStream()))) :
292             new BufferedReader(new FilterReader(new InputStreamReader(new Filter(http.getInputStream()))) {
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                     if (Log.on) Log.log(this, "recv: " + new String(c, off, ret));
302                     return ret;
303                 }
304             });
305         return recieve(br);
306     }
307
308     protected String send(Object[] args, HTTP http) throws JavaScriptException, IOException {
309         StringBuffer content = new StringBuffer();
310         content.append("<?xml version=\"1.0\"?>\n");
311         content.append("    <methodCall>\n");
312         content.append("        <methodName>");
313         content.append(methodname);
314         content.append("</methodName>\n");
315         if (args.length > 0) {
316             content.append("        <params>\n");
317             for(int i=0; i<args.length; i++) {
318                 content.append("            <param>\n");
319                 appendObject(args[i], content);
320                 content.append("            </param>\n");
321             }
322             content.append("        </params>\n");
323         }
324         content.append("    </methodCall>");
325         return content.toString();
326     }
327         
328     protected Object recieve(BufferedReader br) throws JavaScriptException, IOException {
329         // parse XML reply
330         try {
331             parse(br);
332         } catch (XML.SAXException e) {
333             if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
334             throw new JavaScriptException("reply from server was not well-formed XML: " + e);
335         }
336         
337         if (fault) throw new JavaScriptException(objects.elementAt(0));
338         if (objects.size() == 0) return null;
339         return objects.elementAt(0);
340     }
341
342     public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
343
344         if (!ThreadMessage.suspendThread()) return null;
345
346         try {
347             return call(args);
348         } catch (IOException se) {
349             if (Log.on) Log.log(this, se);
350             if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
351             throw new JavaScriptException("socket exception: " + se);
352
353         } catch (JavaScriptException jse) {
354             Object val = jse.getValue();
355             if (val instanceof String) {
356                 if (Log.on) Log.log(this, val.toString());
357                 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
358             }
359             throw jse;
360         } finally {
361             ThreadMessage.resumeThread();
362         }
363
364     }
365
366     /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
367     public Object get(String name, Scriptable start) {
368         return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name);
369     }
370
371     public XMLRPC(String url, String methodname) {
372         this.url = url;
373         this.methodname = methodname;
374     }
375
376
377     // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
378
379     /** CharArrayWriter that lets us touch its buffer */
380     protected static class AccessibleCharArrayWriter extends CharArrayWriter {
381         public char[] getBuf() { return buf; }
382         public AccessibleCharArrayWriter(int i) { super(i); }
383     }
384
385     /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
386     private static class Filter extends FilterInputStream {
387         public Filter(InputStream is) { super(is); }
388         public int read() throws IOException {
389             Thread.yield();
390             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
391             return super.read();
392         }
393         public int read(byte[] b) throws IOException {
394             Thread.yield();
395             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
396             return super.read(b);
397         }
398         public int read(byte[] b, int i, int j) throws IOException {
399             Thread.yield();
400             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
401             return super.read(b, i, j);
402         }
403     }
404
405
406     // Methods Required by Rhino ////////////////////////////////////////////////////////
407
408     public String getClassName() { return "XMLRPC"; }
409     public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
410     public void delete(String name) { }
411     public Scriptable getParentScope() { return null; }
412     public void setParentScope(Scriptable p) { }
413     public boolean hasInstance(Scriptable value) { return false; }
414     public Scriptable getPrototype() { return null; }
415     public void setPrototype(Scriptable p) { }
416     public void delete(int i) { }
417     public Object getDefaultValue(Class hint) { return "XML-RPC"; }
418     public void put(int i, Scriptable start, Object value) { }
419     public Object get(int i, Scriptable start) { return null; }
420     public void put(String name, Scriptable start, Object value) { }
421     public boolean has(String name, Scriptable start) { return true; }
422     public boolean has(int i, Scriptable start) { return false; }
423     public Object[] getIds() { return new Object[] { }; }
424
425 }