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