2003/10/31 09:50:08
[org.ibex.core.git] / src / org / xwt / XMLRPC.java
index ebea2a6..ac83249 100644 (file)
@@ -1,16 +1,16 @@
-// Copyright 2002 Adam Megacz, see the COPYING file for licensing [GPL]
+// Copyright 2003 Adam Megacz, see the COPYING file for licensing [GPL]
 package org.xwt;
 
 import java.io.*;
 import java.net.*;
 import java.util.*;
-import org.mozilla.javascript.*;
+import org.xwt.js.*;
 import org.xwt.util.*;
 import org.bouncycastle.util.encoders.Base64;
 
 /**
- *  An XML-RPC client implemented as a Rhino JavaScript Host
- *  Object. See the XWT spec for information on its behavior.
+ *  An XML-RPC client implemented as a JavaScript Host Object. See the
+ *  XWT spec for information on its behavior.
  *
  *  NOTE: this client is EXTREMELY lenient in the responses it will
  *  accept; there are many, many invalid responses that it will
@@ -30,7 +30,9 @@ import org.bouncycastle.util.encoders.Base64;
  *         convert.
  *  </ol>
  */
-class XMLRPC extends XML implements Function {
+class XMLRPC extends JS.Callable {
+
+    public Object[] keys() { throw new Error("not implemented"); }
 
     /** the url to connect to */
     protected String url = null;
@@ -55,7 +57,7 @@ class XMLRPC extends XML implements Function {
      *
      *  If an &lt;array&gt; tag is encountered, a null is pushed onto the
      *  stack. When a &lt;/data&gt; is encountered, we search back on the
-     *  stack to the last null, replace it with a NativeArray, and
+     *  stack to the last null, replace it with a NativeJS.Array, and
      *  insert into it all elements above it on the stack.
      *
      *  If a &lt;struct&gt; tag is encountered, a JSObject is pushed
@@ -76,100 +78,104 @@ class XMLRPC extends XML implements Function {
 
     // Methods to Recieve and parse XML-RPC Response ////////////////////////////////////////////////////
 
-    public void startElement(XML.Element c) {
-        content.reset();
-        if (c.localName.equals("fault")) fault = true;
-        else if (c.localName.equals("struct")) objects.setElementAt(new JSObject(false), objects.size() - 1);
-        else if (c.localName.equals("array")) objects.setElementAt(null, objects.size() - 1);
-        else if (c.localName.equals("value")) objects.addElement("");
-    }
-
-    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"))
-            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 ByteStream(Base64.decode(new String(content.getBuf(), 0, content.size()))), 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")) {
-            String s = new String(content.getBuf(), 0, content.size());
+    private class Helper extends XML {
+        public Helper() { super(BUFFER_SIZE); }
 
-            // strip whitespace
-            int i=0;
-            while(Character.isWhitespace(s.charAt(i))) i++;
-            if (i > 0) s = s.substring(i);
-
-            try {
-                NativeDate nd = (NativeDate)Context.enter().newObject(org.xwt.util.JSObject.defaultObjects, "Date");
-                double date = NativeDate.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
-                                                           Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
-                                                           Double.valueOf(s.substring(6, 8)).doubleValue(),
-                                                           Double.valueOf(s.substring(9, 11)).doubleValue(),
-                                                           Double.valueOf(s.substring(12, 14)).doubleValue(),
-                                                           Double.valueOf(s.substring(15, 17)).doubleValue(),
-                                                           (double)0
-                                                           );
-                nd.jsFunction_setTime(NativeDate.internalUTC(date));
-                objects.setElementAt(nd, objects.size() - 1);
-
-            } catch (Exception e) {
-                if (Log.on) Log.log(this, "error parsing date : " + s);
-                if (Log.on) Log.log(this, e);
+        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.Obj(), objects.size() - 1);
+            else if (c.localName.equals("array")) objects.setElementAt(null, objects.size() - 1);
+            else if (c.localName.equals("value")) objects.addElement("");
+        }
+        
+        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"))
+                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()))), 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")) {
+                String s = new String(content.getBuf(), 0, content.size());
+                
+                // strip whitespace
+                int i=0;
+                while(Character.isWhitespace(s.charAt(i))) i++;
+                if (i > 0) s = s.substring(i);
+                
+                try {
+                    org.xwt.js.Date nd = new org.xwt.js.Date();
+                    double date = org.xwt.js.Date.date_msecFromDate(Double.valueOf(s.substring(0, 4)).doubleValue(),
+                                                                    Double.valueOf(s.substring(4, 6)).doubleValue() - 1,
+                                                                    Double.valueOf(s.substring(6, 8)).doubleValue(),
+                                                                    Double.valueOf(s.substring(9, 11)).doubleValue(),
+                                                                    Double.valueOf(s.substring(12, 14)).doubleValue(),
+                                                                    Double.valueOf(s.substring(15, 17)).doubleValue(),
+                                                                    (double)0
+                                                                    );
+                    nd.jsFunction_setTime(org.xwt.js.Date.internalUTC(date));
+                    objects.setElementAt(nd, objects.size() - 1);
+                    
+                } catch (Exception e) {
+                    if (Log.on) Log.log(this, "error parsing date : " + s);
+                    if (Log.on) Log.log(this, e);
+                }
+                
+            } else if (c.localName.equals("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);
+                objects.setSize(objects.size() - 2);
+                
+            } else if (c.localName.equals("data")) {
+                int i;
+                for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
+                JS.Array arr = new JS.Array();
+                for(int j = i + 1; j<objects.size(); j++) arr.put(new Integer(j - i - 1), objects.elementAt(j));
+                objects.setElementAt(arr, i);
+                objects.setSize(i + 1);
+                
             }
-
-        } else if (c.localName.equals("member")) {
-            Object memberValue = objects.elementAt(objects.size() - 1);
-            String memberName = (String)objects.elementAt(objects.size() - 2);
-            Scriptable struct = (Scriptable)objects.elementAt(objects.size() - 3);
-            struct.put(memberName, struct, memberValue);
-            objects.setSize(objects.size() - 2);
-
-        } else if (c.localName.equals("data")) {
-            int i;
-            for(i=objects.size() - 1; objects.elementAt(i) != null; i--);
-            Object[] arr = new Object[objects.size() - i - 1];
-            for(int j = i + 1; j<objects.size(); j++) arr[j - i - 1] = objects.elementAt(j);
-            objects.setElementAt(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, arr), i);
-            objects.setSize(i + 1);
-
+            
+            content.reset();
         }
