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