bugfix in url parsing for HTTP.java
[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());
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(new JSArray());
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         Object me = 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         if (parent != null && parent instanceof JSArray) {
149             objects.removeElementAt(objects.size() - 1);
150             ((JSArray)parent).addElement(me);
151
152         } else if (parent != null && parent instanceof JS) {
153             objects.removeElementAt(objects.size() - 1);
154             try {
155                 ((JS)parent).put(name, me);
156             } catch (JSExn e) {
157                 throw new Error("this should never happen");
158             }
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 JSExn {
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         } else if (o instanceof Stream) {
183             try {
184                 sb.append("                <" + name + " xsi:type=\"SOAP-ENC:base64\">\r\n");
185                 InputStream is = ((Stream)o).getInputStream();
186                 byte[] buf = new byte[54];
187                 while(true) {
188                     int numread = is.read(buf, 0, 54);
189                     if (numread == -1) break;
190                     byte[] writebuf = buf;
191                     if (numread < buf.length) {
192                         writebuf = new byte[numread];
193                         System.arraycopy(buf, 0, writebuf, 0, numread);
194                     }
195                     sb.append("              ");
196                     sb.append(new String(Base64.encode(writebuf)));
197                     sb.append("\r\n");
198                 }
199                 sb.append(((Boolean)o).booleanValue() ? "1" : "0");
200                 sb.append("</" + name + ">\r\n");
201             } catch (IOException e) {
202                 if (Log.on) Log.info(this, "caught IOException while attempting to send a ByteStream via SOAP");
203                 if (Log.on) Log.info(this, e);
204                 throw new JSExn("caught IOException while attempting to send a ByteStream via SOAP");
205             }
206
207         } else if (o instanceof String) {
208             sb.append("                <" + name + " xsi:type=\"xsd:string\">");
209             String s = (String)o;
210             if (s.indexOf('<') == -1 && s.indexOf('&') == -1) {
211                 sb.append(s);
212             } else {
213                 char[] cbuf = s.toCharArray();
214                 while(true) {
215                     int oldi = 0, i=0;
216                     while(i < cbuf.length && cbuf[i] != '<' && cbuf[i] != '&') i++;
217                     sb.append(cbuf, oldi, i);
218                     if (i == cbuf.length) break;
219                     if (cbuf[i] == '<') sb.append("&lt;");
220                     else if (cbuf[i] == '&') sb.append("&amp;");
221                     i = oldi = i + 1;
222                 }
223             }
224             sb.append("</" + name + ">\r\n");
225
226         } else if (o instanceof JSArray) {
227             JSArray a = (JSArray)o;
228             sb.append("                <" + name + " SOAP-ENC:arrayType=\"xsd:ur-type[" + a.length() + "]\">");
229             for(int i=0; i<a.length(); i++) appendObject("item", a.elementAt(i), sb);
230             sb.append("</" + name + ">\r\n");
231
232         } else if (o instanceof JS) {
233             JS j = (JS)o;
234             sb.append("                <" + name + ">");
235             Enumeration e = j.keys();
236             while(e.hasMoreElements()) {
237                 Object key = e.nextElement();
238                 appendObject((String)key, j.get(key), sb);
239             }
240             sb.append("</" + name + ">\r\n");
241
242         }
243     }
244
245     protected String buildRequest(JSArray args) throws JSExn, IOException {
246         // build up the request
247         StringBuffer content = new StringBuffer();
248         content.append("SOAPAction: " + action + "\r\n\r\n");
249         content.append("<?xml version=\"1.0\"?>\r\n");
250         content.append("<SOAP-ENV:Envelope SOAP-ENV:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
251         content.append("                   xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\"\r\n");
252         content.append("                   xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\"\r\n");
253         content.append("                   xmlns:xsd=\"http://www.w3.org/1999/XMLSchema\"\r\n");
254         content.append("                   xmlns:xsi=\"http://www.w3.org/1999/XMLSchema-instance\">\r\n");
255         content.append("<SOAP-ENV:Body>\r\n");
256         content.append("    <");
257         content.append(method);
258         content.append(nameSpace != null ? " xmlns=\"" + nameSpace + "\"" : "");
259         content.append(">\r\n");
260         if (args.length() > 0) {
261             Enumeration e = ((JS)args.elementAt(0)).keys();
262             while(e.hasMoreElements()) {
263                 Object key = e.nextElement();
264                 appendObject((String)key, ((JS)args.elementAt(0)).get(key), content);
265             }
266         }
267         content.append("    </" + method + "></SOAP-ENV:Body></SOAP-ENV:Envelope>\r\n");
268         return content.toString();
269     }
270
271     public SOAP(String url, String methodname, String action, String nameSpace) {
272         super(url, methodname);
273         this.action = action;
274         this.nameSpace = nameSpace;
275     }
276     public SOAP(String url, String methodname, SOAP httpSource, String action, String nameSpace) {
277         super(url, methodname, httpSource);
278         this.action = action;
279         this.nameSpace = nameSpace;
280     }
281
282 }