274b5ef84b21277c767ef66e5213ce58ea6f6161
[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 String(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 String) {
186             sb.append("                <value><string>");
187             String s = (String)o;
188             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
189                 sb.append(s);
190             } else {
191                 char[] cbuf = s.toCharArray();
192                 int oldi = 0, i=0;
193                 while(true) {
194                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
195                     sb.append(cbuf, oldi, i - oldi);
196                     if (i >= cbuf.length) break;
197                     if (cbuf[i] == '<') sb.append("&lt;");
198                     else if (cbuf[i] == '&') sb.append("&amp;");
199                     i = oldi = i + 1;
200                     if (i >= cbuf.length) break;
201                 }
202             }
203             sb.append("</string></value>\n");
204
205         } else if (o instanceof NativeArray) {
206             if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
207             tracker.put(o, Boolean.TRUE);
208             sb.append("                <value><array><data>\n");
209             NativeArray na = (NativeArray)o;
210             for(int i=0; i<na.jsGet_length(); i++)
211                 appendObject(na.get(i, na), sb);
212             sb.append("                </data></array></value>\n");
213
214         } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
215             if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
216             tracker.put(o, Boolean.TRUE);
217             Scriptable s = (Scriptable)o;
218             sb.append("                <value><struct>\n");
219             Object[] ids = s.getIds();
220             for(int i=0; i<ids.length; i++) {
221                 sb.append("                <member><name>" + ids[i] + "</name>\n");
222                 appendObject(s.get(ids[i].toString(), s), sb);
223                 sb.append("                </member>\n");
224             }
225             sb.append("                </struct></value>\n");
226
227         } else {
228             throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
229
230         }
231     }
232
233     public Object call(Object[] args) throws JavaScriptException, IOException {
234         if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
235
236         if (tracker == null) tracker = new Hash();
237         else tracker.clear();
238
239         if (objects == null) objects = new Vec();
240         else objects.setSize(0);
241
242         HTTP http = new HTTP(url);
243         String content = send(args, http);
244         OutputStream os = new BufferedOutputStream(http.getOutputStream(content.length(), "text/xml"), 4000);
245         PrintWriter ps = !Log.verbose ?
246             new PrintWriter(os) :
247             new PrintWriter(new FilterWriter(new OutputStreamWriter(os)) {
248                     public void write(int i) throws IOException {
249                         super.write(i);
250                         if (Log.on) Log.log(this, "send: " + ((char)i));
251                     }
252                     public void write(String s, int start, int len) throws IOException {
253                         super.write(s, start, len);
254                         if (Log.on) Log.log(this, "send: " + s.substring(start, start + len));
255                     }
256                     public void write(char[] c, int start, int len) throws IOException {
257                         super.write(c, start, len);
258                         if (Log.on) Log.log(this, "send: " + new String(c, start, len));
259                     }
260                 });
261         ps.print(content.toString());
262         ps.flush();
263         
264         BufferedReader br = !Log.verbose ?
265             new BufferedReader(new InputStreamReader(new Filter(http.getInputStream()))) :
266             new BufferedReader(new FilterReader(new InputStreamReader(new Filter(http.getInputStream()))) {
267                 public int read() throws IOException {
268                     int i = super.read();
269                     System.out.println("X " + i);
270                     if (Log.on) Log.log(this, "recv: " + ((char)i));
271                     return i;
272                 }
273                 public int read(char[] c, int off, int len) throws IOException {
274                     int ret = super.read(c, off, len);
275                     System.out.println("Y " + ret);
276                     if (ret == -1) return ret;
277                     if (Log.on) Log.log(this, "recv: " + new String(c, off, ret));
278                     return ret;
279                 }
280             });
281         return recieve(br);
282     }
283
284     protected String send(Object[] args, HTTP http) throws JavaScriptException, IOException {
285         StringBuffer content = new StringBuffer();
286         content.append("<?xml version=\"1.0\"?>\n");
287         content.append("    <methodCall>\n");
288         content.append("        <methodName>");
289         content.append(methodname);
290         content.append("</methodName>\n");
291         if (args.length > 0) {
292             content.append("        <params>\n");
293             for(int i=0; i<args.length; i++) {
294                 content.append("            <param>\n");
295                 appendObject(args[i], content);
296                 content.append("            </param>\n");
297             }
298             content.append("        </params>\n");
299         }
300         content.append("    </methodCall>");
301         return content.toString();
302     }
303         
304     protected Object recieve(BufferedReader br) throws JavaScriptException, IOException {
305         // parse XML reply
306         try {
307             parse(br);
308         } catch (XML.SAXException e) {
309             if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
310             throw new JavaScriptException("reply from server was not well-formed XML: " + e);
311         }
312         
313         if (fault) throw new JavaScriptException(objects.elementAt(0));
314         if (objects.size() == 0) return null;
315         return objects.elementAt(0);
316     }
317
318     public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
319
320         // put ourselves in the background
321         Thread thread = Thread.currentThread();
322         if (!(thread instanceof ThreadMessage)) {
323             if (Log.on) Log.log(this, "RPC calls may only be made from background threads");
324             return null;
325         }
326         ThreadMessage mythread = (ThreadMessage)thread;
327         mythread.setPriority(Thread.MIN_PRIORITY);
328         mythread.done.release();
329
330         try {
331             return call(args);
332
333         } catch (IOException se) {
334             if (Log.on) Log.log(this, se);
335             if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
336             throw new JavaScriptException("socket exception: " + se);
337
338         } catch (JavaScriptException jse) {
339             Object val = jse.getValue();
340             if (val instanceof String) {
341                 if (Log.on) Log.log(this, val.toString());
342                 if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
343             }
344             throw jse;
345
346         } finally {
347             // okay, let ourselves be brought to the foreground
348             MessageQueue.add(mythread);
349             mythread.setPriority(Thread.NORM_PRIORITY);
350             mythread.go.block();
351         }
352
353     }
354
355     /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
356     public Object get(String name, Scriptable start) {
357         return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name);
358     }
359
360     public XMLRPC(String url, String methodname) {
361         this.url = url;
362         this.methodname = methodname;
363     }
364
365
366     // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
367
368     /** CharArrayWriter that lets us touch its buffer */
369     protected static class AccessibleCharArrayWriter extends CharArrayWriter {
370         public char[] getBuf() { return buf; }
371         public AccessibleCharArrayWriter(int i) { super(i); }
372     }
373
374     /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
375     private static class Filter extends FilterInputStream {
376         public Filter(InputStream is) { super(is); }
377         public int read() throws IOException {
378             Thread.yield();
379             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
380             return super.read();
381         }
382         public int read(byte[] b) throws IOException {
383             Thread.yield();
384             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
385             return super.read(b);
386         }
387         public int read(byte[] b, int i, int j) throws IOException {
388             Thread.yield();
389             while(MessageQueue.working) try { Thread.sleep(100); } catch (Exception e) { };
390             return super.read(b, i, j);
391         }
392     }
393
394
395     // Methods Required by Rhino ////////////////////////////////////////////////////////
396
397     public String getClassName() { return "XMLRPC"; }
398     public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
399     public void delete(String name) { }
400     public Scriptable getParentScope() { return null; }
401     public void setParentScope(Scriptable p) { }
402     public boolean hasInstance(Scriptable value) { return false; }
403     public Scriptable getPrototype() { return null; }
404     public void setPrototype(Scriptable p) { }
405     public void delete(int i) { }
406     public Object getDefaultValue(Class hint) { return "XML-RPC"; }
407     public void put(int i, Scriptable start, Object value) { }
408     public Object get(int i, Scriptable start) { return null; }
409     public void put(String name, Scriptable start, Object value) { }
410     public boolean has(String name, Scriptable start) { return true; }
411     public boolean has(int i, Scriptable start) { return false; }
412     public Object[] getIds() { return new Object[] { }; }
413
414 }