KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > samples > client > DynamicInvoker


1 /*
2  * Copyright 2001-2004 The Apache Software Foundation.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package samples.client;
17
18 import org.apache.axis.Constants;
19 import org.apache.axis.utils.XMLUtils;
20 import org.apache.axis.encoding.ser.SimpleDeserializer;
21 import org.apache.axis.encoding.ser.ElementSerializerFactory;
22 import org.apache.axis.encoding.ser.ElementDeserializerFactory;
23 import org.apache.axis.encoding.ser.ElementDeserializer;
24 import org.apache.axis.wsdl.gen.Parser;
25 import org.apache.axis.wsdl.symbolTable.BaseType;
26 import org.apache.axis.wsdl.symbolTable.BindingEntry;
27 import org.apache.axis.wsdl.symbolTable.Parameter;
28 import org.apache.axis.wsdl.symbolTable.Parameters;
29 import org.apache.axis.wsdl.symbolTable.ServiceEntry;
30 import org.apache.axis.wsdl.symbolTable.SymTabEntry;
31 import org.apache.axis.wsdl.symbolTable.SymbolTable;
32 import org.apache.axis.wsdl.symbolTable.TypeEntry;
33 import org.w3c.dom.Element JavaDoc;
34
35 import javax.wsdl.Binding;
36 import javax.wsdl.Operation;
37 import javax.wsdl.Port;
38 import javax.wsdl.Service;
39 import javax.wsdl.extensions.soap.SOAPAddress;
40 import javax.xml.namespace.QName JavaDoc;
41 import javax.xml.rpc.Call JavaDoc;
42 import javax.xml.rpc.encoding.Deserializer JavaDoc;
43 import javax.xml.rpc.encoding.DeserializerFactory JavaDoc;
44 import java.util.HashMap JavaDoc;
45 import java.util.Iterator JavaDoc;
46 import java.util.List JavaDoc;
47 import java.util.Map JavaDoc;
48 import java.util.Vector JavaDoc;
49
50 /**
51  * This sample shows how to use Axis for completely dynamic invocations
52  * as it is completely stubless execution. It supports both doc/lit and rpc/encoded
53  * services. But this sample does not support complex types
54  * (it could if there was defined a to encode complex values as command line arguments).
55  *
56  * @author Davanum Srinivas (dims@yahoo.com)
57  */

58 public class DynamicInvoker {
59
60     /** Field wsdlParser */
61     private Parser wsdlParser = null;
62
63     /**
64      * Constructor DynamicInvoker
65      *
66      * @param wsdlURL
67      *
68      * @throws Exception
69      */

70     public DynamicInvoker(String JavaDoc wsdlURL) throws Exception JavaDoc {
71         // Start by reading in the WSDL using Parser
72
wsdlParser = new Parser();
73         System.out.println("Reading WSDL document from '" + wsdlURL + "'");
74         wsdlParser.run(wsdlURL);
75     }
76
77     /**
78      * Method usage
79      */

80     private static void usage() {
81         System.err.println(
82                 "Usage: java " + DynamicInvoker.class.getName() + " wsdlLocation "
83                 + "operationName[(portName)] "
84                 + "[argument1 ...]");
85         System.exit(1);
86     }
87
88     /**
89      * Method main
90      *
91      * @param args
92      *
93      * @throws Exception
94      */

95     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
96         if (args.length < 2) {
97             usage();
98         }
99         String JavaDoc wsdlLocation = (args.length > 0)
100                 ? args[0]
101                 : null;
102         String JavaDoc operationName = (args.length > 1)
103                 ? args[1]
104                 : null;
105         String JavaDoc portName = null;
106         try {
107             portName = operationName.substring(operationName.indexOf("(") + 1,
108                                                operationName.indexOf(")"));
109             operationName = operationName.substring(0, operationName.indexOf("("));
110         } catch (Exception JavaDoc ignored) {
111         }
112
113         DynamicInvoker invoker = new DynamicInvoker(wsdlLocation);
114         HashMap JavaDoc map = invoker.invokeMethod(operationName, portName, args);
115
116         for (Iterator JavaDoc it = map.entrySet().iterator(); it.hasNext();) {
117             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) it.next();
118             String JavaDoc key = (String JavaDoc) entry.getKey();
119             Object JavaDoc value = entry.getValue();
120             if (value instanceof Element JavaDoc) {
121                 System.out.println("====== " + key + " ======");
122                 XMLUtils.ElementToStream((Element JavaDoc) value, System.out);
123                 System.out.println("=========================");
124             } else {
125                 System.out.println(key + "=" + value);
126             }
127         }
128         System.out.println("\nDone!");
129     }
130
131     /**
132      * Method invokeMethod
133      *
134      * @param wsdlLocation
135      * @param operationName
136      * @param inputName
137      * @param outputName
138      * @param portName
139      * @param args
140      *
141      * @return
142      *
143      * @throws Exception
144      */

