2003/09/26 07:09:55
[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 JS.Callable {
34
35     public Object[] keys() { throw new Error("not implemented"); }
36
37     /** the url to connect to */
38     protected String url = null;
39
40     /** the method name to invoke on the remove server */
41     protected String methodname = null;
42
43     /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
44     protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
45
46     /** the HTTP connection to use */
47     protected HTTP http = null;
48
49     /** The object stack. As we process xml elements, pieces of the
50      *  return value are pushed onto and popped off of this stack.
51      *
52      *  The general protocol is that any time a &lt;value&gt; tag is
53      *  encountered, an empty String ("") is pushed onto the stack. If
54      *  the &lt;value/&gt; node has content (either an anonymous
55      *  string or some other XML node), that content replaces the
56      *  empty string.
57      *
58      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
59      *  stack. When a &lt;/data&gt; is encountered, we search back on the
60      *  stack to the last null, replace it with a NativeJS.Array, and
61      *  insert into it all elements above it on the stack.
62      *
63      *  If a &lt;struct&gt; tag is encountered, a JSObject is pushed
64      *  onto the stack. If a &lt;name&gt; tag is encountered, its CDATA is
65      *  pushed onto the stack. When a &lt;/member&gt; is encountered, the
66      *  name (second element on stack) and value (top of stack) are
67      *  popped off the stack and inserted into the struct (third
68      *  element on stack).
69      */
70     protected Vec objects = null;
71
72     /** used to detect multi-ref data */
73     private Hash tracker;
74
75     /** True iff the return value is a fault (and should be thrown as an exception) */
76     protected boolean fault = false;
77
78
79     // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
80
81     private class Helper extends XML {
82         public Helper() { super(BUFFER_SIZE); }
83
84         public void startElement(XML.Element c) {
85             content.reset();
86             if (c.localName.equals("fault")) fault = true;
87             else if (c.localName.equals("struct")) objects.setElementAt(new JS.Obj(), objects.size() - 1);
88             else if (c.localName.equals("array")) objects.setElementAt(null, objects.size() - 1);
89             else if (c.localName.equals("value")) objects.addElement("");
90         }
91         
92         public void endElement(XML.Element c) {
93             
94             if (c.localName.equals("int") || c.localName.equals("i4"))
95                 objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
96             
97             else if (c.localName.equals("boolean"))
98                 objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
99             
100             else if (c.localName.equals("string"))
101                 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
102             
103             else if (c.localName.equals("double"))
104                 objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
105             
106             else if (c.localName.equals("base64"))
107                 objects.setElementAt(new Res.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size()))), objects.size() - 1);
108
109             else if (c.localName.equals("name"))
110                 objects.addElement(new String(content.getBuf(), 0, content.size()));
111             
112             else if (c.localName.equals("value") && "".equals(objects.lastElement()))
113                 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
114             
115             else if (c.localName.equals("dateTime.iso8601")) {
116                 String s = new String(content.getBuf(), 0, content.size());
117                 
118                 // strip whitespace
119                 int i=0;
120                 while(Character.isWhitespace(s.charAt(i))) i++;
121                 if (i > 0) s = s.substring(i);
122                 
123                 try {
124                     org.xwt.js.Date nd = new org.xwt.js.Date();
125                     double date = org.xwt.js.Date.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
126                                                                     Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
127                                                                     Double.valueOf(s.substring(6, 8)).doubleValue(),
128                                                                     Double.valueOf(s.substring(9, 11)).doubleValue(),
129                                                                     Double.valueOf(s.substring(12, 14)).doubleValue(),
130                                                                     Double.valueOf(s.substring(15, 17)).doubleValue(),
131                                                                     (double)0
132                                                                     );
133                     nd.jsFunction_setTime(org.xwt.js.Date.internalUTC(date));
134                     objects.setElementAt(nd, objects.size() - 1);
135                     
136                 } catch (Exception e) {
137                     if (Log.on) Log.log(this, "error parsing date : " + s);
138                     if (Log.on) Log.log(this, e);
139                 }
140                 
141             } else if (c.localName.equals("member")) {
142                 Object memberValue = objects.elementAt(objects.size() - 1);
143                 String memberName = (String)objects.elementAt(objects.size() - 2);
144                 JS struct = (JS)objects.elementAt(objects.size() - 3);
145                 struct.put(memberName, memberValue);
146                 objects.setSize(objects.size() - 2);
147                 
148             } else if (c.localName.equals("data")) {
149                 int i;
150                 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
151                 JS.Array arr = new JS.Array();
152                 for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
153                 objects.setElementAt(arr, i);
154                 objects.setSize(i + 1);
155                 
156             }
157             
158             content.reset();
159         }
160         
161         public void characters(char[] ch, int start, int length) {
162             try { content.write(ch, start, length); }
163             catch (Exception e) { 
164                 if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
165                 if (Log.on) Log.log(this, e);
166             }
167         }
168         
169         public void whitespace(char[] ch, int start, int length) {}
170     }
171
172     // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
173
174     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
175     void appendObject(Object o, StringBuffer sb) throws JS.Exn {
176
177         if (o == null) {
178             throw new JS.Exn("attempted to send a null value via XML-RPC");
179
180         } else if (o instanceof Number) {
181             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
182                 sb.append("                <value><i4>");
183                 sb.append(((Number)o).intValue());
184                 sb.append("</i4></value>\n");
185             } else {
186                 sb.append("                <value><double>");
187                 sb.append(o);
188                 sb.append("</double></value>\n");
189             }
190
191         } else if (o instanceof Boolean) {
192             sb.append("                <value><boolean>");
193             sb.append(((Boolean)o).booleanValue() ? "1" : "0");
194             sb.append("</boolean></value>\n");
195
196         } else if (o instanceof Res) {
197             try {
198                 sb.append("                <value><base64>\n");
199                 InputStream is = ((Res)o).getInputStream();
200                 byte[] buf = new byte[54];
201                 while(true) {
202                     int numread = is.read(buf, 0, 54);
203                     if (numread == -1) break;
204                     byte[] writebuf = buf;
205                     if (numread < buf.length) {
206                         writebuf = new byte[numread];
207                         System.arraycopy(buf, 0, writebuf, 0, numread);
208                     }
209                     sb.append("              ");
210                     sb.append(new String(Base64.encode(writebuf)));
211                     sb.append("\n");
212                 }
213                 sb.append("\n              </base64></value>\n");
214             } catch (IOException e) {
215                 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
216                 if (Log.on) Log.log(this, e);
217                 throw new JS.Exn("caught IOException while attempting to send a ByteStream via XML-RPC");
218             }
219
220         } else if (o instanceof String) {
221             sb.append("                <value><string>");
222             String s = (String)o;
223             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
224                 sb.append(s);
225             } else {
226                 char[] cbuf = s.toCharArray();
227                 int oldi = 0, i=0;
228                 while(true) {
229                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
230                     sb.append(cbuf, oldi, i - oldi);
231                     if (i >= cbuf.length) break;
232                     if (cbuf[i] == '<') sb.append("&lt;");
233                     else if (cbuf[i] == '&') sb.append("&amp;");
234                     i = oldi = i + 1;
235                     if (i >= cbuf.length) break;
236                 }
237             }
238             sb.append("</string></value>\n");
239
240         } else if (o instanceof org.xwt.js.Date) {
241             sb.append("                <value><dateTime.iso8601>");
242             java.util.Date d = new java.util.Date(((org.xwt.js.Date)o).getRawTime());
243             sb.append(d.getYear() + 1900);
244             if (d.getMonth() + 1 < 10) sb.append('0');
245             sb.append(d.getMonth() + 1);
246             if (d.getDate() < 10) sb.append('0');
247             sb.append(d.getDate());
248             sb.append('T');
249             if (d.getHours() < 10) sb.append('0');
250             sb.append(d.getHours());
251             sb.append(':');
252             if (d.getMinutes() < 10) sb.append('0');
253             sb.append(d.getMinutes());
254             sb.append(':');
255             if (d.getSeconds() < 10) sb.append('0');
256             sb.append(d.getSeconds());
257             sb.append("</dateTime.iso8601></value>\n");
258
259         } else if (o instanceof JS.Array) {
260             if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
261             tracker.put(o, Boolean.TRUE);
262             sb.append("                <value><array><data>\n");
263             JS.Array a = (JS.Array)o;
264             for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
265             sb.append("                </data></array></value>\n");
266
267         } else if (o instanceof JS) {
268             if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
269             tracker.put(o, Boolean.TRUE);
270             JS j = (JS)o;
271             sb.append("                <value><struct>\n");
272             Object[] ids = j.keys();
273             for(int i=0; i<ids.length; i++) {
274                 sb.append("                <member><name>" + ids[i] + "</name>\n");
275                 appendObject(j.get(ids[i].toString()), sb);
276                 sb.append("                </member>\n");
277             }
278             sb.append("                </struct></value>\n");
279
280         } else {
281             throw new JS.Exn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
282
283         }
284     }
285
286     // this is synchronized in case multiple threads try to make a call on the same object... in the future, change this
287     // behavior to use pipelining.
288     public synchronized Object call2(JS.Array args) throws JS.Exn, IOException {
289         if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
290
291         if (tracker == null) tracker = new Hash();
292         else tracker.clear();
293
294         if (objects == null) objects = new Vec();
295         else objects.setSize(0);
296
297         String content = send(args, http);
298         if (Log.verbose) {
299             String s;
300             BufferedReader br2 = new BufferedReader(new StringReader(content));
301             while ((s = br2.readLine()) != null) Log.log(this, "send: " + s);
302         }
303
304         InputStream is = http.POST("text/xml", content);
305         try {
306             BufferedReader br = !Log.verbose ?
307                 new BufferedReader(new InputStreamReader(new Filter(is))) :
308                 new BufferedReader(new FilterReader(new InputStreamReader(new Filter(is))) {
309                         public int read() throws IOException {
310                             int i = super.read();
311                             if (Log.on) Log.log(this, "recv: " + ((char)i));
312                             return i;
313                         }
314                         public int read(char[] c, int off, int len) throws IOException {
315                             int ret = super.read(c, off, len);
316                             if (ret == -1) return ret;
317                             String s;
318                             BufferedReader br2 = new BufferedReader(new StringReader(new String(c, off, ret)));
319                             while ((s = br2.readLine()) != null) Log.log(this, "recv: " + s);
320                             return ret;
321                         }
322                     });
323             return recieve(br);
324         } finally {
325             is.close();
326         }
327     }
328
329     protected String send(JS.Array args, HTTP http) throws JS.Exn, IOException {
330         StringBuffer content = new StringBuffer();
331         content.append("\r\n");
332         content.append("<?xml version=\"1.0\"?>\n");
333         content.append("    <methodCall>\n");
334         content.append("        <methodName>");
335         content.append(methodname);
336         content.append("</methodName>\n");
337         content.append("        <params>\n");
338         for(int i=0; i<args.length(); i++) {
339             content.append("            <param>\n");
340             appendObject(args.elementAt(i), content);
341             content.append("            </param>\n");
342         }
343         content.append("        </params>\n");
344         content.append("    </methodCall>");
345         return content.toString();
346     }
347         
348     protected Object recieve(BufferedReader br) throws JS.Exn, IOException {
349         // parse XML reply
350         try {
351             new Helper().parse(br);
352         } catch (XML.XMLException e) {
353             if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
354             throw new JS.Exn("reply from server was not well-formed XML: " + e);
355         }
356         
357         if (fault) throw new JS.Exn(objects.elementAt(0));
358         if (objects.size() == 0) return null;
359         return objects.elementAt(0);
360     }
361
362     public final Object call(JS.Array args) throws JS.Exn {
363
364         if (!ThreadMessage.suspendThread()) return null;
365
366         try {
367             return call2(args);
368         } catch (IOException se) {
369             if (Log.on) Log.log(this, se);
370             throw new JS.Exn("socket exception: " + se);
371
372         } catch (JS.Exn jse) {
373             if (Log.on) Log.log(this, jse.toString());
374             throw jse;
375         } finally {
376             ThreadMessage.resumeThread();
377         }
378
379     }
380
381     /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
382     public Object get(Object name) {
383         return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name.toString(), http);
384     }
385
386     public XMLRPC(String url, String methodname) {
387         this(url, methodname, new HTTP(url));
388     }
389
390     public XMLRPC(String url, String methodname, HTTP http) {
391         this.http = http;
392         this.url = url;
393         this.methodname = methodname;
394     }
395
396
397     // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
398
399     /** CharArrayWriter that lets us touch its buffer */
400     protected static class AccessibleCharArrayWriter extends CharArrayWriter {
401         public char[] getBuf() { return buf; }
402         public AccessibleCharArrayWriter(int i) { super(i); }
403     }
404
405     /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
406     private static class Filter extends FilterInputStream {
407         public Filter(InputStream is) { super(is); }
408         public int read() throws IOException {
409             java.lang.Thread.yield();
410             while(Message.Q.nonThreadEventsInQueue > 0) try { java.lang.Thread.sleep(100); } catch (Exception e) { };
411             return super.read();
412         }
413         public int read(byte[] b) throws IOException {
414             java.lang.Thread.yield();
415             while(Message.Q.nonThreadEventsInQueue > 0) try { java.lang.Thread.sleep(100); } catch (Exception e) { };
416             return super.read(b);
417         }
418         public int read(byte[] b, int i, int j) throws IOException {
419             java.lang.Thread.yield();
420             while(Message.Q.nonThreadEventsInQueue > 0) try { java.lang.Thread.sleep(100); } catch (Exception e) { };
421             return super.read(b, i, j);
422         }
423     }
424
425 }