mass rename and rebranding from xwt to ibex - fixed to use ixt files
[org.ibex.core.git] / src / org / ibex / SOAP.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex;
3
4 import java.io.*;
5 import java.util.*;
6 import org.ibex.js.*;
7 import org.ibex.util.*;
8 import org.bouncycastle.util.encoders.Base64;
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) {
31         return new SOAP(url.toString(), (method.equals("") ? "" : method + ".") + name, http, 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         content.reset();
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 JS());
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("JSArray") || key.endsWith("arrayType")) {
70                     objects.removeElementAt(objects.size() - 1);
71                     objects.addElement(new JSArray());
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 Stream.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())), null));
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 JSArray) {
150             objects.removeElementAt(objects.size() - 1);
151             ((JSArray)parent).addElement(me);
152
153         } else if (parent != null && parent instanceof JS) {
154             objects.removeElementAt(objects.size() - 1);
155             try {
156                 ((JS)parent).put(name, me);
157             } catch (JSExn e) {
158                 throw new Error("this should never happen");
159             }
160
161         }
162
163     }
164
165     /** Appends the SOAP representation of <code>o</code> to <code>sb</code> */
166     void appendObject(String name, Object o, StringBuffer sb) throws JSExn {
167         if (o instanceof Number) {
168             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
169                 sb.append("                <" + name + " xsi:type=\"xsd:int\">");
170                 sb.append(((Number)o).intValue());
171                 sb.append("</" + name + ">\r\n");
172             } else {
173                 sb.append("                <" + name + " xsi:type=\"xsd:double\">");
174                 sb.append(o);
175                 sb.append("</" + name + ">\r\n");
176             }
177
178         } else if (o instanceof Boolean) {
179             sb.append("                <" + name + " xsi:type=\"xsd:boolean\">");
180             sb.append(((Boolean)o).booleanValue() ? "true" : "false");
181             sb.append("</" + name + ">\r\n");
182
183         } else if (o instanceof Stream) {
184             try {
185                 sb.append("                <" + name + " xsi:type=\"SOAP-ENC:base64\">\r\n");
186                 InputStream is = ((Stream)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.info(this, "caught IOException while attempting to send a ByteStream via SOAP");
204                 if (Log.on) Log.info(this, e);
205                 throw new JSExn("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 JSArray) {
228             JSArray a = (JSArray)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             Enumeration e = j.keys();
237             while(e.hasMoreElements()) {
238                 Object key = e.nextElement();
239                 appendObject((String)key, j.get(key), sb);
240             }
241             sb.append("</" + name + ">\r\n");
242
243         }
244     }
245
246     protected String buildRequest(JSArray args) throws JSExn, IOException {
247         // build up the request
248         StringBuffer content = new StringBuffer();
249         content.append("SOAPAction: " + action + "\r\n\r\n");
250         content.append("<?xml version=\"1.0\"?>\r\n");
251         content.append("<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
252         content.append("                   xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
253         content.append("                   xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n");
254         content.append("                   xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"\r\n");
255         content.append("                   xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">\r\n");
256         content.append("<SOAP-ENV:Body>\r\n");
257         content.append("    <");
258         content.append(method);
259         content.append(nameSpace != null ? " xmlns=\"" + nameSpace + "\"" : "");
260         content.append(">\r\n");
261         if (args.length() > 0) {
262             Enumeration e = ((JS)args.elementAt(0)).keys();
263             while(e.hasMoreElements()) {
264                 Object key = e.nextElement();
265                 appendObject((String)key, ((JS)args.elementAt(0)).get(key), content);
266             }
267         }
268         content.append("    </" + method + "></SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n");
269         return content.toString();
270     }
271
272     SOAP(String url, String methodname, String action, String nameSpace) {
273         this(url, methodname, new HTTP(url), action, nameSpace);
274     }
275     SOAP(String url, String methodname, HTTP http, String action, String nameSpace) {
276         super(url, methodname, http);
277         this.action = action;
278         this.nameSpace = nameSpace;
279     }
280
281 }