145     public HashMap JavaDoc invokeMethod(
146             String JavaDoc operationName, String JavaDoc portName, String JavaDoc[] args)
147             throws Exception JavaDoc {
148         String JavaDoc serviceNS = null;
149         String JavaDoc serviceName = null;
150         String JavaDoc operationQName = null;
151
152         System.out.println("Preparing Axis dynamic invocation");
153         Service service = selectService(serviceNS, serviceName);
154         Operation operation = null;
155         org.apache.axis.client.Service dpf = new org.apache.axis.client.Service(wsdlParser, service.getQName());
156
157         Vector JavaDoc inputs = new Vector JavaDoc();
158         Port port = selectPort(service.getPorts(), portName);
159         if (portName == null) {
160             portName = port.getName();
161         }
162         Binding binding = port.getBinding();
163         Call JavaDoc call = dpf.createCall(QName.valueOf(portName),
164                                    QName.valueOf(operationName));
165         ((org.apache.axis.client.Call)call).setTimeout(new Integer JavaDoc(15*1000));
166         ((org.apache.axis.client.Call)call).setProperty(ElementDeserializer.DESERIALIZE_CURRENT_ELEMENT, Boolean.TRUE);
167         
168         // Output types and names
169
Vector JavaDoc outNames = new Vector JavaDoc();
170
171         // Input types and names
172
Vector JavaDoc inNames = new Vector JavaDoc();
173         Vector JavaDoc inTypes = new Vector JavaDoc();
174         SymbolTable symbolTable = wsdlParser.getSymbolTable();
175         BindingEntry bEntry =
176                 symbolTable.getBindingEntry(binding.getQName());
177         Parameters parameters = null;
178         Iterator JavaDoc i = bEntry.getParameters().keySet().iterator();
179
180         while (i.hasNext()) {
181             Operation o = (Operation) i.next();
182             if (o.getName().equals(operationName)) {
183                 operation = o;
184                 parameters = (Parameters) bEntry.getParameters().get(o);
185                 break;
186             }
187         }
188         if ((operation == null) || (parameters == null)) {
189             throw new RuntimeException JavaDoc(operationName + " was not found.");
190         }
191
192         // loop over paramters and set up in/out params
193
for (int j = 0; j < parameters.list.size(); ++j) {
194             Parameter p = (Parameter) parameters.list.get(j);
195
196             if (p.getMode() == 1) { // IN
197
inNames.add(p.getQName().getLocalPart());
198                 inTypes.add(p);
199             } else if (p.getMode() == 2) { // OUT
200
outNames.add(p.getQName().getLocalPart());
201             } else if (p.getMode() == 3) { // INOUT
202
inNames.add(p.getQName().getLocalPart());
203                 inTypes.add(p);
204                 outNames.add(p.getQName().getLocalPart());
205             }
206         }
207
208         // set output type
209
if (parameters.returnParam != null) {
210
211             if(!parameters.returnParam.getType().isBaseType()) {
212                 ((org.apache.axis.client.Call)call).registerTypeMapping(org.w3c.dom.Element JavaDoc.class, parameters.returnParam.getType().getQName(),
213                             new ElementSerializerFactory(),
214                             new ElementDeserializerFactory());
215             }
216
217             // Get the QName for the return Type
218
QName JavaDoc returnType = org.apache.axis.wsdl.toJava.Utils.getXSIType(
219                     parameters.returnParam);
220             QName JavaDoc returnQName = parameters.returnParam.getQName();
221
222             outNames.add(returnQName.getLocalPart());
223         }
224
225         if (inNames.size() != args.length - 2)
226             throw new RuntimeException JavaDoc("Need " + inNames.size() + " arguments!!!");
227
228         for (int pos = 0; pos < inNames.size(); ++pos) {
229             String JavaDoc arg = args[pos + 2];
230             Parameter p = (Parameter) inTypes.get(pos);
231             inputs.add(getParamData((org.apache.axis.client.Call) call, p, arg));
232         }
233         System.out.println("Executing operation " + operationName + " with parameters:");
234         for (int j = 0; j < inputs.size(); j++) {
235             System.out.println(inNames.get(j) + "=" + inputs.get(j));
236         }
237         Object JavaDoc ret = call.invoke(inputs.toArray());
238         Map JavaDoc outputs = call.getOutputParams();
239         HashMap JavaDoc map = new HashMap JavaDoc();
240
241         for (int pos = 0; pos < outNames.size(); ++pos) {
242             String JavaDoc name = (String JavaDoc) outNames.get(pos);
243             Object JavaDoc value = outputs.get(name);
244
245             if ((value == null) && (pos == 0)) {
246                 map.put(name, ret);
247             } else {
248                 map.put(name, value);
249             }
250         }
251         return map;
252     }
253
254     /**
255      * Method getParamData
256      *
257      * @param c
258      * @param arg
259      */

