Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Groovy-power automated builds with Gant

Enhance your build process with Groovy plus Ant

Page 4 of 5

From Ant to Gant

In this section I present two examples that demonstrate the migration from Ant to Gant. Listing 6 shows many typical Ant tasks expressed using simple Groovy "scriptlets." These tasks include Ant.path, Ant.javac, Ant.javadoc, Ant.copy, Ant.zip, Ant.jar, and Ant.delete. The sample also includes fileset definitions and a "depends" call, all highlighted in bold.

Listing 6. Typical Ant tasks expressed in Gant

... other definitions here
long startTime = System.currentTimeMillis()

Ant.property(file: 'build.properties')
def antProperty = Ant.project.properties // introduce a shortcut for further access

private static final GROOVY_ADD_ONS = "${antProperty.'groovy.home'}/../groovy-add-ons"

target (javagen: "$JAVAGEN_TARGET_DESCRIPTION") {
    depends(init)
    if (wsdlRegexProvided && !wsdlRegexOK) {
        return
    }

    println javagen_description
    println "using data binding: ${antProperty.'axis.data.binding'}"
    new File("${antProperty.'output.axis.file'}").delete()
    new File("${antProperty.'error.axis.file'}").delete()

    def modifyAxis2Client = {
        def javaSrcDirPath = new File(it)
        javaSrcDirPath.eachFileRecurse{
            if (it.isFile() && (it.name.endsWith('Stub.java'))) {
                println()
                print "${NL}Modifying $it.name ..."
                tools.webservices.wsdl.stubutil.ModifyingJavaParser.main(it.absolutePath)
                println ' Done.'
            }
        }
    }

    def compileAxis2Client = { jarfileName, srcDir ->
        def classfileDir = srcDir-"/src" + '/classes'
        new File(classfileDir).mkdir()
        def java_compile_classpath = Ant.path {
            pathelement(location: classfileDir)
            fileset(dir: GROOVY_ADD_ONS) {
                include(name: 'commons-*.jar')
                include(name: 'japa.jar')
            }
            fileset(dir: antProperty.'axis2.lib.dir') {
                include(name: '*.jar')
            }
        }
        Ant.javac(
            destdir: classfileDir,
            srcdir: srcDir,
            classpath: java_compile_classpath,
            debug: true,
            source: '1.5',
            target: '1.5',
            failonerror: 'no'
        )
        def destDir = srcDir-"/src"
        Ant.zip(zipfile: "${destDir}/${jarfileName}-src.zip", basedir: srcDir)
        Ant.jar(destfile: "${destDir}/${jarfileName}.jar", basedir: classfileDir)
        if (antProperty.'axis.data.binding'.equals('xmlbeans')) {
            def resourceDir = srcDir-"/src" + '/resources'
            Ant.jar(destfile: "${destDir}/${jarfileName}-res.jar", basedir: resourceDir)
        }
    }

    def generateJavaDocumentation = { serviceName, srcDir ->
        def classfileDir = srcDir-"/src" + '/classes'
        Ant.copy(todir: srcDir) {
            fileset(dir: "${antProperty.'java-parser.install.dir'}/src") {
                include(name: 'tools/webservices/wsdl/stubutil/*.java')
                exclude(name: 'tools/webservices/wsdl/stubutil/Modifying*.java')
            }
        }
        Ant.copy(todir: classfileDir) {
            fileset(dir: "${antProperty.'java-parser.install.dir'}/classes") {
                include(name: 'tools/webservices/wsdl/stubutil/*.class')
            }
        }

        def javadocsDir = srcDir-"/src" + '/javadocs'
        new File(javadocsDir).mkdir()
        def javadoc_classpath = Ant.path {
            pathelement(location: classfileDir)
            fileset(dir: antProperty.'axis2.lib.dir') {
                include(name: '*.jar')
            }
            fileset(dir: GROOVY_ADD_ONS) {
                include(name: 'commons-*.jar')
                include(name: 'japa.jar')
            }
        }
        Ant.javadoc(
            destdir: javadocsDir,
            author: true,
            version: true,
            source: '1.5',
            packagenames: antProperty.'javadoc.packageNames',
            windowtitle: "Axis2 client - Version ${antProperty.'axis2.version'}",
            doctitle: "Axis2 client (Version ${antProperty.'axis2.version'}) for service $serviceName",
            nodeprecated: true,
            bottom: antProperty.'project.copyright',
            sourcepath: srcDir,
            classpath: javadoc_classpath)

        def destDir = srcDir-"/src"
        Ant.zip(zipfile: "${destDir}/${serviceName}-doc.zip", basedir: javadocsDir)
        Ant.delete(dir: "$destDir/src/tools") // delete the japa src part
        Ant.delete(dir: "$destDir/classes/tools") // delete the japa bytecode part
    }

    def processOneFile = { filename, wsdlFile, javaSrcDir, wsdlPackage ->
        println()
        println 'processing file: ' + filename
        generateJavaCode(wsdlFile, javaSrcDir)
        if (Ant.project.properties."taskResult_$wsdlFile" == '0') {
            modifyAxis2Client(javaSrcDir + '/' + wsdlPackage.replace('.', '/'))
            compileAxis2Client(filename-'.wsdl', javaSrcDir)
            if (antProperty.'javadoc.enabled' == 'yes') {
                generateJavaDocumentation(filename-'.wsdl', javaSrcDir)
            }
        }
        else {
            println "     ERROR: cannot generate Java code for file $filename"
        }
    }

    ...

    long endTime = System.currentTimeMillis()
    def duration = Math.round((endTime - startTime) / 1000.0f) // in seconds
    println()
    println("GANT PROCESSING SUCCESSFULL: $duration seconds")
}

