KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > axis > tools > ant > wsdl > Java2WsdlAntTask


1 /*
2  * Copyright 2002,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 org.apache.axis.tools.ant.wsdl;
17
18 import org.apache.axis.encoding.TypeMappingImpl;
19 import org.apache.axis.encoding.TypeMappingRegistryImpl;
20 import org.apache.axis.encoding.TypeMappingDelegate;
21 import org.apache.axis.utils.ClassUtils;
22 import org.apache.axis.wsdl.fromJava.Emitter;
23 import org.apache.tools.ant.AntClassLoader;
24 import org.apache.tools.ant.BuildException;
25 import org.apache.tools.ant.Project;
26 import org.apache.tools.ant.Task;
27 import org.apache.tools.ant.types.Path;
28 import org.apache.tools.ant.types.Reference;
29 import org.apache.tools.ant.types.Environment;
30 import org.apache.tools.ant.types.CommandlineJava;
31
32 import java.io.File JavaDoc;
33 import java.io.PrintWriter JavaDoc;
34 import java.io.StringWriter JavaDoc;
35 import java.util.HashMap JavaDoc;
36 import java.util.Iterator JavaDoc;
37 import java.util.LinkedList JavaDoc;
38 import java.util.List JavaDoc;
39 import java.util.Map JavaDoc;
40 import java.util.StringTokenizer JavaDoc;
41
42 /*
43  * Important. we autogenerate the ant task docs from this.
44  * after adding a new attribute
45  * 1. add the javadoc for the end users. Make it meaningful
46  * 2. get jakarta_ant/proposals/xdocs from ant CVS
47  * 3. run the xdocs target in tools/build.xml
48  * this creates xml files in xdocs/build
49  * 4. run proposals/xdocs/dvsl build.xml to create the html files
50  * these are also created under xdocs/build
51  * 5. copy the the html files to docs/ant
52  * 4. check in the changes in docs/ant
53  */

54 /**
55  * Generates a WSDL description from a Java class.
56  * @author Rich Scheuerle (scheu@us.ibm.com)
57  * @author Steve Loughran
58  * @ant.task category="axis" name="axis-java2wsdl"
59  */

