2002/04/28 21:12:47
[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 String(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) {
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 String) {
180             sb.append("                <" + name + " xsi:type=\"xsd:string\">");
181             String s = (String)o;
182             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
183                 sb.append(s);
184             } else {
185                 char[] cbuf = s.toCharArray();
186                 while(true) {
187                     int oldi = 0, i=0;
188                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
189                     sb.append(cbuf, oldi, i);
190                     if (i == cbuf.length) break;
191                     if (cbuf[i] == '<') sb.append("&lt;");
192                     else if (cbuf[i] == '&') sb.append("&amp;");
193                     i = oldi = i + 1;
194                 }
195             }
196             sb.append("</" + name + ">\n");
197
198         } else if (o instanceof NativeArray) {
199             NativeArray na = (NativeArray)o;
200             sb.append("                <" + name + " SOAP-ENC:arrayType=\"xsd:ur-type[" + na.jsGet_length() + "]\">");
201             for(int i=0; i<na.jsGet_length(); i++)
202                 appendObject("item", na.get(i, na), sb);
203             sb.append("</" + name + ">\n");
204
205         } else if (o instanceof Scriptable && !(o instanceof Undefined)) {
206             Scriptable s = (Scriptable)o;
207             sb.append("                <" + name + ">");
208             Object[] ids = s.getIds();
209             for(int i=0; i<ids.length; i++)
210                 appendObject(ids[i].toString(), s.get(ids[i].toString(), s), sb);
211             sb.append("</" + name + ">\n");
212         }
213     }
214
215     protected Object send(Object[] args, BufferedReader br, PrintWriter ps) throws IOException, JavaScriptException {
216
217         // build up the request
218         StringBuffer content = new StringBuffer();
219         content.append("<?xml version=\"1.0\"?>\n");
220         content.append("<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\n");
221         content.append("                   xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\n");
222         content.append("                   xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\n");
223         content.append("                   xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"\n");
224         content.append("                   xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">\n");
225         content.append("<SOAP-ENV:Body>\n");
226         content.append("    <");
227         content.append(methodname);
228         content.append(nameSpace != null ? " xmlns=\"" + nameSpace + "\"" : "");
229         content.append(">\n");
230         if (args.length > 0) {
231             Object[] o = ((Scriptable)args[0]).getIds();
232             for(int i=0; i<o.length; i++)
233                 appendObject(o[i].toString(), ((Scriptable)args[0]).get(o[i].toString(), (Scriptable)args[0]), content);
234         }
235         content.append("    </" + methodname + "></SOAP-ENV:Body></SOAP-ENV:Envelope>");
236         
237         // send it
238         ps.print("POST " + filename + " HTTP/1.0\r\n");
239         ps.print("Host: " + host + "\r\n");
240         ps.print("User-Agent: XWT (http://www.xwt.org/)\r\n");
241         ps.print("Content-Type: text/xml; charset=\"us-ascii\"\r\n");
242         ps.print("Content-length: " + (content.length() + 1) + "\r\n");
243         ps.print("SOAPAction: " + (action == null ? filename : action) + "\r\n");
244         ps.print("\r\n");
245         ps.print(content);
246         ps.print("\n");
247         ps.flush();
248         
249         // throw away HTTP reply headers
250         while(!br.readLine().equals("")) { }
251
252         // parse XML reply
253         try {
254             parse(br);
255         } catch (XML.SAXException e) {
256             if (Log.on) Log.log(this, "reply from server was not well-formed XML: " + e);
257             throw new JavaScriptException("reply from server was not well-formed XML: " + e);
258         }
259
260         if (fault) throw new JavaScriptException((Scriptable)objects.elementAt(0));
261         if (objects.size() == 0) return null;
262         return objects.elementAt(0);
263     }
264
265     SOAP(String urlstr, String methodname, String action, String nameSpace) {
266         super(urlstr, methodname);
267         this.action = action;
268         this.nameSpace = nameSpace;
269     }
270
271 }