reorganized file layout (part 1: moves and renames)
[org.ibex.core.git] / src / org / ibex / net / SOAP.java
diff --git a/src/org/ibex/net/SOAP.java b/src/org/ibex/net/SOAP.java
new file mode 100644 (file)
index 0000000..946ccb7
--- /dev/null
@@ -0,0 +1,282 @@
+// Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
+package org.ibex;
+
+import java.io.*;
+import java.util.*;
+import org.ibex.js.*;
+import org.ibex.util.*;
+import org.bouncycastle.util.encoders.Base64;
+
+/**
+ *  A partial RPC-style SOAP 1.1 client. Implemented from the SOAP 1.1
+ *  Spec and Dave Winer's "SOAP for Busy Developers". This class
+ *  extends XMLRPC in order to share some networking logic.
+ *
+ *  Currently unsupported features/hacks:
+ *  <ul><li> Multi-ref data and circular references
+ *      <li> 'Document Style'
+ *      <li> WSDL support
+ *  </ul>
+ */
+class SOAP extends XMLRPC {
+
+    /** the desired content of the SOAPAction header */
+    String action = null;
+
+    /** the namespace to use */
+    String nameSpace = null;
+
+    /** When you get a property from an SOAP, it just returns another SOAP with the property name tacked onto methodname. */
+    public Object get(Object name) {
+        return new SOAP(url, (method.equals("") ? "" : method + ".") + name.toString(), this, action, nameSpace); }
+
+
+    // Methods to Recieve and parse SOAP Responses ////////////////////////////////////////////////////
+
+    public void startElement(String name, String[] keys, Object[] vals, int line, int col) {
+
+        content.reset();
+        if (name.equals("SOAP-ENV:Envelope")) return;
+        if (name.equals("SOAP-ENV:Body")) return;
+        if (name.equals("SOAP-ENV:Fault")) fault = true;
+        // add a generic struct; we'll change this if our type is different
+        objects.addElement(new JS());
+
+        for(int i=0; i<keys.length; i++) {
+            String key = keys[i];
+            String value = vals[i].toString();
+            if (key.endsWith("ype")) {
+                if (value.endsWith("boolean")) {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement(Boolean.FALSE);
+                } else if (value.endsWith("int")) {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement(new Integer(0));
+                } else if (value.endsWith("double")) {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement(new Double(0.0));
+                } else if (value.endsWith("string")) {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement("");
+                } else if (value.endsWith("base64")) {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement(new byte[] { });
+                } else if (value.endsWith("null")) {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement(null);
+                } else if (value.endsWith("arrayType") || value.endsWith("JSArray") || key.endsWith("arrayType")) {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement(new JSArray());
+                }
+            }
+        }
+    }
+
+    public void endElement(String name, int line, int col) {
+
+        if (name.equals("SOAP-ENV:Envelope")) return;
+        if (name.equals("SOAP-ENV:Body")) return;
+
+        if (content.size() > 0 && content.toString().trim().length() > 0) {
+
+            // remove ourselves
+            Object me = objects.elementAt(objects.size() - 1);
+
+            if (fault || me instanceof String) {
+                objects.removeElementAt(objects.size() - 1);
+                objects.addElement(new String(content.getBuf(), 0, content.size()).intern());
+                content.reset();
+
+            } else if (me instanceof byte[]) {
+                objects.removeElementAt(objects.size() - 1);
+                objects.addElement(new Stream.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())), null));
+                content.reset();                
+
+            } else if (me instanceof Integer) {
+                objects.removeElementAt(objects.size() - 1);
+                objects.addElement(new Integer(new String(content.getBuf(), 0, content.size())));
+                content.reset();
+                
+            } else if (me instanceof Boolean) {
+                objects.removeElementAt(objects.size() - 1);
+                String s = new String(content.getBuf(), 0, content.size()).trim();
+                if (s.equals("1") || s.equals("true")) objects.addElement(Boolean.TRUE);
+                else objects.addElement(Boolean.FALSE);
+                content.reset();
+                
+            } else if (me instanceof Double) {
+                objects.removeElementAt(objects.size() - 1);
+                objects.addElement(new Double(new String(content.getBuf(), 0, content.size())));
+                content.reset();
+                
+            } else {
+                // okay, we got PCDATA for what is supposedly a
+                // struct... somebody's not adding their type info...
+                String s = new String(content.getBuf(), 0, content.size()).trim();
+                boolean hasdot = false;
+                for(int i=0; i<s.length(); i++) {
+                    if (s.charAt(i) == '.') hasdot = true;
+                    if (!Character.isDigit(s.charAt(i))) {
+                        objects.removeElementAt(objects.size() - 1);
+                        objects.addElement(s);
+                        return;
+                    }
+                }
+                if (hasdot) {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement(new Double(s));
+                } else {
+                    objects.removeElementAt(objects.size() - 1);
+                    objects.addElement(new Integer(s));
+                }
+                content.reset();
+            }
+
+        }
+        
+        // remove ourselves
+        Object me = objects.elementAt(objects.size() - 1);
+
+        // find our parent
+        Object parent = objects.size() > 1 ? objects.elementAt(objects.size() - 2) : null;
+
+        // we want to fold stuff back into the fault object
+        if (objects.size() < 2) return;
+
+        // our parent "should" be an aggregate type -- add ourselves to it.
+        if (parent != null && parent instanceof JSArray) {
+            objects.removeElementAt(objects.size() - 1);
+            ((JSArray)parent).addElement(me);
+
+        } else if (parent != null && parent instanceof JS) {
+            objects.removeElementAt(objects.size() - 1);
+            try {
+                ((JS)parent).put(name, me);
+            } catch (JSExn e) {
+                throw new Error("this should never happen");
+            }
+
+        }
+
+    }
+
+    /** Appends the SOAP representation of <code>o</code> to <code>sb</code> */
+    void appendObject(String name, Object o, StringBuffer sb) throws JSExn {
+        if (o instanceof Number) {
+            if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
+                sb.append("                <" + name + " xsi:type=\"xsd:int\">");
+                sb.append(((Number)o).intValue());
+                sb.append("</" + name + ">\r\n");
+            } else {
+                sb.append("                <" + name + " xsi:type=\"xsd:double\">");
+                sb.append(o);
+                sb.append("</" + name + ">\r\n");
+            }
+
+        } else if (o instanceof Boolean) {
+            sb.append("                <" + name + " xsi:type=\"xsd:boolean\">");
+            sb.append(((Boolean)o).booleanValue() ? "true" : "false");
+            sb.append("</" + name + ">\r\n");
+
+        } else if (o instanceof Stream) {
+            try {
+                sb.append("                <" + name + " xsi:type=\"SOAP-ENC:base64\">\r\n");
+                InputStream is = ((Stream)o).getInputStream();
+                byte[] buf = new byte[54];
+                while(true) {
+                    int numread = is.read(buf, 0, 54);
+                    if (numread == -1) break;
+                    byte[] writebuf = buf;
+                    if (numread < buf.length) {
+                        writebuf = new byte[numread];
+                        System.arraycopy(buf, 0, writebuf, 0, numread);
+                    }
+                    sb.append("              ");
+                    sb.append(new String(Base64.encode(writebuf)));
+                    sb.append("\r\n");
+                }
+                sb.append(((Boolean)o).booleanValue() ? "1" : "0");
+                sb.append("</" + name + ">\r\n");
+            } catch (IOException e) {
+                if (Log.on) Log.info(this, "caught IOException while attempting to send a ByteStream via SOAP");
+                if (Log.on) Log.info(this, e);
+                throw new JSExn("caught IOException while attempting to send a ByteStream via SOAP");
+            }
+
+        } else if (o instanceof String) {
+            sb.append("                <" + name + " xsi:type=\"xsd:string\">");
+            String s = (String)o;
+            if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
+                sb.append(s);
+            } else {
+                char[] cbuf = s.toCharArray();
+                while(true) {
+                    int oldi = 0, i=0;
+                    while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
+                    sb.append(cbuf, oldi, i);
+                    if (i == cbuf.length) break;
+                    if (cbuf[i] == '<') sb.append("&lt;");
+                    else if (cbuf[i] == '&') sb.append("&amp;");
+                    i = oldi = i + 1;
+                }
+            }
+            sb.append("</" + name + ">\r\n");
+
+        } else if (o instanceof JSArray) {
+            JSArray a = (JSArray)o;
+            sb.append("                <" + name + " SOAP-ENC:arrayType=\"xsd:ur-type[" + a.length() + "]\">");
+            for(int i=0; i<a.length(); i++) appendObject("item", a.elementAt(i), sb);
+            sb.append("</" + name + ">\r\n");
+
+        } else if (o instanceof JS) {
+            JS j = (JS)o;
+            sb.append("                <" + name + ">");
+            Enumeration e = j.keys();
+            while(e.hasMoreElements()) {
+                Object key = e.nextElement();
+                appendObject((String)key, j.get(key), sb);
+            }
+            sb.append("</" + name + ">\r\n");
+
+        }
+    }
+
+    protected String buildRequest(JSArray args) throws JSExn, IOException {
+        // build up the request
+        StringBuffer content = new StringBuffer();
+        content.append("SOAPAction: " + action + "\r\n\r\n");
+        content.append("<?xml version=\"1.0\"?>\r\n");
+        content.append("<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
+        content.append("                   xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
+        content.append("                   xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n");
+        content.append("                   xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"\r\n");
+        content.append("                   xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">\r\n");
+        content.append("<SOAP-ENV:Body>\r\n");
+        content.append("    <");
+        content.append(method);
+        content.append(nameSpace != null ? " xmlns=\"" + nameSpace + "\"" : "");
+        content.append(">\r\n");
+        if (args.length() > 0) {
+            Enumeration e = ((JS)args.elementAt(0)).keys();
+            while(e.hasMoreElements()) {
+                Object key = e.nextElement();
+                appendObject((String)key, ((JS)args.elementAt(0)).get(key), content);
+            }
+        }
+        content.append("    </" + method + "></SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n");
+        return content.toString();
+    }
+
+    SOAP(String url, String methodname, String action, String nameSpace) {
+        super(url, methodname);
+        this.action = action;
+        this.nameSpace = nameSpace;
+    }
+    SOAP(String url, String methodname, SOAP httpSource, String action, String nameSpace) {
+        super(url, methodname, httpSource);
+        this.action = action;
+        this.nameSpace = nameSpace;
+    }
+
+}