FileDocCategorySizeDatePackage
Wsdl2javaAntTask.javaAPI DocApache Axis 1.421706Sat Apr 22 18:57:28 BST 2006org.apache.axis.tools.ant.wsdl

Wsdl2javaAntTask

public class Wsdl2javaAntTask extends org.apache.tools.ant.Task
Create Java classes from local or remote WSDL. Mappings from namespaces to packages can be provided as nested <mapping> elements.

Proxy settings are taken from the java runtime settings of http.ProxyHost, http.ProxyPort, etc. The Ant task <setProxy> can set these. As well as the nested mapping elements, this task uses the file NStoPkg.properties in the project base directory for namespace mapping

This task does no dependency checking; files are generated whether they need to be or not. The exception to this is the Impl class, which is not overwritten if it exists. This is a safety measure. However, all other classes are generated overwriting anything that exists.

The safe way to use this task is to have it generate the java source in a build directory, then have a <copy> task selectively copy the files you need into a safe location. Again, copying into the source tree is dangerous, but a separate build/src tree is safe. Then include this separate tree in the <javac> task's src attribute to include it in the build. Implement your own implementation classes of the server stub and the test cases using the generated templates. If you want to add methods to autogenerated data types, consider subclassing them, or write helper classes.

Tip: if you <get> the wsdl, and use the <filesmatch> condition to compare the fetched wsdl with a catched copy, you can make the target that calls the axis-wsd2ljava task conditional on the WSDL having changed. This stops spurious code regeneration and follow-on rebuilds across the java source tree.

ant.task
category="axis" name="axis-wsdl2java"
author
Davanum Srinivas (dims@yahoo.com)
author
steve loughran

Fields Summary
private boolean
verbose
private boolean
debug
private boolean
quiet
private boolean
server
private boolean
skeletonDeploy
private boolean
testCase
private boolean
noImports
private boolean
all
private boolean
helperGen
private boolean
noWrapped
private boolean
allowInvalidURL
private String
factory
private HashMap
namespaceMap
private String
output
private String
protocolHandlerPkgs
private String
deployScope
private String
url
private String
typeMappingVersion
private long
timeout
private File
namespaceMappingFile
private MappingSet
mappings
private String
username
private String
password
private org.apache.tools.ant.types.Path
classpath
private List
nsIncludes
private List
nsExcludes
private List
properties
private String
implementationClassName
private org.apache.tools.ant.types.CommandlineJava
commandline
private boolean
printStackTraceOnFailure
do we print a stack trace when something goes wrong?
private boolean
failOnNetworkErrors
what action to take when there was a failure and the source was some URL
private boolean
wrapArrays
Constructors Summary
public Wsdl2javaAntTask()


      
    
Methods Summary
public voidaddMapping(NamespaceMapping mapping)
add a mapping of namespaces to packages

        mappings.addMapping(mapping);
    
public voidaddMappingSet(MappingSet mappingset)
add a mapping of namespaces to packages

        mappings.addMappingSet(mappingset);
    
public voidaddSysproperty(Environment.Variable sysp)
Adds a system property that tests can access.

param
sysp environment variable to add

        commandline.addSysproperty(sysp);
    
public org.apache.tools.ant.types.PathcreateClasspath()
set the classpath

return

        if (classpath == null) {
            classpath = new Path(getProject());
        }
        return classpath.createPath();
    
protected org.apache.axis.wsdl.toJava.EmittercreateEmitter()
This factory method makes it easier to extend this Ant task with a custom Emitter, if necessary.

        return new Emitter();
    
public org.apache.axis.wsdl.toJava.NamespaceSelectorcreateNsExclude()
Adds an additional namespace to the list to be excluded from source code generation.

        NamespaceSelector selector = new NamespaceSelector();
        nsExcludes.add(selector);
        return selector;
    
public org.apache.axis.wsdl.toJava.NamespaceSelectorcreateNsInclude()
Adds an additional namespace to the list to be included in source code generation.

        NamespaceSelector selector = new NamespaceSelector();
        nsIncludes.add(selector);
        return selector;
    
