2003/12/27 23:47:52
[org.ibex.core.git] / src / org / xwt / XMLRPC.java
index efcccf7..050199a 100644 (file)
@@ -30,19 +30,21 @@ import org.bouncycastle.util.encoders.Base64;
  *         convert.
  *  </ol>
  */
-class XMLRPC extends JSCallable {
+class XMLRPC extends JS {
 
-    /** the url to connect to */
-    protected String url = null;
+    public XMLRPC(String url, String method) { this(url, method, new HTTP(url)); }
+    public XMLRPC(String url, String method, HTTP http) { this.http = http; this.url = url; this.method = method; }
+    public Object get(Object name) { return new XMLRPC(url, (method.equals("") ? "" : method + ".") + name.toString(), http); }
 
-    /** the method name to invoke on the remove server */
-    protected String methodname = null;
 
     /** this holds character content as we read it in -- since there is only one per instance, we don't support mixed content */
     protected AccessibleCharArrayWriter content = new AccessibleCharArrayWriter(100);
+    protected String url = null;       ///< the url to connect to
+    protected String method = null;    ///< the method name to invoke on the remove server
+    protected HTTP http = null;        ///< the HTTP connection to use
+    private Hash tracker;                ///< used to detect multi-ref data
+    protected boolean fault = false;     ///< True iff the return value is a fault (and should be thrown as an exception)
 
-    /** the HTTP connection to use */
-    protected HTTP http = null;
 
     /** The object stack. As we process xml elements, pieces of the
      *  return value are pushed onto and popped off of this stack.
@@ -67,50 +69,35 @@ class XMLRPC extends JSCallable {
      */
     protected Vec objects = null;
 
-    /** used to detect multi-ref data */
-    private Hash tracker;
 
-    /** True iff the return value is a fault (and should be thrown as an exception) */
-    protected boolean fault = false;
-
-
-    // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
+    // Recieve ////////////////////////////////////////////////////////////////
 
     private class Helper extends XML {
         public Helper() { super(BUFFER_SIZE); }
 
         public void startElement(XML.Element c) {
             content.reset();
-            if (c.localName.equals("fault")) fault = true;
-            else if (c.localName.equals("struct")) objects.setElementAt(new JS(), objects.size() - 1);
-            else if (c.localName.equals("array")) objects.setElementAt(null, objects.size() - 1);
-            else if (c.localName.equals("value")) objects.addElement("");
+            //#switch(c.getLocalName())
+            case "fault": fault = true;
+            case "struct": objects.setElementAt(new JS(), objects.size() - 1);
+            case "array": objects.setElementAt(null, objects.size() - 1);
+            case "value": objects.addElement("");
+            //#end
         }
         
         public void endElement(XML.Element c) {
-            
-            if (c.localName.equals("int") || c.localName.equals("i4"))
-                objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
-            
-            else if (c.localName.equals("boolean"))
-                objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
-            
-            else if (c.localName.equals("string"))
+            //#switch(c.getLocalName())
+            case "int": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
+            case "i4": objects.setElementAt(new Integer(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
+            case "boolean": objects.setElementAt(content.getBuf()[0] == '1' ? Boolean.TRUE : Boolean.FALSE, objects.size() - 1);
+            case "string": objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
+            case "double": objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
+            case "base64": objects.setElementAt(new Res.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())),
+                                                                  null), objects.size() - 1);
+            case "name": objects.addElement(new String(content.getBuf(), 0, content.size()));
+            case "value": if ("".equals(objects.lastElement()))
                 objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
-            
-            else if (c.localName.equals("double"))
-                objects.setElementAt(new Double(new String(content.getBuf(), 0, content.size())), objects.size() - 1);
-            
-            else if (c.localName.equals("base64"))
-                objects.setElementAt(new Res.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())), null), objects.size() - 1);
-
-            else if (c.localName.equals("name"))
-                objects.addElement(new String(content.getBuf(), 0, content.size()));
-            
-            else if (c.localName.equals("value") && "".equals(objects.lastElement()))
-                objects.setElementAt(new String(content.getBuf(), 0, content.size()), objects.size() - 1);
-            
-            else if (c.localName.equals("dateTime.iso8601")) {
+            case "dateTime.iso8601":
                 String s = new String(content.getBuf(), 0, content.size());
                 
                 // strip whitespace
@@ -135,24 +122,28 @@ class XMLRPC extends JSCallable {
                     if (Log.on) Log.log(this, "error parsing date : " + s);
                     if (Log.on) Log.log(this, e);
                 }
-                
-            } else if (c.localName.equals("member")) {
+            case "member":
                 Object memberValue = objects.elementAt(objects.size() - 1);
                 String memberName = (String)objects.elementAt(objects.size() - 2);
                 JS struct = (JS)objects.elementAt(objects.size() - 3);
-                struct.put(memberName, memberValue);
+                try {
+                    struct.put(memberName, memberValue);
+                } catch (JSExn e) {
+                    throw new Error("this should never happen");
+                }
                 objects.setSize(objects.size() - 2);
-                
-            } else if (c.localName.equals("data")) {
+            case "data":
                 int i;
                 for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
                 JSArray arr = new JSArray();
-                for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
+                try {
+                    for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
+                } catch (JSExn e) {
+                    throw new Error("this should never happen");
+                }
                 objects.setElementAt(arr, i);
                 objects.setSize(i + 1);
-                
-            }
-            
+            //#end            
             content.reset();
         }
         