260     private Object JavaDoc getParamData(org.apache.axis.client.Call c, Parameter p, String JavaDoc arg) throws Exception JavaDoc {
261         // Get the QName representing the parameter type
262
QName JavaDoc paramType = org.apache.axis.wsdl.toJava.Utils.getXSIType(p);
263
264         TypeEntry type = p.getType();
265         if (type instanceof BaseType && ((BaseType) type).isBaseType()) {
266             DeserializerFactory factory = c.getTypeMapping().getDeserializer(paramType);
267             Deserializer deserializer = factory.getDeserializerAs(Constants.AXIS_SAX);
268             if (deserializer instanceof SimpleDeserializer) {
269                 return ((SimpleDeserializer)deserializer).makeValue(arg);
270             }
271         }
272         throw new RuntimeException JavaDoc("not know how to convert '" + arg
273                                    + "' into " + c);
274     }
275
276     /**
277      * Method selectService
278      *
279      * @param def
280      * @param serviceNS
281      * @param serviceName
282      *
283      * @return
284      *
285      * @throws Exception
286      */

287     public Service selectService(String JavaDoc serviceNS, String JavaDoc serviceName)
288             throws Exception JavaDoc {
289         QName JavaDoc serviceQName = (((serviceNS != null)
290                 && (serviceName != null))
291                 ? new QName JavaDoc(serviceNS, serviceName)
292                 : null);
293         ServiceEntry serviceEntry = (ServiceEntry) getSymTabEntry(serviceQName,
294                                                                   ServiceEntry.class);
295         return serviceEntry.getService();
296     }
297
298     /**
299      * Method getSymTabEntry
300      *
301      * @param qname
302      * @param cls
303      *
304      * @return
305      */

306     public SymTabEntry getSymTabEntry(QName JavaDoc qname, Class JavaDoc cls) {
307         HashMap JavaDoc map = wsdlParser.getSymbolTable().getHashMap();
308         Iterator JavaDoc iterator = map.entrySet().iterator();
309
310         while (iterator.hasNext()) {
311             Map.Entry JavaDoc entry = (Map.Entry JavaDoc) iterator.next();
312             QName JavaDoc key = (QName JavaDoc) entry.getKey();
313             Vector JavaDoc v = (Vector JavaDoc) entry.getValue();
314
315             if ((qname == null) || qname.equals(qname)) {
316                 for (int i = 0; i < v.size(); ++i) {
317                     SymTabEntry symTabEntry = (SymTabEntry) v.elementAt(i);
318
319                     if (cls.isInstance(symTabEntry)) {
320                         return symTabEntry;
321                     }
322                 }
323             }
324         }
325         return null;
326     }
327
328     /**
329      * Method selectPort
330      *
331      * @param ports
332      * @param portName
333      *
334      * @return
335      *
336      * @throws Exception
337      */

338     public Port selectPort(Map JavaDoc ports, String JavaDoc portName) throws Exception JavaDoc {
339         Iterator JavaDoc valueIterator = ports.keySet().iterator();
340         while (valueIterator.hasNext()) {
341             String JavaDoc name = (String JavaDoc) valueIterator.next();
342
343             if ((portName == null) || (portName.length() == 0)) {
344                 Port port = (Port) ports.get(name);
345                 List JavaDoc list = port.getExtensibilityElements();
346
347                 for (int i = 0; (list != null) && (i < list.size()); i++) {
348                     Object JavaDoc obj = list.get(i);
349                     if (obj instanceof SOAPAddress) {
350                         return port;
351                     }
352                 }
353             } else if ((name != null) && name.equals(portName)) {
354                 return (Port) ports.get(name);
355             }
356         }
357         return null;
358     }
359 }
360
361
Popular Tags