mass rename and rebranding from xwt to ibex - fixed to use ixt files
[org.ibex.core.git] / src / org / ibex / XMLRPC.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex;
3
4 import java.io.*;
5 import java.util.*;
6 import org.ibex.js.*;
7 import org.ibex.util.*;
8 import org.bouncycastle.util.encoders.Base64;
9
10 /**
11  *  An XML-RPC client implemented as a JavaScript Host Object. See the
12  *  Ibex spec for information on its behavior.
13  *
14  *  NOTE: this client is EXTREMELY lenient in the responses it will
15  *  accept; there are many, many invalid responses that it will
16  *  successfully parse and return. Do NOT use this to determine the
17  *  validity of your server.
18  *
19  *  This client conforms to <a href="http://www.xmlrpc.com/spec">The
20  *  XML-RPC Spec</a>, subject to these limitations:
21  *  <ol>
22  *    <li> XMLRPC cannot invoke methods that require a <base64/> argument
23  *    <li> if a return value contains a <base64/>, it will be returned as a string
24  *    <li> The decision to pass a number as <i4/> or <double/> is based
25  *         entirely on whether or not the argument is fractional. Thus, it
26  *         is impossible to pass a non-fractional number to an xmlrpc
27  *         method that insists on being called with a <double/> element. We
28  *         hope that most xml-rpc servers will be able to automatically
29  *         convert.
30  *  </ol>
31  */
32 class XMLRPC extends JS {
33
34     public XMLRPC(String url, String method) { this(url, method, new HTTP(url)); }
35     public XMLRPC(String url, String method, HTTP http) { this.http = http; this.url = url; this.method = method; }
36     public Object get(Object name) { return new XMLRPC(url, (method.equals("") ? "" : method + ".") + name.toString(), http); }
37
38
39     /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
40     protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
41     protected String url = null;         ///< the url to connect to
42     protected String method = null;      ///< the method name to invoke on the remove server
43     protected HTTP http = null;          ///< the HTTP connection to use
44     private Hash tracker;                ///< used to detect multi-ref data
45     protected boolean fault = false;     ///< True iff the return value is a fault (and should be thrown as an exception)
46
47
48     /** The object stack. As we process xml elements, pieces of the
49      *  return value are pushed onto and popped off of this stack.
50      *
51      *  The general protocol is that any time a &lt;value&gt; tag is
52      *  encountered, an empty String ("") is pushed onto the stack. If
53      *  the &lt;value/&gt; node has content (either an anonymous
54      *  string or some other XML node), that content replaces the
55      *  empty string.
56      *
57      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
58      *  stack. When a &lt;/data&gt; is encountered, we search back on the
59      *  stack to the last null, replace it with a NativeJSArray, and
60      *  insert into it all elements above it on the stack.
61      *
62      *  If a &lt;struct&gt; tag is encountered, a JSect is pushed
63      *  onto the stack. If a &lt;name&gt; tag is encountered, its CDATA is
64      *  pushed onto the stack. When a &lt;/member&gt; is encountered, the
65      *  name (second element on stack) and value (top of stack) are
66      *  popped off the stack and inserted into the struct (third
67      *  element on stack).
68      */
69     protected Vec objects = null;
70
71
72     // Recieve ////////////////////////////////////////////////////////////////
73
74     private class Helper extends XML {
75         public Helper() { super(BUFFER_SIZE); }
76
77         public void startElement(XML.Element c) {
78             content.reset();
79             //#switch(c.getLocalName())
80             case "fault": fault = true;
81             case "struct": objects.setElementAt(new JS(), objects.size() - 1);
82             case "array": objects.setElementAt(null, objects.size() - 1);
83             case "value": objects.addElement("");
84             //#end
85         }
86         
87         public void endElement(XML.Element c) {
88             //#switch(c.getLocalName())
89             case "int": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
90             case "i4": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
91             case "boolean": objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
92             case "string": objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
93             case "double": objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
94             case "base64":
95                 objects.setElementAt(new Stream.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())),
96                                                           null), objects.size() - 1);
97             case "name": objects.addElement(new String(content.getBuf(), 0, content.size()));
98             case "value": if ("".equals(objects.lastElement()))
99                 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
100             case "dateTime.iso8601":
101                 String s = new String(content.getBuf(), 0, content.size());
102                 
103                 // strip whitespace
104                 int i=0;
105                 while(Character.isWhitespace(s.charAt(i))) i++;
106                 if (i > 0) s = s.substring(i);
107                 
108                 try {
109                     JSDate nd = new JSDate();
110                     double date = JSDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
111                                                            Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
112                                                            Double.valueOf(s.substring(6, 8)).doubleValue(),
113                                                            Double.valueOf(s.substring(9, 11)).doubleValue(),
114                                                            Double.valueOf(s.substring(12, 14)).doubleValue(),
115                                                            Double.valueOf(s.substring(15, 17)).doubleValue(),
116                                                            (double)0
117                                                            );
118                     nd.setTime(JSDate.internalUTC(date));
119                     objects.setElementAt(nd, objects.size() - 1);
120                     
121                 } catch (Exception e) {
122                     throw new RuntimeException("ibex.net.rpc.xml.recieve.malformedDateTag" +
123                                     "the server sent a <dateTime.iso8601> tag which was malformed: " + s);
124                 }
125             case "member":
126                 Object memberValue = objects.elementAt(objects.size() - 1);
127                 String memberName = (String)objects.elementAt(objects.size() - 2);
128                 JS struct = (JS)objects.elementAt(objects.size() - 3);
129                 try {
130                     struct.put(memberName, memberValue);
131                 } catch (JSExn e) {
132                     throw new Error("this should never happen");
133                 }
134                 objects.setSize(objects.size() - 2);
135             case "data":
136                 int i;
137                 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
138                 JSArray arr = new JSArray();
139                 try {
140                     for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
141                 } catch (JSExn e) {
142                     throw new Error("this should never happen");
143                 }
144                 objects.setElementAt(arr, i);
145                 objects.setSize(i + 1);
146             //#end            
147             content.reset();
148         }
149         
150         public void characters(char[] ch, int start, int length) {
151             try { content.write(ch, start, length); }
152             catch (Exception e) { 
153                 if (Log.on) Log.info(this, "Exception in XMLRPC.content() -- this should never happen");
154                 if (Log.on) Log.info(this, e);
155             }
156         }
157         
158         public void whitespace(char[] ch, int start, int length) {}
159     }
160
161     // Send ///////////////////////////////////////////////////////////////////////////
162
163     protected String buildRequest(JSArray args) throws JSExn, IOException {
164         StringBuffer content = new StringBuffer();
165         content.append("\r\n");
166         content.append("<?xml version=\"1.0\"?>\n");
167         content.append("    <methodCall>\n");
168         content.append("        <method>");
169         content.append(method);
170         content.append("</method>\n");
171         content.append("        <params>\n");
172         for(int i=0; i<args.length(); i++) {
173             content.append("            <param>\n");
174             appendObject(args.elementAt(i), content);
175             content.append("            </param>\n");
176         }
177         content.append("        </params>\n");
178         content.append("    </methodCall>");
179         return content.toString();
180     }
181
182     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
183     void appendObject(Object o, StringBuffer sb) throws JSExn {
184
185         if (o == null) {
186             throw new JSExn("attempted to send a null value via XML-RPC");
187
188         } else if (o instanceof Number) {
189             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
190                 sb.append("                <value><i4>");
191                 sb.append(((Number)o).intValue());
192                 sb.append("</i4></value>\n");
193             } else {
194                 sb.append("                <value><double>");
195                 sb.append(o);
196                 sb.append("</double></value>\n");
197             }
198
199         } else if (o instanceof Boolean) {
200             sb.append("                <value><boolean>");
201             sb.append(((Boolean)o).booleanValue() ? "1" : "0");
202             sb.append("</boolean></value>\n");
203
204         } else if (o instanceof Stream) {
205             try {
206                 sb.append("                <value><base64>\n");
207                 InputStream is = ((Stream)o).getInputStream();
208                 byte[] buf = new byte[54];
209                 while(true) {
210                     int numread = is.read(buf, 0, 54);
211                     if (numread == -1) break;
212                     byte[] writebuf = buf;
213                     if (numread < buf.length) {
214                         writebuf = new byte[numread];
215                         System.arraycopy(buf, 0, writebuf, 0, numread);
216                     }
217                     sb.append("              ");
218                     sb.append(new String(Base64.encode(writebuf)));
219                     sb.append("\n");
220                 }
221                 sb.append("\n              </base64></value>\n");
222             } catch (IOException e) {
223                 if (Log.on) Log.info(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
224                 if (Log.on) Log.info(this, e);
225                 throw new JSExn("caught IOException while attempting to send a ByteStream via XML-RPC");
226             }
227
228         } else if (o instanceof String) {
229             sb.append("                <value><string>");
230             String s = (String)o;
231             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
232                 sb.append(s);
233             } else {
234                 char[] cbuf = s.toCharArray();
235                 int oldi = 0, i=0;
236                 while(true) {
237                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
238                     sb.append(cbuf, oldi, i - oldi);
239                     if (i >= cbuf.length) break;
240                     if (cbuf[i] == '<') sb.append("&lt;");
241                     else if (cbuf[i] == '&') sb.append("&amp;");
242                     i = oldi = i + 1;
243                     if (i >= cbuf.length) break;
244                 }
245             }
246             sb.append("</string></value>\n");
247
248         } else if (o instanceof JSDate) {
249             sb.append("                <value><dateTime.iso8601>");
250             java.util.Date d = new java.util.Date(((JSDate)o).getRawTime());
251             sb.append(d.getYear() + 1900);
252             if (d.getMonth() + 1 < 10) sb.append('0');
253             sb.append(d.getMonth() + 1);
254             if (d.getDate() < 10) sb.append('0');
255             sb.append(d.getDate());
256             sb.append('T');
257             if (d.getHours() < 10) sb.append('0');
258             sb.append(d.getHours());
259             sb.append(':');
260             if (d.getMinutes() < 10) sb.append('0');
261             sb.append(d.getMinutes());
262             sb.append(':');
263             if (d.getSeconds() < 10) sb.append('0');
264             sb.append(d.getSeconds());
265             sb.append("</dateTime.iso8601></value>\n");
266
267         } else if (o instanceof JSArray) {
268             if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
269             tracker.put(o, Boolean.TRUE);
270             sb.append("                <value><array><data>\n");
271             JSArray a = (JSArray)o;
272             for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
273             sb.append("                </data></array></value>\n");
274
275         } else if (o instanceof JS) {
276             if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
277             tracker.put(o, Boolean.TRUE);
278             JS j = (JS)o;
279             sb.append("                <value><struct>\n");
280             Enumeration e = j.keys();
281             while(e.hasMoreElements()) {
282                 Object key = e.nextElement();
283                 sb.append("                <member><name>" + key + "</name>\n");
284                 appendObject(j.get(key), sb);
285                 sb.append("                </member>\n");
286             }
287             sb.append("                </struct></value>\n");
288
289         } else {
290             throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
291
292         }
293     }
294
295
296     // Call Sequence //////////////////////////////////////////////////////////////////////////
297
298     public final Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
299         JSArray args = new JSArray();
300         for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
301         return call(args);
302     }
303
304     public final Object call(final JSArray args) throws JSExn {
305         try {
306             final JS.UnpauseCallback callback = JS.pause();
307             new java.lang.Thread() { public void run() { call(callback, args); }  }.start();
308             return null; // doesn't matter since we paused
309         } catch (NotPauseableException npe) {
310             throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
311         }
312     }
313
314     final void call(final JS.UnpauseCallback callback, final JSArray args) {
315         try {
316             if (Log.verbose) Log.info(this, "call to " + url + " : " + method);
317             if (tracker == null) tracker = new Hash();
318             if (objects == null) objects = new Vec();
319             String request = buildRequest(args);
320             if (Log.verbose) Log.info(this, "send:\n" + request);
321             InputStream is = http.POST("text/xml", request);
322             BufferedReader br = new BufferedReader(new InputStreamReader(is));
323             try {
324                 new Helper().parse(br);
325                 final Object result = fault ? new JSExn(objects.elementAt(0)) : objects.size() == 0 ? null : objects.elementAt(0);
326                 Scheduler.add(new Scheduler.Task() { public void perform() throws Exception { callback.unpause(result); }});
327             } finally {
328                 tracker.clear();
329                 objects.setSize(0);
330             }
331         } catch (final JSExn e) {
332             final Exception e2 = e;
333             Scheduler.add(new Scheduler.Task() { public void perform() throws Exception { callback.unpause(e2); }});
334         } catch (final IOException e) {
335             final Exception e2 = e;
336             Scheduler.add(new Scheduler.Task() { public void perform() throws Exception { callback.unpause(new JSExn(e2)); }});
337         } catch (final XML.Exn e) {
338             final Exception e2 = e;
339             Scheduler.add(new Scheduler.Task() { public void perform() throws Exception { callback.unpause(new JSExn(e2)); }});
340         }
341     }
342 }