@@ -167,13 +158,32 @@ class XMLRPC extends JSCallable {
         public void whitespace(char[] ch, int start, int length) {}
     }
 
-    // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
+    // Send ///////////////////////////////////////////////////////////////////////////
+
+    protected String buildRequest(JSArray args) throws JSExn, IOException {
+        StringBuffer content = new StringBuffer();
+        content.append("\r\n");
+        content.append("<?xml version=\"1.0\"?>\n");
+        content.append("    <methodCall>\n");
+        content.append("        <method>");
+        content.append(method);
+        content.append("</method>\n");
+        content.append("        <params>\n");
+        for(int i=0; i<args.length(); i++) {
+            content.append("            <param>\n");
+            appendObject(args.elementAt(i), content);
+            content.append("            </param>\n");
+        }
+        content.append("        </params>\n");
+        content.append("    </methodCall>");
+        return content.toString();
+    }
 
     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
-    void appendObject(Object o, StringBuffer sb) throws JS.Exn {
+    void appendObject(Object o, StringBuffer sb) throws JSExn {
 
         if (o == null) {
-            throw new JS.Exn("attempted to send a null value via XML-RPC");
+            throw new JSExn("attempted to send a null value via XML-RPC");
 
         } else if (o instanceof Number) {
             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
@@ -212,7 +222,7 @@ class XMLRPC extends JSCallable {
             } catch (IOException e) {
                 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via XML-RPC");
                 if (Log.on) Log.log(this, e);
-                throw new JS.Exn("caught IOException while attempting to send a ByteStream via XML-RPC");
+                throw new JSExn("caught IOException while attempting to send a ByteStream via XML-RPC");
             }
 
         } else if (o instanceof String) {
@@ -255,7 +265,7 @@ class XMLRPC extends JSCallable {
             sb.append("</dateTime.iso8601></value>\n");
 
         } else if (o instanceof JSArray) {
-            if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
+            if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
             tracker.put(o, Boolean.TRUE);
             sb.append("                <value><array><data>\n");
             JSArray a = (JSArray)o;
@@ -263,7 +273,7 @@ class XMLRPC extends JSCallable {
             sb.append("                </data></array></value>\n");
 
         } else if (o instanceof JS) {
-            if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
+            if (tracker.get(o) != null) throw new JSExn("attempted to send multi-ref data structure via XML-RPC");
             tracker.put(o, Boolean.TRUE);
             JS j = (JS)o;
             sb.append("                <value><struct>\n");
@@ -277,127 +287,53 @@ class XMLRPC extends JSCallable {
             sb.append("                </struct></value>\n");
 
         } else {
-            throw new JS.Exn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
+            throw new JSExn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
 
         }
     }
 
-    public Object call_(JSArray args) throws JS.Exn, IOException {
-        if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
-
-        if (tracker == null) tracker = new Hash();
-        else tracker.clear();
-
-        if (objects == null) objects = new Vec();
-        else objects.setSize(0);
-
-        final String content = send(args, http);
-        if (Log.verbose) {
-            String s;
-            BufferedReader br2 = new BufferedReader(new StringReader(content));
-            while ((s = br2.readLine()) != null) Log.log(this, "send: " + s);
-        }
-
-        InputStream is = http.POST("text/xml", content);
-        try {
-            BufferedReader br = !Log.verbose ?
-                new BufferedReader(new InputStreamReader(is)) :
-                new BufferedReader(new FilterReader(new InputStreamReader(is)) {
-                        public int read() throws IOException {
-                            int i = super.read();
-                            if (Log.on) Log.log(this, "recv: " + ((char)i));
-                            return i;
-                        }
-                        public int read(char[] c, int off, int len) throws IOException {
-                            int ret = super.read(c, off, len);
-                            if (ret == -1) return ret;
-                            String s;
-                            BufferedReader br2 = new BufferedReader(new StringReader(new String(c, off, ret)));
-                            while ((s = br2.readLine()) != null) Log.log(this, "recv: " + s);
-                            return ret;
-                        }
-                    });
-            return null;
-        } finally {
-            is.close();
-        }
-    }
 
-    protected String send(JSArray args, HTTP http) throws JS.Exn, IOException {
-        StringBuffer content = new StringBuffer();
-        content.append("\r\n");
-        content.append("<?xml version=\"1.0\"?>\n");
-        content.append("    <methodCall>\n");
-        content.append("        <methodName>");
-        content.append(methodname);
-        content.append("</methodName>\n");
-        content.append("        <params>\n");
-        for(int i=0; i<args.length(); i++) {
-            content.append("            <param>\n");
-            appendObject(args.elementAt(i), content);
-            content.append("            </param>\n");
-        }
-        content.append("        </params>\n");
-        content.append("    </methodCall>");
-        return content.toString();
-    }
-        
-    protected Object recieve(BufferedReader br) throws JS.Exn, IOException {
-        // parse XML reply
-        try {
-            new Helper().parse(br);
-        } catch (XML.XMLException e) {
-            if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
-            throw new JS.Exn("reply from server was not well-formed XML: " + e);
-        }
-        
-        if (fault) throw new JS.Exn(objects.elementAt(0));
-        if (objects.size() == 0) return null;
-        return objects.elementAt(0);
-    }
+    // Call Sequence //////////////////////////////////////////////////////////////////////////
 
-    public final Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JS.Exn {
+    public final Object call(Object a0, Object a1, Object a2, Object[] rest, int nargs) throws JSExn {
         JSArray args = new JSArray();
         for(int i=0; i<nargs; i++) args.addElement(i==0?a0:i==1?a1:i==2?a2:rest[i-3]);
         return call(args);
     }
-    public final Object call(final JSArray args) throws JS.Exn {
-        final Callback callback = JSContext.pause();
-        new java.lang.Thread() {
-            public void run() {
-                try {
-                    final Object ret = call_(args);
-                    Scheduler.add(new Scheduler.Task() { public void perform() { callback.call(ret); } });
-                } catch (IOException se) {
-                    if (Log.on) Log.log(this, se);
-                    throw new JS.Exn("socket exception: " + se);
-                }
-        } }.start();
-        return null;
-    }
 
-    /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
-    public Object get(Object name) {
-        return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name.toString(), http);
-    }
-
-    public XMLRPC(String url, String methodname) {
-        this(url, methodname, new HTTP(url));
-    }
-
-    public XMLRPC(String url, String methodname, HTTP http) {
-        this.http = http;
-        this.url = url;
-        this.methodname = methodname;
+    public final Object call(final JSArray args) throws JSExn {
+        try {
+            final JS.UnpauseCallback callback = JS.pause();
+            new java.lang.Thread() { public void run() { call(callback, args); }  }.start();
+            return null; // doesn't matter since we paused
+        } catch (NotPauseableException npe) {
+            throw new JSExn("cannot invoke an XML-RPC call in the foreground thread");
+        }
     }
 
-
-    // Helper Classes ///////////////////////////////////////////////////////////////////////////////////
-
-    /** CharArrayWriter that lets us touch its buffer */
-    protected static class AccessibleCharArrayWriter extends CharArrayWriter {
-        public char[] getBuf() { return buf; }
-        public AccessibleCharArrayWriter(int i) { super(i); }
+    final void call(final JS.UnpauseCallback callback, final JSArray args) {
+        try {
+            if (Log.verbose) Log.log(this, "call to " + url + " : " + method);
+            String request = buildRequest(args);
+            if (Log.verbose) Log.log(this, "send:\n" + request);
+            InputStream is = http.POST("text/xml", request);
+            BufferedReader br = new BufferedReader(new InputStreamReader(is));
+            if (tracker == null) tracker = new Hash();
+            if (objects == null) objects = new Vec();
+            try {
+                new Helper().parse(br);
+                final Object result = fault ? new JSExn(objects.elementAt(0)) : objects.size() == 0 ? null : objects.elementAt(0);
+                Scheduler.add(new Scheduler.Task() { public void perform() throws Exception { callback.unpause(result); }});
+            } finally {
+                tracker.clear();
+                objects.setSize(0);
+            }
+        } catch (final JSExn e) {
+            Scheduler.add(new Scheduler.Task() { public void perform() throws Exception { callback.unpause(e); }});
+        } catch (final IOException e) {
+            Scheduler.add(new Scheduler.Task() { public void perform() throws Exception { callback.unpause(new JSExn(e)); }});
+        } catch (final XML.Exn e) {
+            Scheduler.add(new Scheduler.Task() { public void perform() throws Exception { callback.unpause(new JSExn(e)); }});
+        }
     }
-
 }