KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > clients > DynamicInvoker


1 /*
2  * The Apache Software License, Version 1.1
3  *
4  *
5  * Copyright (c) 2002 The Apache Software Foundation. All rights
6  * reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  *
12  * 1. Redistributions of source code must retain the above copyright
13  * notice, this list of conditions and the following disclaimer.
14  *
15  * 2. Redistributions in binary form must reproduce the above copyright
16  * notice, this list of conditions and the following disclaimer in
17  * the documentation and/or other materials provided with the
18  * distribution.
19  *
20  * 3. The end-user documentation included with the redistribution,
21  * if any, must include the following acknowledgment:
22  * "This product includes software developed by the
23  * Apache Software Foundation (http://www.apache.org/)."
24  * Alternately, this acknowledgment may appear in the software itself,
25  * if and wherever such third-party acknowledgments normally appear.
26  *
27  * 4. The names "WSIF" and "Apache Software Foundation" must
28  * not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation and was
52  * originally based on software copyright (c) 2001, 2002, International
53  * Business Machines, Inc., http://www.apache.org. For more
54  * information on the Apache Software Foundation, please see
55  * <http://www.apache.org/>.
56  */

57
58 package clients;
59
60 import java.util.HashMap JavaDoc;
61 import java.util.Iterator JavaDoc;
62 import java.util.List JavaDoc;
63 import java.util.Map JavaDoc;
64 import java.util.StringTokenizer JavaDoc;
65
66 import javax.wsdl.Definition;
67 import javax.wsdl.Input;
68 import javax.wsdl.Operation;
69 import javax.wsdl.Output;
70 import javax.wsdl.Part;
71 import javax.wsdl.Port;
72 import javax.wsdl.PortType;
73 import javax.wsdl.Service;
74 import javax.xml.namespace.QName JavaDoc;
75
76 import org.apache.wsif.WSIFException;
77 import org.apache.wsif.WSIFMessage;
78 import org.apache.wsif.WSIFOperation;
79 import org.apache.wsif.WSIFPort;
80 import org.apache.wsif.WSIFService;
81 import org.apache.wsif.WSIFServiceFactory;
82 import org.apache.wsif.providers.soap.apacheaxis.WSIFDynamicProvider_ApacheAxis;
83 import org.apache.wsif.util.WSIFPluggableProviders;
84 import org.apache.wsif.util.WSIFUtils;
85
86 /**
87  * This sample shows how to use WSIF for completely dynamic invocations
88  * as it is completely stubless execution. This sample does not support
89  * complex types (it could if there was defined a to encode complex
90  * values as command line arguments).
91  *
92  * @author Sanjiva Weerawarana
93  * @author Alekander Slominski
94  */

