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