Using Ant from Groovy

Groovy 

      Download | Documentation | Developers | Community

An agile dynamic language for the Java Platform

If ever you've been working with a build.xml file or some Jelly script and found yourself a little restricted by all those pointy brackets, or found it a bit wierd using XML as a scripting language and wanted something a little cleaner and more straight forward, then maybe Ant scripting with Groovy might be what you're after.

Groovy has a helper class called AntBuilder which makes the scripting of Ant tasks really easy; allowing a real scripting language to be used for programming constructs (variables, methods, loops, logical branching, classes etc). It still looks like a neat concise version of Ant's XML without all those pointy brackets; though you can mix and match this markup inside your script. Ant itself is a collection of jar files. By adding them to your classpath, you can easily use them within Groovy as is. We believe using AntBuilder leads to more concise and readily understood syntax.

Below are some examples (most taken from Groovy's own AntBuilder tests) which demonstrate:

  • the use of Ant inside Groovy using the AntBuilder DSL notation
  • a demo of iterating through an Ant FileSet using fileScanner
  • that normal variables can be used to pass state into the Ant tasks and that Groovy code can be embedded anywhere in the markup.
def ant = new AntBuilder()

// lets just call one task
ant.echo("hello")

// here is an example of a block of Ant inside GroovyMarkup
ant.sequential {
    echo("inside sequential")
    myDir = "target/AntTest/"
    mkdir(dir:myDir)
    copy(todir:myDir) {
        fileset(dir:"src/test") {
            include(name:"**/*.groovy")
        }
    }
    echo("done")
}

// now lets do some normal Groovy again
file = new File("target/AntTest/groovy/util/AntTest.groovy")
assert file.exists()
def ant = new AntBuilder()

// lets create a scanner of filesets
scanner = ant.fileScanner {
    fileset(dir:"src/test") {
        include(name:"**/Ant*.groovy")
    }
}

// now lets iterate over
def found = false
for (f in scanner) {
    println("Found file $f")
    found = true
    assert f instanceof File
    assert f.name.endsWith(".groovy")
}
assert found
def ant = new AntBuilder()

ant.junit {
    test(name:'groovy.util.SomethingThatDoesNotExist')
}
def ant = new AntBuilder()

value = ant.path {
    fileset(dir:"xdocs") {
        include(name:"*.wiki")
    }
}

assert value != null

println "Found path of type ${value.class.name}"
println value
def ant = new AntBuilder()
def taskContainer = ant.parallel(){ // "Parallel" serves as a sample TaskContainer
    ant.echo()                      // "Echo" without message to keep tests silent
}
// not very elegant, but the easiest way to get the ant internals...
assert taskContainer.dump() =~ /nestedTasks=\[org.apache.tools.ant.taskdefs.Echo@\w+\]/

Compiling and running a Java file:

def ant = new AntBuilder()
ant.echo(file:'Temp.java', '''
class Temp { public static void main(String[] args) { System.out.println("Hello"); }}
''')
ant.javac(srcdir:'.', includes:'Temp.java', fork:'true')
ant.java(classpath:'.', classname:'Temp', fork:'true')
ant.echo('Done')
// =>
//    [javac] Compiling 1 source file
//     [java] Hello
//     [echo] Done

Sniffing around ...

def ant = new AntBuilder()
SpoofTaskContainer.spoof.length = 0
def PATH = 'task.path'
ant.path(id:PATH){ant.pathelement(location:'classes')}
['spoofcontainer':'SpoofTaskContainer', 'spoof':'SpoofTask'].each{ pair ->
    ant.taskdef(name:pair.key, classname:'groovy.util.'+pair.value, classpathref:PATH)
}
ant.spoofcontainer(){
    ant.spoof()
}
expectedSpoof =
    "SpoofTaskContainer ctor\n"+
    "SpoofTask ctor\n"+
    "in addTask\n"+
    "begin SpoofTaskContainer execute\n"+
    "begin SpoofTask execute\n"+
    "end SpoofTask execute\n"+
    "end SpoofTaskContainer execute\n"
assertEquals expectedSpoof, SpoofTaskContainer.spoof.toString()

Using the joint compiler

Here is a small build file which uses the joint compiler to compile Groovy and Java source files together, and put them in WEB-INF/classes:

def ant = new AntBuilder().sequential {
	webinf = "deploy/WEB-INF"
	taskdef name: "groovyc", classname: "org.codehaus.groovy.ant.Groovyc"
	groovyc srcdir: "src", destdir: "${webinf}/classes", {
		classpath {
			fileset dir: "${webinf}/lib", {
		    	include name: "*.jar"
			}
			pathelement path: "${webinf}/classes"
		}
		javac source: "1.5", target: "1.5", debug: "on"
	}
}


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值