public org.apache.axis.wsdl.toJava.FactoryPropertycreateProperty()
Adds a property name/value pair for specialized JavaGeneratorFactories.

        FactoryProperty property = new FactoryProperty();
        properties.add(property);
        return property;
    
protected org.apache.axis.wsdl.toJava.NamespaceSelectorcreateSelector()

        return new NamespaceSelector();
    
public voidexecute()
The method executing the task

throws
BuildException if validation or execution failed

        //before we get any further, if the user didnt spec a namespace mapping
        //file, we load in the default

        traceParams(Project.MSG_VERBOSE);
        validate();
        CommandlineJava.SysProperties sysProperties =
                commandline.getSystemProperties();
        if (sysProperties != null) {
            sysProperties.setSystem();
        }
        
        try {
            // Instantiate the emitter
            Emitter emitter = createEmitter();

            //extract the scope
            Scope scope = Scope.getScope(deployScope, null);
            if (scope != null) {
                emitter.setScope(scope);
            } else if (deployScope.length() == 0
                    || "none".equalsIgnoreCase(deployScope)) {
                /* leave default (null, or not-explicit) */;
            } else {
                log("Unrecognized scope:  " + deployScope + ".  Ignoring it.", Project.MSG_VERBOSE);
            }

            //do the mappings, with namespaces mapped as the key
            mappings.execute(this, namespaceMap, false);
            if (!namespaceMap.isEmpty()) {
                emitter.setNamespaceMap(namespaceMap);
            }
            emitter.setTestCaseWanted(testCase);
            emitter.setHelperWanted(helperGen);
            if (factory != null) {
                emitter.setFactory(factory);
            }
            emitter.setNamespaceIncludes(nsIncludes);
            emitter.setNamespaceExcludes(nsExcludes);
            emitter.setProperties(properties);
            emitter.setImports(!noImports);
            emitter.setAllWanted(all);
            emitter.setOutputDir(output);
            emitter.setServerSide(server);
            emitter.setSkeletonWanted(skeletonDeploy);
            emitter.setVerbose(verbose);
            emitter.setDebug(debug);
            emitter.setQuiet(quiet);
            emitter.setTypeMappingVersion(typeMappingVersion);
            emitter.setNowrap(noWrapped);
            emitter.setAllowInvalidURL(allowInvalidURL);
            emitter.setWrapArrays(wrapArrays);
            if (namespaceMappingFile != null) {
                emitter.setNStoPkg(namespaceMappingFile.toString());
            }
			emitter.setTimeout(timeout);
			emitter.setImplementationClassName(implementationClassName);

            Authenticator.setDefault(new DefaultAuthenticator(username, password));
            if (classpath != null) {
                AntClassLoader cl = new AntClassLoader(
                        getClass().getClassLoader(),
                        getProject(),
                        classpath,
                        false);
                log("Using CLASSPATH " + cl.getClasspath(),
                        Project.MSG_VERBOSE);
                ClassUtils.setDefaultClassLoader(cl);
            }

            try {
                if(url.indexOf(':") == -1)
                    url = getProject().resolveFile(url).getAbsolutePath();
            } catch (Throwable t){
            }
            
            log("WSDL2Java " + url, Project.MSG_INFO);
            try {
                emitter.run(url);
            } catch (Throwable e) {
                if (url.startsWith("http://")) {
                    // What we have is either a network error or invalid XML -
                    // the latter most likely an HTML error page.  This makes
                    // it impossible to continue with the test, so we stop here
                    if (!failOnNetworkErrors) {
                        // test mode, issue a warning, and return without
                        //reporting a fatal error.
                        log(e.toString(), Project.MSG_WARN);
                        return;
                    } else {
                        //in 'consumer' mode, bail out with the URL
                        throw new BuildException("Could not build " + url, e);
                    }
                } else {
                    throw e;
                }
            }
        } catch (BuildException b) {
            //we rethrow this immediately; but need to catch it to stop it being
            //mistaken for a throwable.
            throw b;
        } catch (Throwable t) {
            if (printStackTraceOnFailure) {
                traceParams(Project.MSG_INFO);
                t.printStackTrace();
            }
            //now throw an exception that includes the error text of the caught exception.
            throw new BuildException("WSDL processing error for "
                    + url +" :\n "+t.getMessage() , t);
        } finally {
            if (sysProperties != null) {
                sysProperties.restoreSystem();
            }
        }

    
public voidsetAll(boolean parameter)
flag to generate code for all elements, even unreferenced ones default=false;

        this.all = parameter;
    
public voidsetAllowInvalidUrl(boolean b)
Set the allowInvalidURL flag.

        this.allowInvalidURL = b;
    
public voidsetDebug(boolean debug)
flag for debug output; default=false

param
debug The new debug value

        this.debug = debug;
    
public voidsetDeployScope(java.lang.String scope)
add scope to deploy.xml: "Application", "Request", "Session" optional;

        this.deployScope = scope;
    
public voidsetFactory(java.lang.String parameter)
name of the Java2WSDLFactory class for extending WSDL generation functions

        this.factory = parameter;
    
public voidsetFailOnNetworkErrors(boolean failOnNetworkErrors)
should the task fail the build if there is a network error? optional: defaults to false

param
failOnNetworkErrors

        this.failOnNetworkErrors = failOnNetworkErrors;
    
public voidsetHelperGen(boolean parameter)
Turn on/off Helper class generation; default is false

        this.helperGen = parameter;
    
public voidsetImplementationClassName(java.lang.String implementationClassName)
Set the name of the class implementing the web service. This is especially useful when exporting a java class as a web service using Java2WSDL followed by WSDL2Java.

param
implementationClassName

		this.implementationClassName = implementationClassName;
	
public voidsetNamespaceMappingFile(java.io.File namespaceMappingFile)
set the mapping file. This is a properties file of package=namespace order. Optional, default is to look for a file called NStoPkg.properties in the project directory.

param
namespaceMappingFile

        this.namespaceMappingFile = namespaceMappingFile;
    
public voidsetNoImports(boolean parameter)
only generate code for the immediate WSDL document, and not imports; default=false;

        this.noImports = parameter;
    
public voidsetNoWrapped(boolean noWrapped)
Set the noWrapped flag.

param
noWrapped

        this.noWrapped = noWrapped;
    
public voidsetOutput(java.io.File parameter)
output directory for emitted files

        try {
            this.output = parameter.getCanonicalPath();
        } catch (IOException ioe) {
            throw new BuildException(ioe);
        }
    
public voidsetPassword(java.lang.String password)
set any password required for BASIC authenticated access to the WSDL; optional; only used if username is set

param
password
see
#username

        this.password = password;
    
public voidsetPrintStackTraceOnFailure(boolean printStackTraceOnFailure)
should we print a stack trace on failure? Optional, default=true.

param
printStackTraceOnFailure

        this.printStackTraceOnFailure = printStackTraceOnFailure;
    
public voidsetProtocolHandlerPkgs(java.lang.String handlerPkgs)
append any protocol handler pkgs specified with the task

        String currentPkgs = System.getProperty("java.protocol.handler.pkgs");
        String newPkgs = null;

        if (currentPkgs == null)
            newPkgs = handlerPkgs;
        else
        // append to the existing list
            newPkgs = currentPkgs + "|" + handlerPkgs;

        System.setProperty("java.protocol.handler.pkgs", newPkgs);
    
public voidsetQuiet(boolean quiet)
flag for quiet output; default=false

param
quiet The new quiet value

        this.quiet = quiet;
    
public voidsetServerSide(boolean parameter)
emit server-side bindings for web service; default=false

        this.server = parameter;
    
public voidsetSkeletonDeploy(boolean parameter)
deploy skeleton (true) or implementation (false) in deploy.wsdd. Default is false. Assumes server-side="true".

        this.skeletonDeploy = parameter;
    
public voidsetTestCase(boolean parameter)
flag for automatic Junit testcase generation default is false

        this.testCase = parameter;
    
public voidsetTimeout(long parameter)
timeout in milliseconds for URL retrieval; default is 45 seconds. Set this to -1 to disable timeouts altogether: other negative values are not allowed)

        this.timeout = parameter;
    
public voidsetTypeMappingVersion(TypeMappingVersionEnum parameter)
the default type mapping registry to use. Either 1.1 or 1.2. Default is 1.1

param
parameter new version

        this.typeMappingVersion = parameter.getValue();
    
public voidsetURL(java.lang.String parameter)
URL to fetch and generate WSDL for. Can be remote or a local file.

        this.url = parameter;
    
public voidsetUsername(java.lang.String username)
set any username required for BASIC authenticated access to the WSDL; optional.

param
username

        this.username = username;
    
public voidsetVerbose(boolean verbose)
flag for verbose output; default=false

param
verbose The new verbose value

        this.verbose = verbose;
    
public voidsetWrapArrays(boolean wrapArrays)
Set the wrap arrays flag - if true this will make new classes like "ArrayOfString" for literal "wrapped" arrays. Otherwise it will use "String []" and generate appropriate metadata.

param
wrapArrays

        this.wrapArrays = wrapArrays;
    
private voidtraceNetworkSettings(int logLevel)

        traceSystemSetting("http.proxyHost", logLevel);
        traceSystemSetting("http.proxyPort", logLevel);
        traceSystemSetting("http.proxyUser", logLevel);
        traceSystemSetting("http.proxyPassword", logLevel);
        traceSystemSetting("socks.proxyHost", logLevel);
        traceSystemSetting("socks.proxyPort", logLevel);
    
public voidtraceParams(int logLevel)
trace out parameters

param
logLevel to log at
see
org.apache.tools.ant.Project#log

        log("Running Wsdl2javaAntTask with parameters:", logLevel);
        log("\tverbose:" + verbose, logLevel);
        log("\tdebug:" + debug, logLevel);
        log("\tquiet:" + quiet, logLevel);
        log("\tserver-side:" + server, logLevel);
        log("\tskeletonDeploy:" + skeletonDeploy, logLevel);
        log("\thelperGen:" + helperGen, logLevel);
        log("\tfactory:" + factory, logLevel);
        log("\tnsIncludes:" + nsIncludes, logLevel);
        log("\tnsExcludes:" + nsExcludes, logLevel);
        log("\tfactoryProps:" + properties, logLevel);
        log("\ttestCase:" + testCase, logLevel);
        log("\tnoImports:" + noImports, logLevel);
        log("\tNStoPkg:" + namespaceMap, logLevel);
        log("\toutput:" + output, logLevel);
        log("\tprotocolHandlerPkgs:" + protocolHandlerPkgs, logLevel);
        log("\tdeployScope:" + deployScope, logLevel);
        log("\tURL:" + url, logLevel);
        log("\tall:" + all, logLevel);
        log("\ttypeMappingVersion:" + typeMappingVersion, logLevel);
        log("\ttimeout:" + timeout, logLevel);
        log("\tfailOnNetworkErrors:" + failOnNetworkErrors, logLevel);
        log("\tprintStackTraceOnFailure:" + printStackTraceOnFailure, logLevel);
        log("\tnamespaceMappingFile:" + namespaceMappingFile, logLevel);
        log("\tusername:" + username, logLevel);
        log("\t:password" + password, logLevel);
        log("\t:noWrapped" + noWrapped, logLevel);
        log("\t:allowInvalidURL" + allowInvalidURL, logLevel);
		log("\t:implementationClassName" + implementationClassName, logLevel);
        log("\t:classpath" + classpath, logLevel);
        traceNetworkSettings(logLevel);
    
private voidtraceSystemSetting(java.lang.String setting, int logLevel)

        String value = System.getProperty(setting);
        log("\t" + setting + "=" + value, logLevel);
    
protected voidvalidate()
validation code

throws
BuildException if validation failed

        if (url == null || url.length() == 0) {
            throw new BuildException("No url specified");
        }
        if (timeout < -1) {
            throw new BuildException("negative timeout supplied");
        }
        File outdir = new File(output);
        if (!outdir.isDirectory() || !outdir.exists()) {
            throw new BuildException("output directory is not valid");
        }
        if (quiet) {
            if (verbose) {
                throw new BuildException("quiet and verbose options are " +
                                         "exclusive");
            }
            if (debug) {
                throw new BuildException("quiet and debug options are " +
                                         "exclusive");
            }
        }