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