2003/09/24 07:33:32
[org.ibex.core.git] / src / org / xwt / SOAP.java
1 // Copyright 2003 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.xwt.js.*;
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) {
32         return new SOAP(url.toString(), (methodname.equals("") ? "" : methodname + ".") + name, http, 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         content.reset();
41         if (name.equals("SOAP-ENV:Envelope")) return;
42         if (name.equals("SOAP-ENV:Body")) return;
43         if (name.equals("SOAP-ENV:Fault")) fault = true;
44  
45         // add a generic struct; we'll change this if our type is different
46         objects.addElement(new JS.Obj());
47
48         for(int i=0; i<keys.length; i++) {
49             String key = keys[i];
50             String value = vals[i].toString();
51             if (key.endsWith("ype")) {
52                 if (value.endsWith("boolean")) {
53                     objects.removeElementAt(objects.size() - 1);
54                     objects.addElement(Boolean.FALSE);
55                 } else if (value.endsWith("int")) {
56                     objects.removeElementAt(objects.size() - 1);
57                     objects.addElement(new Integer(0));
58                 } else if (value.endsWith("double")) {
59                     objects.removeElementAt(objects.size() - 1);
60                     objects.addElement(new Double(0.0));
61                 } else if (value.endsWith("string")) {
62                     objects.removeElementAt(objects.size() - 1);
63                     objects.addElement("");
64                 } else if (value.endsWith("base64")) {
65                     objects.removeElementAt(objects.size() - 1);
66                     objects.addElement(new byte[] { });
67                 } else if (value.endsWith("null")) {
68                     objects.removeElementAt(objects.size() - 1);
69                     objects.addElement(null);
70                 } else if (value.endsWith("arrayType") || value.endsWith("JS.Array") || key.endsWith("arrayType")) {
71                     objects.removeElementAt(objects.size() - 1);
72                     objects.addElement(new JS.Array());
73                 }
74             }
75         }
76     }
77
78     public void endElement(String name, int line, int col) {
79
80         if (name.equals("SOAP-ENV:Envelope")) return;
81         if (name.equals("SOAP-ENV:Body")) return;
82
83         if (content.size() > 0 && content.toString().trim().length() > 0) {
84
85             // remove ourselves
86             Object me = objects.elementAt(objects.size() - 1);
87
88             if (fault || me instanceof String) {
89                 objects.removeElementAt(objects.size() - 1);
90                 objects.addElement(new String(content.getBuf(), 0, content.size()).intern());
91                 content.reset();
92
93             } else if (me instanceof byte[]) {
94                 objects.removeElementAt(objects.size() - 1);
95                 objects.addElement(new Res.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size()))));
96                 content.reset();                
97
98             } else if (me instanceof Integer) {
99                 objects.removeElementAt(objects.size() - 1);
100                 objects.addElement(new Integer(new String(content.getBuf(), 0, content.size())));
101                 content.reset();
102                 
103             } else if (me instanceof Boolean) {
104                 objects.removeElementAt(objects.size() - 1);
105                 String s = new String(content.getBuf(), 0, content.size()).trim();
106                 if (s.equals("1") || s.equals("true")) objects.addElement(Boolean.TRUE);
107                 else objects.addElement(Boolean.FALSE);
108                 content.reset();
109                 
110             } else if (me instanceof Double) {
111                 objects.removeElementAt(objects.size() - 1);
112                 objects.addElement(new Double(new String(content.getBuf(), 0, content.size())));
113                 content.reset();
114                 
115             } else {
116                 // okay, we got PCDATA for what is supposedly a
117                 // struct... somebody's not adding their type info...
118                 String s = new String(content.getBuf(), 0, content.size()).trim();
119                 boolean hasdot = false;
120                 for(int i=0; i<s.length(); i++) {
121                     if (s.charAt(i) == '.') hasdot = true;
122                     if (!Character.isDigit(s.charAt(i))) {
123                         objects.removeElementAt(objects.size() - 1);
124                         objects.addElement(s);
125                         return;
126                     }
127                 }
128                 if (hasdot) {
129                     objects.removeElementAt(objects.size() - 1);
130                     objects.addElement(new Double(s));
131                 } else {
132                     objects.removeElementAt(objects.size() - 1);
133                     objects.addElement(new Integer(s));
134                 }
135                 content.reset();
136             }
137
138         }
139         
140         // remove ourselves
141         Object me = objects.elementAt(objects.size() - 1);
142
143         // find our parent
144         Object parent = objects.size() > 1 ? objects.elementAt(objects.size() - 2) : null;
145
146         // we want to fold stuff back into the fault object
147         if (objects.size() < 2) return;
148
149         // our parent "should" be an aggregate type -- add ourselves to it.
150         if (parent != null && parent instanceof JS.Array) {
151             objects.removeElementAt(objects.size() - 1);
152             ((JS.Array)parent).addElement(me);
153
154         } else if (parent != null && parent instanceof JS) {
155             objects.removeElementAt(objects.size() - 1);
156             ((JS)parent).put(name, me);
157
158         }
159
160     }
161
162     /** Appends the SOAP representation of <code>o</code> to <code>sb</code> */
163     void appendObject(String name, Object o, StringBuffer sb) throws JS.Exn {
164         if (o instanceof Number) {
165             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
166                 sb.append("                <" + name + " xsi:type=\"xsd:int\">");
167                 sb.append(((Number)o).intValue());
168                 sb.append("</" + name + ">\r\n");
169             } else {
170                 sb.append("                <" + name + " xsi:type=\"xsd:double\">");
171                 sb.append(o);
172                 sb.append("</" + name + ">\r\n");
173             }
174
175         } else if (o instanceof Boolean) {
176             sb.append("                <" + name + " xsi:type=\"xsd:boolean\">");
177             sb.append(((Boolean)o).booleanValue() ? "true" : "false");
178             sb.append("</" + name + ">\r\n");
179
180         } else if (o instanceof Res) {
181             try {
182                 sb.append("                <" + name + " xsi:type=\"SOAP-ENC:base64\">\r\n");
183                 InputStream is = ((Res)o).getInputStream();
184                 byte[] buf = new byte[54];
185                 while(true) {
186                     int numread = is.read(buf, 0, 54);
187                     if (numread == -1) break;
188                     byte[] writebuf = buf;
189                     if (numread < buf.length) {
190                         writebuf = new byte[numread];
191                         System.arraycopy(buf, 0, writebuf, 0, numread);
192                     }
193                     sb.append("              ");
194                     sb.append(new String(Base64.encode(writebuf)));
195                     sb.append("\r\n");
196                 }
197                 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
198                 sb.append("</" + name + ">\r\n");
199             } catch (IOException e) {
200                 if (Log.on) Log.log(this, "caught IOException while attempting to send a ByteStream via SOAP");
201                 if (Log.on) Log.log(this, e);
202                 throw new JS.Exn("caught IOException while attempting to send a ByteStream via SOAP");
203             }
204
205         } else if (o instanceof String) {
206             sb.append("                <" + name + " xsi:type=\"xsd:string\">");
207             String s = (String)o;
208             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
209                 sb.append(s);
210             } else {
211                 char[] cbuf = s.toCharArray();
212                 while(true) {
213                     int oldi = 0, i=0;
214                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
215                     sb.append(cbuf, oldi, i);
216                     if (i == cbuf.length) break;
217                     if (cbuf[i] == '<') sb.append("&lt;");
218                     else if (cbuf[i] == '&') sb.append("&amp;");
219                     i = oldi = i + 1;
220                 }
221             }
222             sb.append("</" + name + ">\r\n");
223
224         } else if (o instanceof JS.Array) {
225             JS.Array a = (JS.Array)o;
226             sb.append("                <" + name + " SOAP-ENC:arrayType=\"xsd:ur-type[" + a.length() + "]\">");
227             for(int i=0; i<a.length(); i++) appendObject("item", a.elementAt(i), sb);
228             sb.append("</" + name + ">\r\n");
229
230         } else if (o instanceof JS) {
231             JS j = (JS)o;
232             sb.append("                <" + name + ">");
233             Object[] ids = j.keys();
234             for(int i=0; i<ids.length; i++) appendObject(ids[i].toString(), j.get(ids[i].toString()), sb);
235             sb.append("</" + name + ">\r\n");
236         }
237     }
238
239     protected String send(JS.Array args, HTTP http) throws JS.Exn, IOException {
240         // build up the request
241         StringBuffer content = new StringBuffer();
242         content.append("SOAPAction: " + action + "\r\n\r\n");
243         content.append("<?xml version=\"1.0\"?>\r\n");
244         content.append("<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
245         content.append("                   xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
246         content.append("                   xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n");
247         content.append("                   xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"\r\n");
248         content.append("                   xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">\r\n");
249         content.append("<SOAP-ENV:Body>\r\n");
250         content.append("    <");
251         content.append(methodname);
252         content.append(nameSpace != null ? " xmlns=\"" + nameSpace + "\"" : "");
253         content.append(">\r\n");
254         if (args.length() > 0) {
255             Object[] o = ((JS)args.elementAt(0)).keys();
256             for(int i=0; i<o.length; i++)
257                 appendObject(o[i].toString(), ((JS)args.elementAt(0)).get(o[i].toString()), content);
258         }
259         content.append("    </" + methodname + "></SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n");
260         return content.toString();
261     }
262
263     SOAP(String url, String methodname, String action, String nameSpace) { this(url, methodname, new HTTP(url), action, nameSpace); }
264     SOAP(String url, String methodname, HTTP http, String action, String nameSpace) {
265         super(url, methodname, http);
266         this.action = action;
267         this.nameSpace = nameSpace;
268     }
269
270 }