95
96 public class DynamicInvoker {
97     private static void usage() {
98         System.err.println(
99             "Usage: java "
100                 + DynamicInvoker.class.getName()
101                 + " wsdlLocation "
102                 + "operationName[(portName)]:[inputMessageName]:[outputMessageName] "
103                 + "[soap|axis] [argument1 ...]");
104         System.exit(1);
105     }
106
107     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
108         if (args.length < 2)
109             usage();
110
111         String JavaDoc wsdlLocation = args.length > 0 ? args[0] : null;
112         String JavaDoc operationKey = args.length > 1 ? args[1] : null;
113         String JavaDoc portName = null;
114         String JavaDoc operationName = null;
115         String JavaDoc inputName = null;
116         String JavaDoc outputName = null;
117
118         StringTokenizer JavaDoc st = new StringTokenizer JavaDoc(operationKey, ":");
119         int tokens = st.countTokens();
120         int specType = 0;
121         if (tokens == 2) {
122             specType = operationKey.endsWith(":") ? 1 : 2;
123         } else if (tokens != 1 && tokens != 3)
124             usage();
125
126         while (st.hasMoreTokens()) {
127             if (operationName == null)
128                 operationName = st.nextToken();
129             else if (inputName == null && specType != 2)
130                 inputName = st.nextToken();
131             else if (outputName == null)
132                 outputName = st.nextToken();
133             else
134                 break;
135         }
136
137         try {
138             portName =
139                 operationName.substring(operationName.indexOf("(")+1, operationName.indexOf(")"));
140             operationName = operationName.substring(0, operationName.indexOf("("));
141         } catch (Exception JavaDoc ignored) {
142         }
143
144         String JavaDoc protocol = args.length > 2 ? args[2] : "";
145         int shift = 2;
146         if (protocol.equals("soap") || protocol.equals("axis"))
147             shift = 3;
148
149         HashMap JavaDoc map =
150             invokeMethod(
151                 wsdlLocation,
152                 operationName,
153                 inputName,
154                 outputName,
155                 portName,
156                 protocol,
157                 args,
158                 shift);
159
160         // print result
161
System.out.println("Result:");
162         for (Iterator JavaDoc it = map.keySet().iterator(); it.hasNext();) {
163             String JavaDoc name = (String JavaDoc) it.next();
164             System.out.println(name + "=" + map.get(name));
165         }
166         System.out.println("\nDone!");
167
168     }
169
170     public static HashMap JavaDoc invokeMethod(
171         String JavaDoc wsdlLocation,
172         String JavaDoc operationName,
173         String JavaDoc inputName,
174         String JavaDoc outputName,
175         String JavaDoc portName,
176         String JavaDoc protocol,
177         String JavaDoc[] args,
178         int argShift)
179         throws Exception JavaDoc {
180
181         String JavaDoc serviceNS = null;
182         String JavaDoc serviceName = null;
183         String JavaDoc portTypeNS = null;
184         String JavaDoc portTypeName = null;
185
186         // The default SOAP provider is the Apache SOAP provider. If Axis was specified
187
// then change that
188
if ("axis".equals(protocol)) {
189             WSIFPluggableProviders.overrideDefaultProvider(
190                 "http://schemas.xmlsoap.org/wsdl/soap/",
191                 new WSIFDynamicProvider_ApacheAxis());
192         }
193
194         System.out.println("Reading WSDL document from '" + wsdlLocation + "'");
195         Definition def = WSIFUtils.readWSDL(null, wsdlLocation);
196
197         System.out.println("Preparing WSIF dynamic invocation");
198
199         Service service = WSIFUtils.selectService(def, serviceNS, serviceName);
200
201         Map JavaDoc portTypes = WSIFUtils.getAllItems(def, "PortType");
202         // Really there should be a way to specify the portType
203
// for now just try to find one with the portName
204
if (portTypes.size() > 1 && portName != null) {
205             for (Iterator JavaDoc i=portTypes.keySet().iterator(); i.hasNext(); ) {
206                 QName JavaDoc qn = (QName JavaDoc) i.next();
207                 if (portName.equals(qn.getLocalPart())) {
208                   portTypeName = qn.getLocalPart();
209                   portTypeNS = qn.getNamespaceURI();
210                   break;
211                }
212             }
213         }
214         PortType portType = WSIFUtils.selectPortType(def, portTypeNS, portTypeName);
215
216         WSIFServiceFactory factory = WSIFServiceFactory.newInstance();
217         WSIFService dpf = factory.getService(def, service, portType);
218         WSIFPort port = null;
219         if (portName == null)
220             port = dpf.getPort();
221         else
222             port = dpf.getPort(portName);
223
224         if (inputName == null && outputName == null) {
225             // retrieve list of operations
226
List JavaDoc operationList = portType.getOperations();
227
228             // try to find input and output names for the operation specified
229
boolean found = false;
230             for (Iterator JavaDoc i = operationList.iterator(); i.hasNext();) {
231                 Operation op = (Operation) i.next();
232                 String JavaDoc name = op.getName();
233                 if (!name.equals(operationName)) {
234                     continue;
235                 }
236                 if (found) {
237                     throw new RuntimeException JavaDoc(
238                         "Operation '"
239                             + operationName
240                             + "' is overloaded. "
241                             + "Please specify the operation in the form "
242                             + "'operationName:inputMessageName:outputMesssageName' to distinguish it");
243                 }
244                 found = true;
245                 Input opInput = op.getInput();
246                 inputName = (opInput.getName() == null) ? null : opInput.getName();
247                 Output opOutput = op.getOutput();
248                 outputName = (opOutput.getName() == null) ? null : opOutput.getName();
249             }
250         }
251
252         WSIFOperation operation =
253             port.createOperation(operationName, inputName, outputName);
254         WSIFMessage input = operation.createInputMessage();
255         WSIFMessage output = operation.createOutputMessage();
256         WSIFMessage fault = operation.createFaultMessage();
257
258         // retrieve list of names and types for input and names for output
259
List JavaDoc operationList = portType.getOperations();
260
261         // find portType operation to prepare in/oout message w/ parts
262
boolean found = false;
263         String JavaDoc[] outNames = new String JavaDoc[0];
264         Class JavaDoc[] outTypes = new Class JavaDoc[0];
265         for (Iterator JavaDoc i = operationList.iterator(); i.hasNext();) {
266             Operation op = (Operation) i.next();
267             String JavaDoc name = op.getName();
268             if (!name.equals(operationName)) {
269                 continue;
270             }
271             if (found) {
272                 throw new RuntimeException JavaDoc("overloaded operations are not supported in this sample");
273             }
274             found = true;
275
276             //System.err.println("op = "+op);
277
Input opInput = op.getInput();
278
279             // first determine list of arguments
280
String JavaDoc[] inNames = new String JavaDoc[0];
281             Class JavaDoc[] inTypes = new Class JavaDoc[0];
282             if (opInput != null) {
283                 List JavaDoc parts = opInput.getMessage().getOrderedParts(null);
284                 unWrapIfWrappedDocLit(parts, name, def);
285                 int count = parts.size();
286                 inNames = new String JavaDoc[count];
287                 inTypes = new Class JavaDoc[count];
288                 retrieveSignature(parts, inNames, inTypes);
289             }
290             // now prepare out parameters
291

292             for (int pos = 0; pos < inNames.length; ++pos) {
293                 String JavaDoc arg = args[pos + argShift];
294                 Object JavaDoc value = null;
295                 Class JavaDoc c = inTypes[pos];
296                 if (c.equals(String JavaDoc.class)) {
297                     value = arg;
298                 } else if (c.equals(Double.TYPE)) {
299                     value = new Double JavaDoc(arg);
300                 } else if (c.equals(Float.TYPE)) {
301                     value = new Float JavaDoc(arg);
302                 } else if (c.equals(Integer.TYPE)) {
303                     value = new Integer JavaDoc(arg);
304                 } else if (c.equals(Boolean.TYPE)) {
305                     value = new Boolean JavaDoc(arg);
306                 } else {
307                     throw new RuntimeException JavaDoc("not know how to convert '" + arg + "' into " + c);
308                 }
309
310                 input.setObjectPart(inNames[pos], value);
311             }
312
313             Output opOutput = op.getOutput();
314             if (opOutput != null) {
315                 List JavaDoc parts = opOutput.getMessage().getOrderedParts(null);
316                 unWrapIfWrappedDocLit(parts, name+"Response", def);
317                 int count = parts.size();
318                 outNames = new String JavaDoc[count];
319                 outTypes = new Class JavaDoc[count];
320                 retrieveSignature(parts, outNames, outTypes);
321             }
322
323         }
324         if (!found) {
325             throw new RuntimeException JavaDoc(
326                 "no operation "
327                     + operationName
328                     + " was found in port type "
329                     + portType.getQName());
330         }
331
332         System.out.println("Executing operation " + operationName);
333         operation.executeRequestResponseOperation(input, output, fault);
334
335         HashMap JavaDoc map = new HashMap JavaDoc();
336         for (int pos = 0; pos < outNames.length; ++pos) {
337             String JavaDoc name = outNames[pos];
338             map.put(name, output.getObjectPart(name));
339         }
340
341         return map;
342     }
343
344     private static void retrieveSignature(
345         List JavaDoc parts,
346         String JavaDoc[] names,
347         Class JavaDoc[] types) {
348         // get parts in correct order
349
for (int i = 0; i < names.length; ++i) {
350             Part part = (Part) parts.get(i);
351             names[i] = part.getName();
352             QName JavaDoc partType = part.getTypeName();
353             if (partType == null) {
354                partType = part.getElementName();
355             }
356             if (partType == null) {
357                 throw new RuntimeException JavaDoc(
358                     "part " + names[i] + " must have type name declared");
359             }
360             // only limited number of types is supported
361
// cheerfully ignoring schema namespace ...
362
String JavaDoc s = partType.getLocalPart();
363             if ("string".equals(s)) {
364                 types[i] = String JavaDoc.class;
365             } else if ("double".equals(s)) {
366                 types[i] = Integer.TYPE;
367             } else if ("float".equals(s)) {
368                 types[i] = Float.TYPE;
369             } else if ("int".equals(s)) {
370                 types[i] = Integer.TYPE;
371             } else if ("boolean".equals(s)) {
372                 types[i] = Boolean.TYPE;
373             } else {
374                 throw new RuntimeException JavaDoc(
375                     "part type " + partType + " not supported in this sample");
376             }
377         }
378     }
379
380     /**
381      * Unwraps the top level part if this a wrapped DocLit message.
382      */

383     private static void unWrapIfWrappedDocLit(List JavaDoc parts, String JavaDoc operationName, Definition def) throws WSIFException {
384            Part p = WSIFUtils.getWrappedDocLiteralPart(parts, operationName);
385            if (p != null) {
386               List JavaDoc unWrappedParts = WSIFUtils.unWrapPart(p, def);
387               parts.remove(p);
388               parts.addAll(unWrappedParts);
389            }
390     }
391
392 }
393
Popular Tags