Listing 7 shows a more complicated Gant task, junit, and its transformation from XML into HTML with junitreport.

Listing 7. junit as a Gant task

... other definitions here
def excludefile = new File("$eclipseProjectDir/.excludes")
Ant.junit(
    printsummary: 'withOutAndErr',
    fork: 'yes',
    dir: eclipseProjectDir ,
    errorproperty: "junitResult_$eclipseProjectDir",
    failureproperty: "junitResult_$eclipseProjectDir") {
        classpath {
            pathelement(location: classfileTempDir)
            pathelement(location: base_soap_classfileDir)
            pathelement(location: ftsConfigDir)
            pathelement(location: dist_client_dir)
            fileset(dir: GROOVY_ADD_ONS) {
                include(name: 'commons-*.jar')
                include(name: 'japa.jar')
            }
            fileset(dir: antProperty.'axis2.lib.dir') {
                include(name: '*.jar')
            }
            // more fileset definitions here
        }
        formatter (type: 'xml')
        batchtest (todir: reportDir) {
            fileset(dir: srcDir) {
                include(name: '**/*Test.java')
                if (excludefile.exists()) {
                    out("excluding tests: ${excludefile.getText()}")
                    excludesfile(name: excludefile)
                }
            }
        }
}
if (Ant.project.properties."junitResult_$eclipseProjectDir" == null) {
    out('TEST OK')
}
else {
    out('TEST ENDED WITH ERRORS/FAILURES')
}

System.setProperty("javax.xml.transform.TransformerFactory", "org.apache.xalan.processor.TransformerFactoryImpl");
Ant.junitreport(todir: "${antProperty.'fts.reports'}") {
    fileset(dir: "${antProperty.'fts.reports'}") {
        include(name: 'TEST-*.xml')
    }
    report(format: 'frames', todir: "${antProperty.'fts.reports'}")
}

Resources

Downloads

  • The source packet for this article: Includes a complete build.gant and build.properties file.
  • Groovy: A dynamic language for the Java platform.
  • Gant: Groovy plus Ant.
  • Apache Ant: A build utility for the Java platform.
  • Ant-Contrib: a collection of tasks for Apache Ant.
  • AntBuilder: Allows Ant tasks to be used with Groovy markup.
  • Eclipse Groovy Plugin: The Groovy Eclipse Plugin allows you to edit, compile and run groovy scripts and classes. Requires at least Eclipse 3.2.
  • Grails: An open source Web application framework for Groovy-based Java development.