-
-        content.reset();
-    }
-
-    public void characters(char[] ch, int start, int length) {
-        try { content.write(ch, start, length); }
-        catch (Exception e) { 
-            if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
-            if (Log.on) Log.log(this, e);
+        
+        public void characters(char[] ch, int start, int length) {
+            try { content.write(ch, start, length); }
+            catch (Exception e) { 
+                if (Log.on) Log.log(this, "Exception in XMLRPC.content() -- this should never happen");
+                if (Log.on) Log.log(this, e);
+            }
         }
+        
+        public void whitespace(char[] ch, int start, int length) {}
     }
 
-    public void whitespace(char[] ch, int start, int length) {}
-
     // Methods to make outbound XML-RPC request ///////////////////////////////////////////////////
 
     /** Appends the XML-RPC representation of <code>o</code> to <code>sb</code> */
-    void appendObject(Object o, StringBuffer sb) throws JavaScriptException {
+    void appendObject(Object o, StringBuffer sb) throws JS.Exn {
 
         if (o == null) {
-            throw new JavaScriptException("attempted to send a null value via XML-RPC");
+            throw new JS.Exn("attempted to send a null value via XML-RPC");
 
         } else if (o instanceof Number) {
             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
@@ -187,10 +193,10 @@ class XMLRPC extends XML implements Function {
             sb.append(((Boolean)o).booleanValue() ? "1" : "0");
             sb.append("</boolean></value>\n");
 
-        } else if (o instanceof ByteStream) {
+        } else if (o instanceof Res) {
             try {
                 sb.append("                <value><base64>\n");
-                InputStream is = ((ByteStream)o).getInputStream();
+                InputStream is = ((Res)o).getInputStream();
                 byte[] buf = new byte[54];
                 while(true) {
                     int numread = is.read(buf, 0, 54);
@@ -208,7 +214,7 @@ class XMLRPC extends XML implements Function {
             } 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 JavaScriptException("caught IOException while attempting to send a ByteStream via XML-RPC");
+                throw new JS.Exn("caught IOException while attempting to send a ByteStream via XML-RPC");
             }
 
         } else if (o instanceof String) {
@@ -231,10 +237,9 @@ class XMLRPC extends XML implements Function {
             }
             sb.append("</string></value>\n");
 
-        } else if (o instanceof NativeDate) {
+        } else if (o instanceof org.xwt.js.Date) {
             sb.append("                <value><dateTime.iso8601>");
-            NativeDate nd = (NativeDate)o;
-            Date d = new Date(nd.getRawTime());
+            java.util.Date d = new java.util.Date(((org.xwt.js.Date)o).getRawTime());
             sb.append(d.getYear() + 1900);
             if (d.getMonth() + 1 < 10) sb.append('0');
             sb.append(d.getMonth() + 1);
@@ -251,37 +256,36 @@ class XMLRPC extends XML implements Function {
             sb.append(d.getSeconds());
             sb.append("</dateTime.iso8601></value>\n");
 
-        } else if (o instanceof NativeArray) {
-            if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
+        } else if (o instanceof JS.Array) {
+            if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
             tracker.put(o, Boolean.TRUE);
             sb.append("                <value><array><data>\n");
-            NativeArray na = (NativeArray)o;
-            for(int i=0; i<na.jsGet_length(); i++)
-                appendObject(na.get(i, na), sb);
+            JS.Array a = (JS.Array)o;
+            for(int i=0; i<a.length(); i++) appendObject(a.elementAt(i), sb);
             sb.append("                </data></array></value>\n");
 
-        } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
-            if (tracker.get(o) != null) throw new JavaScriptException("attempted to send multi-ref data structure via XML-RPC");
+        } else if (o instanceof JS) {
+            if (tracker.get(o) != null) throw new JS.Exn("attempted to send multi-ref data structure via XML-RPC");
             tracker.put(o, Boolean.TRUE);
-            Scriptable s = (Scriptable)o;
+            JS j = (JS)o;
             sb.append("                <value><struct>\n");
-            Object[] ids = s.getIds();
+            Object[] ids = j.keys();
             for(int i=0; i<ids.length; i++) {
                 sb.append("                <member><name>" + ids[i] + "</name>\n");
-                appendObject(s.get(ids[i].toString(), s), sb);
+                appendObject(j.get(ids[i].toString()), sb);
                 sb.append("                </member>\n");
             }
             sb.append("                </struct></value>\n");
 
         } else {
-            throw new JavaScriptException("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
+            throw new JS.Exn("attempt to send object of type " + o.getClass().getName() + " via XML-RPC");
 
         }
     }
 
     // this is synchronized in case multiple threads try to make a call on the same object... in the future, change this
     // behavior to use pipelining.
-    public synchronized Object call(Object[] args) throws JavaScriptException, IOException {
+    public synchronized Object call2(JS.Array args) throws JS.Exn, IOException {
         if (Log.verbose) Log.log(this, "call to " + url + " : " + methodname);
 
         if (tracker == null) tracker = new Hash();
@@ -297,11 +301,11 @@ class XMLRPC extends XML implements Function {
             while ((s = br2.readLine()) != null) Log.log(this, "send: " + s);
         }
 
-        HTTP.HTTPInputStream is = http.POST("text/xml", content);
+        InputStream is = http.POST("text/xml", content);
         try {
             BufferedReader br = !Log.verbose ?
-                new BufferedReader(new InputStreamReader(new Filter(is))) :
-                new BufferedReader(new FilterReader(new InputStreamReader(new Filter(is))) {
+                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));
@@ -322,7 +326,7 @@ class XMLRPC extends XML implements Function {
         }
     }
 
-    protected String send(Object[] args, HTTP http) throws JavaScriptException, IOException {
+    protected String send(JS.Array args, HTTP http) throws JS.Exn, IOException {
         StringBuffer content = new StringBuffer();
         content.append("\r\n");
         content.append("<?xml version=\"1.0\"?>\n");
@@ -331,9 +335,9 @@ class XMLRPC extends XML implements Function {
         content.append(methodname);
         content.append("</methodName>\n");
         content.append("        <params>\n");
-        for(int i=0; i<args.length; i++) {
+        for(int i=0; i<args.length(); i++) {
             content.append("            <param>\n");
-            appendObject(args[i], content);
+            appendObject(args.elementAt(i), content);
             content.append("            </param>\n");
         }
         content.append("        </params>\n");
@@ -341,47 +345,36 @@ class XMLRPC extends XML implements Function {
         return content.toString();
     }
         
-    protected Object recieve(BufferedReader br) throws JavaScriptException, IOException {
+    protected Object recieve(BufferedReader br) throws JS.Exn, IOException {
         // parse XML reply
         try {
-            parse(br);
+            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 JavaScriptException("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 JavaScriptException(objects.elementAt(0));
+        if (fault) throw new JS.Exn(objects.elementAt(0));
         if (objects.size() == 0) return null;
         return objects.elementAt(0);
     }
 
-    public final Object call(Context cx, Scriptable scope, Scriptable thisObj, java.lang.Object[] args) throws JavaScriptException {
-
-        if (!ThreadMessage.suspendThread()) return null;
-
+    public final Object call(JS.Array args) throws JS.Exn {
         try {
-            return call(args);
+            return call2(args);
         } catch (IOException se) {
             if (Log.on) Log.log(this, se);
-            if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
-            throw new JavaScriptException("socket exception: " + se);
-
-        } catch (JavaScriptException jse) {
-            Object val = jse.getValue();
-            if (val instanceof String) {
-                if (Log.on) Log.log(this, val.toString());
-                if (Log.on) Log.log(this, " at " + cx.interpreterSourceFile + ":" + cx.interpreterLine);
-            }
+            throw new JS.Exn("socket exception: " + se);
+
+        } catch (JS.Exn jse) {
+            if (Log.on) Log.log(this, jse.toString());
             throw jse;
-        } finally {
-            ThreadMessage.resumeThread();
         }
-
     }
 
     /** When you get a property from an XMLRPC, it just returns another XMLRPC with the property name tacked onto methodname. */
-    public Object get(String name, Scriptable start) {
-        return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name, http);
+    public Object get(Object name) {
+        return new XMLRPC(url, (methodname.equals("") ? "" : methodname + ".") + name.toString(), http);
     }
 
     public XMLRPC(String url, String methodname) {
@@ -389,8 +382,6 @@ class XMLRPC extends XML implements Function {
     }
 
     public XMLRPC(String url, String methodname, HTTP http) {
-        super(BUFFER_SIZE);
-
         this.http = http;
         this.url = url;
         this.methodname = methodname;
@@ -405,44 +396,4 @@ class XMLRPC extends XML implements Function {
         public AccessibleCharArrayWriter(int i) { super(i); }
     }
 
-    /** private filter class to make sure that network transfers don't interfere with UI responsiveness */
-    private static class Filter extends FilterInputStream {
-        public Filter(InputStream is) { super(is); }
-        public int read() throws IOException {
-            Thread.yield();
-            while(MessageQueue.nonThreadEventsInQueue > 0) try { Thread.sleep(100); } catch (Exception e) { };
-            return super.read();
-        }
-        public int read(byte[] b) throws IOException {
-            Thread.yield();
-            while(MessageQueue.nonThreadEventsInQueue > 0) try { Thread.sleep(100); } catch (Exception e) { };
-            return super.read(b);
-        }
-        public int read(byte[] b, int i, int j) throws IOException {
-            Thread.yield();
-            while(MessageQueue.nonThreadEventsInQueue > 0) try { Thread.sleep(100); } catch (Exception e) { };
-            return super.read(b, i, j);
-        }
-    }
-
-
-    // Methods Required by Rhino ////////////////////////////////////////////////////////
-
-    public String getClassName() { return "XMLRPC"; }
-    public Scriptable construct(Context cx, Scriptable scope, java.lang.Object[] args) { return null; }
-    public void delete(String name) { }
-    public Scriptable getParentScope() { return null; }
-    public void setParentScope(Scriptable p) { }
-    public boolean hasInstance(Scriptable value) { return false; }
-    public Scriptable getPrototype() { return null; }
-    public void setPrototype(Scriptable p) { }
-    public void delete(int i) { }
-    public Object getDefaultValue(Class hint) { return "XML-RPC"; }
-    public void put(int i, Scriptable start, Object value) { }
-    public Object get(int i, Scriptable start) { return null; }
-    public void put(String name, Scriptable start, Object value) { }
-    public boolean has(String name, Scriptable start) { return true; }
-    public boolean has(int i, Scriptable start) { return false; }
-    public Object[] getIds() { return new Object[] { }; }
-
 }