fbbb9bc018133b52721e74a8d633caee61178079
[org.ibex.core.git] / src / org / ibex / net / SOAP.java
1 // Copyright 2004 Adam Megacz, see the COPYING file for licensing [GPL]
2 package org.ibex.net;
3
4 import java.io.*;
5 import java.util.*;
6 import org.ibex.js.*;
7 import org.ibex.util.*;
8 import org.ibex.crypto.*;
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 public 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(Object name) {
31         return new SOAP(url, (method.equals("") ? "" : method + ".") + name.toString(), this, action, nameSpace); }
32
33
34     // Methods to Recieve and parse SOAP Responses ////////////////////////////////////////////////////
35
36     public void startElement(String name, String[] keys, Object[] vals, int line, int col) {
37
38         content.reset();
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 JS.O());
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("base64")) {
63                     objects.removeElementAt(objects.size() - 1);
64                     objects.addElement(new byte[] { });
65                 } else if (value.endsWith("null")) {
66                     objects.removeElementAt(objects.size() - 1);
67                     objects.addElement(null);
68                 } else if (value.endsWith("arrayType") || value.endsWith("JSArray") || key.endsWith("arrayType")) {
69                     objects.removeElementAt(objects.size() - 1);
70                     objects.addElement(JS.newArray());
71                 }
72             }
73         }
74     }
75
76     public void endElement(String name, int line, int col) {
77
78         if (name.equals("SOAP-ENV:Envelope")) return;
79         if (name.equals("SOAP-ENV:Body")) return;
80
81         if (content.size() > 0 && content.toString().trim().length() > 0) {
82
83             // remove ourselves
84             Object me = objects.elementAt(objects.size() - 1);
85
86             if (fault || me instanceof String) {
87                 objects.removeElementAt(objects.size() - 1);
88                 objects.addElement(new String(content.getBuf(), 0, content.size()).intern());
89                 content.reset();
90
91             } else if (me instanceof byte[]) {
92                 objects.removeElementAt(objects.size() - 1);
93                 objects.addElement(new Stream.ByteArray(Base64.decode(new String(content.getBuf(), 0, content.size())), null));
94                 content.reset();                
95
96             } else if (me instanceof Integer) {
97                 objects.removeElementAt(objects.size() - 1);
98                 objects.addElement(new Integer(new String(content.getBuf(), 0, content.size())));
99                 content.reset();
100                 
101             } else if (me instanceof Boolean) {
102                 objects.removeElementAt(objects.size() - 1);
103                 String s = new String(content.getBuf(), 0, content.size()).trim();
104                 if (s.equals("1") || s.equals("true")) objects.addElement(Boolean.TRUE);
105                 else objects.addElement(Boolean.FALSE);
106                 content.reset();
107                 
108             } else if (me instanceof Double) {
109                 objects.removeElementAt(objects.size() - 1);
110                 objects.addElement(new Double(new String(content.getBuf(), 0, content.size())));
111                 content.reset();
112                 
113             } else {
114                 // okay, we got PCDATA for what is supposedly a
115                 // struct... somebody's not adding their type info...
116                 String s = new String(content.getBuf(), 0, content.size()).trim();
117                 boolean hasdot = false;
118                 for(int i=0; i<s.length(); i++) {
119                     if (s.charAt(i) == '.') hasdot = true;
120                     if (!Character.isDigit(s.charAt(i))) {
121                         objects.removeElementAt(objects.size() - 1);
122                         objects.addElement(s);
123                         return;
124                     }
125                 }
126                 if (hasdot) {
127                     objects.removeElementAt(objects.size() - 1);
128                     objects.addElement(new Double(s));
129                 } else {
130                     objects.removeElementAt(objects.size() - 1);
131                     objects.addElement(new Integer(s));
132                 }
133                 content.reset();
134             }
135
136         }
137         
138         // remove ourselves
139         JS me = (JS) objects.elementAt(objects.size() - 1);
140
141         // find our parent
142         Object parent = objects.size() > 1 ? objects.elementAt(objects.size() - 2) : null;
143
144         // we want to fold stuff back into the fault object
145         if (objects.size() < 2) return;
146
147         // our parent "should" be an aggregate type -- add ourselves to it.
148         // FIXME: Can we get away without JSArray being public?
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(JS.S(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, JS o, StringBuffer sb) throws JSExn {
167         // FIXME: Update for new api
168         /*
169         if (o instanceof Number) {
170             if ((double)((Number)o).intValue() == ((Number)o).doubleValue()) {
171                 sb.append("                <" + name + " xsi:type=\"xsd:int\">");
172                 sb.append(((Number)o).intValue());
173                 sb.append("</" + name + ">\r\n");
174             } else {
175                 sb.append("                <" + name + " xsi:type=\"xsd:double\">");
176                 sb.append(o);
177                 sb.append("</" + name + ">\r\n");
178             }
179
180         } else if (o instanceof Boolean) {
181             sb.append("                <" + name + " xsi:type=\"xsd:boolean\">");
182             sb.append(((Boolean)o).booleanValue() ? "true" : "false");
183             sb.append("</" + name + ">\r\n");
184
185         } else if (o instanceof Stream) {
186             try {
187                 sb.append("                <" + name + " xsi:type=\"SOAP-ENC:base64\">\r\n");
188                 InputStream is = ((Stream)o).getInputStream();
189                 byte[] buf = new byte[54];
190                 while(true) {
191                     int numread = is.read(buf, 0, 54);
192                     if (numread == -1) break;
193                     byte[] writebuf = buf;
194                     if (numread < buf.length) {
195                         writebuf = new byte[numread];
196                         System.arraycopy(buf, 0, writebuf, 0, numread);
197                     }
198                     sb.append("              ");
199                     sb.append(new String(Base64.encode(writebuf)));
200                     sb.append("\r\n");
201                 }
202                 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
203                 sb.append("</" + name + ">\r\n");
204             } catch (IOException e) {
205                 if (Log.on) Log.info(this, "caught IOException while attempting to send a ByteStream via SOAP");
206                 if (Log.on) Log.info(this, e);
207                 throw new JSExn("caught IOException while attempting to send a ByteStream via SOAP");
208             }
209
210         } else if (o instanceof String) {
211             sb.append("                <" + name + " xsi:type=\"xsd:string\">");
212             String s = (String)o;
213             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
214                 sb.append(s);
215             } else {
216                 char[] cbuf = s.toCharArray();
217                 while(true) {
218                     int oldi = 0, i=0;
219                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
220                     sb.append(cbuf, oldi, i);
221                     if (i == cbuf.length) break;
222                     if (cbuf[i] == '<') sb.append("&lt;");
223                     else if (cbuf[i] == '&') sb.append("&amp;");
224                     i = oldi = i + 1;
225                 }
226             }
227             sb.append("</" + name + ">\r\n");
228
229         } else if (o instanceof JSArray) {
230             JSArray a = (JSArray)o;
231             sb.append("                <" + name + " SOAP-ENC:arrayType=\"xsd:ur-type[" + a.length() + "]\">");
232             for(int i=0; i<a.length(); i++) appendObject("item", a.elementAt(i), sb);
233             sb.append("</" + name + ">\r\n");
234
235         } else if (o instanceof JS) {
236             JS j = (JS)o;
237             sb.append("                <" + name + ">");
238             Enumeration e = j.keys();
239             while(e.hasMoreElements()) {
240                 Object key = e.nextElement();
241                 appendObject((String)key, j.get(key), sb);
242             }
243             sb.append("</" + name + ">\r\n");
244
245         }*/
246     }
247
248     protected String buildRequest(JS[] args) throws JSExn, IOException {
249         // build up the request
250         StringBuffer content = new StringBuffer();
251         content.append("SOAPAction: " + action + "\r\n\r\n");
252         content.append("<?xml version=\"1.0\"?>\r\n");
253         content.append("<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
254         content.append("                   xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
255         content.append("                   xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n");
256         content.append("                   xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"\r\n");
257         content.append("                   xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">\r\n");
258         content.append("<SOAP-ENV:Body>\r\n");
259         content.append("    <");
260         content.append(method);
261         content.append(nameSpace != null ? " xmlns=\"" + nameSpace + "\"" : "");
262         content.append(">\r\n");
263         if (args.length > 0) {
264             Enumeration e = args[0].keys();
265             while(e.hasMoreElements()) {
266                 JS key = e.nextElement();
267                 appendObject(JS.toString(key), args[0].get(key), content);
268             }
269         }
270         content.append("    </" + method + "></SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n");
271         return content.toString();
272     }
273
274     public SOAP(String url, String methodname, String action, String nameSpace) {
275         super(url, methodname);
276         this.action = action;
277         this.nameSpace = nameSpace;
278     }
279     public SOAP(String url, String methodname, SOAP httpSource, String action, String nameSpace) {
280         super(url, methodname, httpSource);
281         this.action = action;
282         this.nameSpace = nameSpace;
283     }
284
285 }