60
61 public class Java2WsdlAntTask extends Task
62 {
63     private String JavaDoc namespace = "";
64     private String JavaDoc namespaceImpl = null;
65     private HashMap JavaDoc namespaceMap = new HashMap JavaDoc();
66     private String JavaDoc location = "";
67     private String JavaDoc locationImport = null;
68     private String JavaDoc output = "." ;
69     private String JavaDoc importSchema = null ;
70     private String JavaDoc input = null ;
71     private String JavaDoc outputImpl = null;
72     private String JavaDoc className = "." ;
73     private String JavaDoc servicePortName = null ;
74     private String JavaDoc portTypeName = null ;
75     private String JavaDoc bindingName = null ;
76     private String JavaDoc implClass = null;
77     private boolean useInheritedMethods = false;
78     private String JavaDoc exclude = null;
79     private String JavaDoc stopClasses = null;
80     private String JavaDoc typeMappingVersion = TypeMappingVersionEnum.DEFAULT_VERSION;
81     private String JavaDoc style = null;
82     private String JavaDoc serviceElementName=null;
83     private String JavaDoc methods=null;
84     private String JavaDoc use = null;
85     private MappingSet mappings=new MappingSet();
86     private String JavaDoc extraClasses = null;
87     private Path classpath = null;
88     private String JavaDoc soapAction = null;
89     private List JavaDoc complexTypes = new LinkedList JavaDoc();
90     private boolean isDeploy = false;
91     private CommandlineJava commandline = new CommandlineJava();
92
93     /**
94      * trace out parameters
95      * @param logLevel to log at
96      * @see org.apache.tools.ant.Project#log
97      */

98     public void traceParams(int logLevel) {
99         log("Running Java2WsdlAntTask with parameters:", logLevel);
100         log("\tnamespace:" + namespace, logLevel);
101         log("\tPkgtoNS:" + namespaceMap, logLevel);
102         log("\tlocation:" + location, logLevel);
103         log("\toutput:" + output, logLevel);
104         log("\timportSchema:" + importSchema, logLevel);
105         log("\tinput:" + input, logLevel);
106         log("\tclassName:" + className, logLevel);
107         log("\tservicePortName:" + servicePortName, logLevel);
108         log("\tportTypeName:" + portTypeName, logLevel);
109         log("\tbindingName:" + bindingName, logLevel);
110         log("\timplClass:" + implClass, logLevel);
111         log("\tinheritance:" + useInheritedMethods, logLevel);
112         log("\texcluded:" + exclude, logLevel);
113         log("\tstopClasses:" + stopClasses, logLevel);
114         log("\ttypeMappingVersion:" + typeMappingVersion, logLevel);
115         log("\tstyle:" + style, logLevel);
116         log("\toutputImpl:" + outputImpl, logLevel);
117         log("\tuse:" + use, logLevel);
118         log("\tnamespaceImpl:" + namespaceImpl, logLevel);
119         log("\tlocationImport:" + locationImport, logLevel);
120         log("\tserviceElementName:" + serviceElementName, logLevel);
121         log("\tmethods:" + methods, logLevel);
122         log("\textraClasses:" + extraClasses, logLevel);
123         log("\tsoapAction:" + soapAction, logLevel);
124         log("\tclasspath:" + classpath, logLevel);
125       
126 }
127
128     /**
129      * validation code
130      * @throws BuildException if validation failed
131      */

132     protected void validate()
133             throws BuildException {
134         if(className==null || className.length() ==0) {
135             throw new BuildException("No classname was specified");
136         }
137         if(location==null || location.length() == 0) {
138             throw new BuildException("No location was specified");
139         }
140     }
141
142     /**
143      * execute the task
144      * @throws BuildException
145      */

146     public void execute() throws BuildException {
147         AntClassLoader cl = new AntClassLoader(getClass().getClassLoader(),
148                 getProject(),
149                 classpath == null ? createClasspath() : classpath,
150                 false);
151         
152         ClassUtils.setDefaultClassLoader(cl);
153         //add extra classes to the classpath when the classpath attr is not null
154
if (extraClasses != null) {
155             StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc(extraClasses, " ,");
156             while (tokenizer.hasMoreTokens()) {
157                 String JavaDoc clsName = tokenizer.nextToken();
158                 ClassUtils.setClassLoader(clsName, cl);
159             }
160         }
161
162         CommandlineJava.SysProperties sysProperties =
163                 commandline.getSystemProperties();
164         if (sysProperties != null) {
165             sysProperties.setSystem();
166         }
167         try {
168             traceParams(Project.MSG_VERBOSE);
169             validate();
170
171             // Instantiate the emitter
172
Emitter emitter = new Emitter();
173             //do the mappings, packages are the key for this map
174
mappings.execute(this,namespaceMap, true);
175             if (!namespaceMap.isEmpty()) {
176                 emitter.setNamespaceMap(namespaceMap);
177             }
178             if (servicePortName != null) {
179                 emitter.setServicePortName(servicePortName);
180             }
181             if (portTypeName != null) {
182                 emitter.setPortTypeName(portTypeName);
183             }
184             if (bindingName != null) {
185                 emitter.setBindingName(bindingName);
186             }
187             log("Java2WSDL " + className, Project.MSG_INFO);
188             emitter.setCls(className);
189             if (implClass != null) {
190                 emitter.setImplCls(implClass);
191             }
192             if (exclude != null) {
193                 emitter.setDisallowedMethods(exclude);
194             }
195             if (stopClasses != null) {
196                 emitter.setStopClasses(stopClasses);
197             }
198             if (extraClasses != null) {
199                 emitter.setExtraClasses(extraClasses);
200             }
201
202             TypeMappingRegistryImpl tmr = new TypeMappingRegistryImpl();
203             tmr.doRegisterFromVersion(typeMappingVersion);
204             emitter.setTypeMappingRegistry(tmr);
205
206             // Create TypeMapping and register complex types
207
TypeMappingDelegate tmi = (TypeMappingDelegate)tmr.getDefaultTypeMapping();
208             Iterator JavaDoc i = complexTypes.iterator();
209             while (i.hasNext()) {
210                 ((ComplexType) i.next()).register(tmi);
211             }
212             
213             if (style != null) {
214                 emitter.setStyle(style);
215             }
216
217             if (use != null) {
218                 emitter.setUse(use);
219             }
220
221             if (importSchema != null) {
222                 emitter.setInputSchema(importSchema);
223             }
224             if (input != null) {
225                 emitter.setInputWSDL(input);
226             }
227             emitter.setIntfNamespace(namespace);
228             emitter.setImplNamespace(namespaceImpl);
229             emitter.setLocationUrl(location);
230             emitter.setImportUrl(locationImport);
231             emitter.setUseInheritedMethods(useInheritedMethods);
232             if(serviceElementName!=null) {
233                 emitter.setServiceElementName(serviceElementName);
234             }
235             if(methods!=null) {
236                 emitter.setAllowedMethods(methods);
237             }
238             if (soapAction != null) {
239                 emitter.setSoapAction(soapAction);
240             }
241             if (outputImpl == null) {
242                 // Normal case
243
emitter.emit(output, Emitter.MODE_ALL);
244             } else {
245                 // Emit interface and implementation wsdls
246
emitter.emit(output, outputImpl);
247             }
248
249             if (isDeploy == true) {
250                 generateServerSide(emitter, (outputImpl != null) ? outputImpl : output);
251             }
252
253         } catch(BuildException b) {
254             //pass build exceptions up the wire
255
throw b;
256         } catch (Throwable JavaDoc t) {
257             //other trouble: stack trace the trouble and throw an exception
258
StringWriter JavaDoc writer = new StringWriter JavaDoc();
259             t.printStackTrace(new PrintWriter JavaDoc(writer));
260             log(writer.getBuffer().toString(), Project.MSG_ERR);
261             throw new BuildException("Error while running " + getClass().getName(), t);
262         } finally {
263             if (sysProperties != null) {
264                 sysProperties.restoreSystem();
265             }
266         }
267     }
268
269     /**
270      * The name of the output WSDL file.
271      * If not specified, a suitable default WSDL file is written into
272      * the current directory.
273      * @param parameter
274      */

275     public void setOutput(File JavaDoc parameter) {
276         this.output = parameter.getPath();
277     }
278
279     /**
280      * Option attribute that indicates the name of an XML Schema file that
281      * should be physically imported into the generated WSDL.
282      * @param parameter
283      */

284     public void setImportSchema(File JavaDoc parameter) throws BuildException {
285         try {
286             this.importSchema = parameter.toURL().toString();
287         } catch (java.io.IOException JavaDoc ioe) {
288             throw new BuildException(ioe);
289         }
290     }
291
292     /**
293      * Optional attribute that indicates the name of the input wsdl file.
294      * The output wsdl file will contain everything from the input wsdl
295      * file plus the new constructs. If a new construct is already present
296      * in the input wsdl file, it is not added. This option is useful for
297      * constructing a wsdl file with multiple ports, bindings, or portTypes.
298      * @param parameter filename
299      */

300     public void setInput(File JavaDoc parameter) {
301         this.input = parameter.getPath();
302     }
303
304     /**
305      * Use this option to indicate the name of the output implementation WSDL
306      * file. If specified, Java2WSDL will produce separate interface and implementation
307      * WSDL files. If not, a single WSDL file is generated
308      * @param parameter
309      */

310     public void setOutputImpl(File JavaDoc parameter) {
311         this.outputImpl = parameter.getPath();
312     }
313
314     /**
315      * The url of the location of the service. The name after the last slash or
316      * backslash is the name of the service port (unless overridden by the -s
317      * option). The service port address location attribute is assigned the
318      * specified value.
319      * @param parameter a URL
320      */

321     public void setLocation(String JavaDoc parameter) {
322         this.location = parameter;
323     }
324
325     /**
326      * the location of the interface WSDL when generating an implementation WSDL
327      * Required when <tt>outputImpl</tt> is set
328      * @param parameter URL?
329      */

330     public void setLocationImport(String JavaDoc parameter) {
331         this.locationImport = parameter;
332     }
333
334     /**
335      * the class name to import, eg. org.example.Foo. Required.
336      * The class must be on the classpath.
337      * @param parameter fully qualified class name
338      */

339     public void setClassName(String JavaDoc parameter) {
340         this.className = parameter;
341     }
342
343     /**
344      * Sometimes extra information is available in the implementation class
345      * file. Use this option to specify the implementation class.
346      * @param parameter
347      */

348     public void setImplClass(String JavaDoc parameter) {
349         this.implClass = parameter;
350     }
351
352     /**
353      * service port name (obtained from location if not specified)
354      * @param parameter portname
355      */

356     public void setServicePortName(String JavaDoc parameter) {
357         this.servicePortName = parameter;
358     }
359
360     /**
361      * Indicates the name to use use for the portType element.
362      * If not specified, the class-of-portType name is used.
363      * @param parameter
364      */

365     public void setPortTypeName(String JavaDoc parameter) {
366         this.portTypeName = parameter;
367     }
368
369     /**
370      * The name to use use for the binding element.
371      * If not specified, the value of the
372      * <tt>servicePortName</tt> + "SoapBinding" is used.
373      * @param parameter
374      */

375     public void setBindingName(String JavaDoc parameter) {
376         this.bindingName = parameter;
377     }
378
379     /**
380      * the target namespace. Required.
381      * @param parameter
382      */

383     public void setNamespace(String JavaDoc parameter) {
384         this.namespace = parameter;
385     }
386
387     /**
388      * Namespace of the implementation WSDL.
389      * @param parameter
390      */

391     public void setNamespaceImpl(String JavaDoc parameter) {
392         this.namespaceImpl = parameter;
393     }
394
395     /**
396      * should inherited methods be exported too? Default=false
397      * @param parameter
398      */

399     public void setUseInheritedMethods(boolean parameter) {
400         this.useInheritedMethods = parameter;
401     }
402
403     /**
404      * Comma separated list of methods to exclude from the wsdl file.
405      * @param exclude
406      */

407     public void setExclude(String JavaDoc exclude) {
408         this.exclude = exclude;
409     }
410
411     /**
412      * Comma separated list of classes which stop the Java2WSDL
413      * inheritance search.
414      * @param stopClasses
415      */

416     public void setStopClasses(String JavaDoc stopClasses) {
417         this.stopClasses = stopClasses;
418     }
419
420     /**
421      * The style of the WSDL document: RPC, DOCUMENT or WRAPPED.
422      * If RPC, a rpc/encoded wsdl is generated. If DOCUMENT, a
423      * document/literal wsdl is generated. If WRAPPED, a
424      * document/literal wsdl is generated using the wrapped approach.
425      * @param style
426      */

427     public void setStyle(String JavaDoc style) {
428         this.style = style;
429     }
430
431     /**
432      * add a mapping of namespaces to packages
433      */

434     public void addMapping(NamespaceMapping mapping) {
435         mappings.addMapping(mapping);
436     }
437
438     /**
439      * add a mapping of namespaces to packages
440      */

441     public void addMappingSet(MappingSet mappingset) {
442         mappings.addMappingSet(mappingset);
443     }
444
445
446     /**
447      * the default type mapping registry to use. Either 1.1 or 1.2.
448      * Default is 1.1
449      * @param parameter new version
450      */

451     public void setTypeMappingVersion(TypeMappingVersionEnum parameter) {
452         this.typeMappingVersion = parameter.getValue();
453     }
454
455     /**
456      * If this option is specified, only the indicated methods in your
457      * interface class will be exported into the WSDL file. The methods list
458      * must be comma separated. If not specified, all methods declared in
459      * the interface class will be exported into the WSDL file
460      * @param methods list of methods
461      */

462     public void setMethods(String JavaDoc methods) {
463         this.methods = methods;
464     }
465
466     /**
467      * Set the use option
468      */

469     public void setUse(String JavaDoc use) {
470         this.use = use;
471     }
472
473     /**
474      * the name of the service element.
475      * If not specified, the service element is the <tt>portTypeName</tt>Service.
476      * @param serviceElementName
477      */

478     public void setServiceElementName(String JavaDoc serviceElementName) {
479         this.serviceElementName = serviceElementName;
480     }
481
482     /**
483      * A comma separated list of classes to add to the classpath.
484      */

485     public void setExtraClasses(String JavaDoc extraClasses) {
486         this.extraClasses = extraClasses;
487     }
488     
489     /**
490      * The setter for the "soapAction" attribute
491      */

492     public void setSoapAction( String JavaDoc soapAction ) {
493         this.soapAction = soapAction;
494     }
495
496     /**
497      * Nested element for Complex Types.
498      * Each Complex Type uses the following fields:
499      * @param ct
500      */

501      public void addComplexType(ComplexType ct) {
502         complexTypes.add(ct);
503     }
504
505     /**
506      * Set the optional classpath
507      *
508      * @param classpath the classpath to use when loading class
509      */

510     public void setClasspath(Path classpath) {
511         createClasspath().append(classpath);
512     }
513
514     /**
515      * Set the optional classpath
516      *
517      * @return a path instance to be configured by the Ant core.
518      */

519     public Path createClasspath() {
520         if (classpath == null) {
521             classpath = new Path(getProject());
522             classpath = classpath.concatSystemClasspath();
523         }
524         return classpath.createPath();
525     }
526
527     /**
528      * Set the reference to an optional classpath
529      *
530      * @param r the id of the Ant path instance to act as the classpath
531      */

532     public void setClasspathRef(Reference r) {
533         createClasspath().setRefid(r);
534     }
535
536     /**
537      * Adds a system property that tests can access.
538      * @param sysp environment variable to add
539      */

540     public void addSysproperty(Environment.Variable sysp) {
541         commandline.addSysproperty(sysp);
542     }
543     
544     /**
545      * Sets the deploy flag
546      * @param deploy true if deploy mode
547      */

548     public void setDeploy(boolean deploy) {
549         this.isDeploy = deploy;
550     }
551     
552     /**
553      * Generate the server side artifacts from the generated WSDL
554      *
555      * @param j2w the Java2WSDL emitter
556      * @param wsdlFileName the generated WSDL file
557      * @throws Exception
558      */

559     protected void generateServerSide(Emitter j2w, String JavaDoc wsdlFileName) throws Exception JavaDoc {
560         org.apache.axis.wsdl.toJava.Emitter w2j = new org.apache.axis.wsdl.toJava.Emitter();
561         File JavaDoc wsdlFile = new File JavaDoc(wsdlFileName);
562         w2j.setServiceDesc(j2w.getServiceDesc());
563         w2j.setQName2ClassMap(j2w.getQName2ClassMap());
564         w2j.setOutputDir(wsdlFile.getParent());
565         w2j.setServerSide(true);
566         w2j.setDeploy(true);
567         w2j.setHelperWanted(true);
568
569         // setup namespace-to-package mapping
570
String JavaDoc ns = j2w.getIntfNamespace();
571         String JavaDoc clsName = j2w.getCls().getName();
572         int idx = clsName.lastIndexOf(".");
573         String JavaDoc pkg = null;
574         if (idx > 0) {
575             pkg = clsName.substring(0, idx);
576             w2j.getNamespaceMap().put(ns, pkg);
577         }
578         
579         Map JavaDoc nsmap = j2w.getNamespaceMap();
580         if (nsmap != null) {
581             for (Iterator JavaDoc i = nsmap.keySet().iterator(); i.hasNext(); ) {
582                 pkg = (String JavaDoc) i.next();
583                 ns = (String JavaDoc) nsmap.get(pkg);
584                 w2j.getNamespaceMap().put(ns, pkg);
585             }
586         }
587         
588         // set 'deploy' mode
589
w2j.setDeploy(true);
590         
591         if (j2w.getImplCls() != null) {
592             w2j.setImplementationClassName(j2w.getImplCls().getName());
593         } else {
594             if (!j2w.getCls().isInterface()) {
595                 w2j.setImplementationClassName(j2w.getCls().getName());
596             } else {
597                 throw new Exception JavaDoc("implementation class is not specified.");
598             }
599         }
600         
601         w2j.run(wsdlFileName);
602     }
603 }
604
Popular Tags