2002/06/01 23:46:31
[org.ibex.core.git] / src / org / xwt / SOAP.java
1 // Copyright 2002 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.mozilla.javascript.*;
8 import org.xwt.util.*;
9 import org.bouncycastle.util.encoders.Base64;
10
11 /**
12  *  A partial RPC-style SOAP 1.1 client. Implemented from the SOAP 1.1
13  *  Spec and Dave Winer's "SOAP for Busy Developers". This class
14  *  extends XMLRPC in order to share some networking logic.
15  *
16  *  Currently unsupported features/hacks:
17  *  <ul><li> Multi-ref data and circular references
18  *      <li> 'Document Style'
19  *      <li> WSDL support
20  *  </ul>
21  */
22 class SOAP extends XMLRPC {
23
24     /** the desired content of the SOAPAction header */
25     String action = null;
26
27     /** the namespace to use */
28     String nameSpace = null;
29
30     /** When you get a property from an SOAP, it just returns another SOAP with the property name tacked onto methodname. */
31     public Object get(String name, Scriptable start) {
32         return new SOAP(url.toString(), (methodname.equals("") ? "" : methodname + ".") + name, action, nameSpace);
33     }
34
35
36     // Methods to Recieve and parse SOAP Responses ////////////////////////////////////////////////////
37
38     public void startElement(String name, String[] keys, Object[] vals, int line, int col) {
39
40         if (name.equals("SOAP-ENV:Envelope")) return;
41         if (name.equals("SOAP-ENV:Body")) return;
42         if (name.equals("SOAP-ENV:Fault")) fault = true;
43
44         // add a generic struct; we'll change this if our type is different
45         objects.addElement(new JSObject(false));
46
47         for(int i=0; i<keys.length; i++) {
48             String key = keys[i];
49             String value = vals[i].toString();
50             if (key.endsWith("ype")) {
51                 if (value.endsWith("boolean")) {
52                     objects.removeElementAt(objects.size() - 1);
53                     objects.addElement(Boolean.FALSE);
54                 } else if (value.endsWith("int")) {
55                     objects.removeElementAt(objects.size() - 1);
56                     objects.addElement(new Integer(0));
57                 } else if (value.endsWith("double")) {
58                     objects.removeElementAt(objects.size() - 1);
59                     objects.addElement(new Double(0.0));
60                 } else if (value.endsWith("string")) {
61                     objects.removeElementAt(objects.size() - 1);
62                     objects.addElement("");
63                 } else if (value.endsWith("base64")) {
64                     objects.removeElementAt(objects.size() - 1);
65                     objects.addElement(new byte[] { });
66                 } else if (value.endsWith("null")) {
67                     objects.removeElementAt(objects.size() - 1);
68                     objects.addElement(null);
69                 } else if (value.endsWith("arrayType") || value.endsWith("Array") || key.endsWith("arrayType")) {
70                     objects.removeElementAt(objects.size() - 1);
71                     objects.addElement(Context.enter().newArray(org.xwt.util.JSObject.defaultObjects, new Object[] { } ));
72                 }
73             }
74         }
75     }
76
77     public void endElement(String name, int line, int col) {
78
79         if (name.equals("SOAP-ENV:Envelope")) return;
80         if (name.equals("SOAP-ENV:Body")) return;
81
82         if (content.size() > 0 && content.toString().trim().length() > 0) {
83
84             // remove ourselves
85             Object me = objects.elementAt(objects.size() - 1);
86
87             if (fault || me instanceof String) {
88                 objects.removeElementAt(objects.size() - 1);
89                 objects.addElement(new String(content.getBuf(), 0, content.size()).intern());
90                 content.reset();
91
92             } else if (me instanceof byte[]) {
93                 objects.removeElementAt(objects.size() - 1);
94                 objects.addElement(new ByteStream(Base64.decode(new String(content.getBuf(), 0, content.size()))));
95                 content.reset();                
96                 
97             } else if (me instanceof Integer) {
98                 objects.removeElementAt(objects.size() - 1);
99                 objects.addElement(new Integer(new String(content.getBuf(), 0, content.size())));
100                 content.reset();
101                 
102             } else if (me instanceof Boolean) {
103                 objects.removeElementAt(objects.size() - 1);
104                 String s = new String(content.getBuf(), 0, content.size()).trim();
105                 if (s.equals("1") || s.equals("true")) objects.addElement(Boolean.TRUE);
106                 else objects.addElement(Boolean.FALSE);
107                 content.reset();
108                 
109             } else if (me instanceof Double) {
110                 objects.removeElementAt(objects.size() - 1);
111                 objects.addElement(new Double(new String(content.getBuf(), 0, content.size())));
112                 content.reset();
113                 
114             } else {
115                 // okay, we got PCDATA for what is supposedly a
116                 // struct... somebody's not adding their type info...
117                 String s = new String(content.getBuf(), 0, content.size()).trim();
118                 boolean hasdot = false;
119                 for(int i=0; i<s.length(); i++) {
120                     if (s.charAt(i) == '.') hasdot = true;
121                     if (!Character.isDigit(s.charAt(i))) {
122                         objects.removeElementAt(objects.size() - 1);
123                         objects.addElement(s);
124                         return;
125                     }
126                 }
127                 if (hasdot) {
128                     objects.removeElementAt(objects.size() - 1);
129                     objects.addElement(new Double(s));
130                 } else {
131                     objects.removeElementAt(objects.size() - 1);
132                     objects.addElement(new Integer(s));
133                 }
134                 content.reset();
135             }
136
137         }
138         
139         // remove ourselves
140         Object me = objects.elementAt(objects.size() - 1);
141
142         // find our parent
143         Object parent = objects.size() > 1 ? objects.elementAt(objects.size() - 2) : null;
144
145         // we want to fold stuff back into the fault object
146         if (objects.size() < 2) return;
147
148         // our parent "should" be an aggregate type -- add ourselves to it.
149         if (parent != null && parent instanceof NativeArray) {
150             objects.removeElementAt(objects.size() - 1);
151             ((NativeArray)parent).put((int)((NativeArray)parent).jsGet_length(), (NativeArray)parent, me);
152
153         } else if (parent != null && parent instanceof Scriptable) {
154             objects.removeElementAt(objects.size() - 1);
155             ((Scriptable)parent).put(name, (Scriptable)parent, me);
156
157         }
158
159     }
160
161     /** Appends the SOAP representation of <code>o</code> to <code>sb</code> */
162     void appendObject(String name, Object o, StringBuffer sb) throws JavaScriptException {
163         if (o instanceof Number) {
164             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
165                 sb.append("                <" + name + " xsi:type=\"xsd:int\">");
166                 sb.append(((Number)o).intValue());
167                 sb.append("</" + name + ">\n");
168             } else {
169                 sb.append("                <" + name + " xsi:type=\"xsd:double\">");
170                 sb.append(o);
171                 sb.append("</" + name + ">\n");
172             }
173
174         } else if (o instanceof Boolean) {
175             sb.append("                <" + name + " xsi:type=\"xsd:boolean\">");
176             sb.append(((Boolean)o).booleanValue() ? "true" : "false");
177             sb.append("</" + name + ">\n");
178
179         } else if (o instanceof ByteStream) {
180             try {
181                 sb.append("                <" + name + " xsi:type=\"SOAP-ENC:base64\">\n");
182                 InputStream is = ((ByteStream)o).getInputStream();
183                 byte[] buf = new byte[54];
184                 while(true) {
185                     int numread = is.read(buf, 0, 54);
186                     if (numread == -1) break;
187                     byte[] writebuf = buf;
188                     if (numread < buf.length) {
189                         writebuf = new byte[numread];
190                         System.arraycopy(buf, 0, writebuf, 0, numread);
191                     }
192                     sb.append("              ");
193                     sb.append(new String(Base64.encode(writebuf)));
194                     sb.append("\n");
195                 }
196                 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
197                 sb.append("</" + name + ">\n");
198             } catch (IOException e) {
199                 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via SOAP");
200                 if (Log.on) Log.log(this, e);
201                 throw new JavaScriptException("caught IOException while attempting to send a ByteStream via SOAP");
202             }
203
204         } else if (o instanceof String) {
205             sb.append("                <" + name + " xsi:type=\"xsd:string\">");
206             String s = (String)o;
207             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
208                 sb.append(s);
209             } else {
210                 char[] cbuf = s.toCharArray();
211                 while(true) {
212                     int oldi = 0, i=0;
213                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
214                     sb.append(cbuf, oldi, i);
215                     if (i == cbuf.length) break;
216                     if (cbuf[i] == '<') sb.append("&lt;");
217                     else if (cbuf[i] == '&') sb.append("&amp;");
218                     i = oldi = i + 1;
219                 }
220             }
221             sb.append("</" + name + ">\n");
222
223         } else if (o instanceof NativeArray) {
224             NativeArray na = (NativeArray)o;
225             sb.append("                <" + name + " SOAP-ENC:arrayType=\"xsd:ur-type[" + na.jsGet_length() + "]\">");
226             for(int i=0; i<na.jsGet_length(); i++)
227                 appendObject("item", na.get(i, na), sb);
228             sb.append("</" + name + ">\n");
229
230         } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
231             Scriptable s = (Scriptable)o;
232             sb.append("                <" + name + ">");
233             Object[] ids = s.getIds();
234             for(int i=0; i<ids.length; i++)
235                 appendObject(ids[i].toString(), s.get(ids[i].toString(), s), sb);
236             sb.append("</" + name + ">\n");
237         }
238     }
239
240     protected String send(Object[] args, HTTP http) throws JavaScriptException, IOException {
241         // build up the request
242         StringBuffer content = new StringBuffer();
243         content.append("<?xml version=\"1.0\"?>\n");
244         content.append("<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\n");
245         content.append("                   xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\n");
246         content.append("                   xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n");
247         content.append("                   xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"\n");
248         content.append("                   xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">\n");
249         content.append("<SOAP-ENV:Body>\n");
250         content.append("    <");
251         content.append(methodname);
252         content.append(nameSpace != null ? " xmlns=\"" + nameSpace + "\"" : "");
253         content.append(">\n");
254         if (args.length > 0) {
255             Object[] o = ((Scriptable)args[0]).getIds();
256             for(int i=0; i<o.length; i++)
257                 appendObject(o[i].toString(), ((Scriptable)args[0]).get(o[i].toString(), (Scriptable)args[0]), content);
258         }
259         content.append("    </" + methodname + "></SOAP-ENV:Body></SOAP-ENV:Envelope>");
260         http.addHeader("SOAPAction", action);
261         return content.toString();
262     }
263
264     SOAP(String url, String methodname, String action, String nameSpace) {
265         super(url, methodname);
266         this.action = action;
267         this.nameSpace = nameSpace;
268     }
269
270 }