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