0
# Programmatic Ant Access
1
2
The AntBuilder provides a Groovy builder-style interface for executing Apache Ant tasks programmatically, enabling fluent, type-safe access to the complete Ant task ecosystem from Groovy code.
3
4
## Capabilities
5
6
### AntBuilder Class
7
8
Provides builder-pattern access to Ant tasks with full project integration and stream management.
9
10
```java { .api }
11
/**
12
* Allows Ant tasks to be used with a Groovy builder-style markup.
13
* Provides programmatic access to all Ant tasks through a fluent interface.
14
*/
15
public class AntBuilder extends groovy.util.BuilderSupport {
16
/** Create AntBuilder with default project */
17
public AntBuilder();
18
19
/** Create AntBuilder with specified Ant project */
20
public AntBuilder(Project project);
21
22
/** Create AntBuilder with project and owning target */
23
public AntBuilder(Project project, Target owningTarget);
24
25
/** Create AntBuilder from parent task context */
26
public AntBuilder(Task parentTask);
27
28
/** Get the underlying Ant project */
29
public Project getProject();
30
31
/** Get the Ant XML context used for task creation */
32
public AntXMLContext getAntXmlContext();
33
34
/** Check if stdin/stdout/stderr streams are saved during task execution */
35
public boolean isSaveStreams();
36
37
/** Control whether streams are saved and redirected during task execution */
38
public void setSaveStreams(boolean saveStreams);
39
40
/** Get the Ant project (alias for getProject) */
41
public Project getAntProject();
42
43
/** Create new Ant project instance with default configuration */
44
protected static Project createProject();
45
46
/** Build XML attributes from a Map for task configuration */
47
protected static org.xml.sax.Attributes buildAttributes(Map attributes);
48
}
49
```
50
51
### Project Management
52
53
Access to Ant project functionality for build management and property handling.
54
55
```java { .api }
56
/**
57
* Ant Project provides the core context for build execution,
58
* property management, and task coordination.
59
*/
60
public class Project {
61
/** Set a project property */
62
public void setProperty(String name, String value);
63
64
/** Get a project property value */
65
public String getProperty(String name);
66
67
/** Set a new property (fails if already exists) */
68
public void setNewProperty(String name, String value);
69
70
/** Get all project properties */
71
public java.util.Hashtable getProperties();
72
73
/** Log a message at INFO level */
74
public void log(String message);
75
76
/** Log a message at specified level */
77
public void log(String message, int msgLevel);
78
79
/** Get project base directory */
80
public File getBaseDir();
81
82
/** Set project base directory */
83
public void setBaseDir(File baseDir);
84
85
/** Get project name */
86
public String getName();
87
88
/** Set project name */
89
public void setName(String name);
90
91
/** Execute a target by name */
92
public void executeTarget(String targetName);
93
94
/** Get all defined targets */
95
public java.util.Hashtable getTargets();
96
97
/** Get default target name */
98
public String getDefaultTarget();
99
100
/** Add a build listener */
101
public void addBuildListener(org.apache.tools.ant.BuildListener listener);
102
}
103
```
104
105
### Stream Management
106
107
Control of input/output streams during task execution.
108
109
```java { .api }
110
/**
111
* Stream management for capturing and redirecting task output.
112
*/
113
public interface StreamManagement {
114
/** Demultiplexed input stream for task input */
115
org.apache.tools.ant.DemuxInputStream getDemuxInputStream();
116
117
/** Demultiplexed output stream for task output */
118
org.apache.tools.ant.DemuxOutputStream getDemuxOutputStream();
119
120
/** Demultiplexed error stream for task errors */
121
org.apache.tools.ant.DemuxOutputStream getDemuxErrorStream();
122
}
123
```
124
125
## Usage Examples
126
127
### Basic Task Execution
128
```groovy
129
import groovy.util.AntBuilder
130
131
def ant = new AntBuilder()
132
133
// Execute simple tasks
134
ant.echo(message: "Hello from AntBuilder!")
135
ant.mkdir(dir: "build/output")
136
137
// Copy files
138
ant.copy(todir: "backup") {
139
fileset(dir: "src", includes: "**/*.groovy")
140
}
141
```
142
143
### File Operations
144
```groovy
145
def ant = new AntBuilder()
146
147
// Create directory structure
148
ant.mkdir(dir: "build/classes")
149
ant.mkdir(dir: "build/resources")
150
ant.mkdir(dir: "build/test-classes")
151
152
// Copy and filter resources
153
ant.copy(todir: "build/resources") {
154
fileset(dir: "src/main/resources") {
155
include(name: "**/*.properties")
156
include(name: "**/*.xml")
157
}
158
filterset {
159
filter(token: "VERSION", value: "1.0.0")
160
filter(token: "BUILD_DATE", value: new Date().toString())
161
}
162
}
163
164
// Delete temporary files
165
ant.delete {
166
fileset(dir: "build/temp", includes: "**/*")
167
}
168
```
169
170
### Archive Operations
171
```groovy
172
def ant = new AntBuilder()
173
174
// Create JAR file
175
ant.jar(destfile: "dist/myapp.jar") {
176
fileset(dir: "build/classes") {
177
exclude(name: "**/*Test.class")
178
}
179
manifest {
180
attribute(name: "Main-Class", value: "com.example.Main")
181
attribute(name: "Class-Path", value: "lib/groovy-all.jar")
182
}
183
}
184
185
// Create ZIP archive
186
ant.zip(destfile: "dist/source.zip") {
187
fileset(dir: "src", includes: "**/*.groovy,**/*.java")
188
fileset(dir: ".", includes: "build.xml,README.md")
189
}
190
191
// Extract archive
192
ant.unzip(src: "downloads/library.zip", dest: "lib/extracted")
193
```
194
195
### Compilation Tasks
196
```groovy
197
def ant = new AntBuilder()
198
199
// Compile Java sources
200
ant.javac(srcdir: "src/main/java",
201
destdir: "build/classes",
202
includeantruntime: false,
203
source: "1.8",
204
target: "1.8") {
205
classpath {
206
fileset(dir: "lib", includes: "*.jar")
207
}
208
}
209
210
// Compile Groovy sources
211
ant.groovyc(srcdir: "src/main/groovy",
212
destdir: "build/classes",
213
includeantruntime: false) {
214
classpath {
215
pathelement(location: "build/classes")
216
fileset(dir: "lib", includes: "*.jar")
217
}
218
}
219
```
220
221
### Testing Integration
222
```groovy
223
def ant = new AntBuilder()
224
225
// Run JUnit tests
226
ant.junit(printsummary: true, haltonfailure: false) {
227
classpath {
228
pathelement(location: "build/classes")
229
pathelement(location: "build/test-classes")
230
fileset(dir: "lib", includes: "*.jar")
231
}
232
233
formatter(type: "xml")
234
235
batchtest(todir: "build/test-reports") {
236
fileset(dir: "build/test-classes") {
237
include(name: "**/*Test.class")
238
}
239
}
240
}
241
242
// Generate test reports
243
ant.junitreport(todir: "build/test-reports") {
244
fileset(dir: "build/test-reports", includes: "TEST-*.xml")
245
report(todir: "build/test-reports/html")
246
}
247
```
248
249
### Property and Environment Access
250
```groovy
251
def ant = new AntBuilder()
252
253
// Set properties
254
ant.property(name: "app.version", value: "2.0.0")
255
ant.property(file: "build.properties")
256
257
// Load environment variables
258
ant.property(environment: "env")
259
260
// Access properties
261
def project = ant.getProject()
262
println "App version: ${project.getProperty('app.version')}"
263
println "Java home: ${project.getProperty('env.JAVA_HOME')}"
264
265
// Conditional execution based on properties
266
if (project.getProperty('debug.mode') == 'true') {
267
ant.echo(message: "Running in debug mode")
268
}
269
```
270
271
### Target Execution and Dependencies
272
```groovy
273
def ant = new AntBuilder()
274
def project = ant.getProject()
275
276
// Define and execute targets programmatically
277
ant.target(name: "clean") {
278
delete(dir: "build")
279
}
280
281
ant.target(name: "compile", depends: "clean") {
282
mkdir(dir: "build/classes")
283
javac(srcdir: "src", destdir: "build/classes")
284
}
285
286
// Execute targets
287
project.executeTarget("compile")
288
```
289
290
### Custom Task Integration
291
```groovy
292
def ant = new AntBuilder()
293
294
// Define custom task
295
ant.taskdef(name: "customtask",
296
classname: "com.example.CustomTask") {
297
classpath {
298
fileset(dir: "lib", includes: "custom-tasks.jar")
299
}
300
}
301
302
// Use custom task
303
ant.customtask(param1: "value1", param2: "value2") {
304
nestedElement(attribute: "value")
305
}
306
```
307
308
### Stream Capture and Processing
309
```groovy
310
def ant = new AntBuilder()
311
312
// Capture task output
313
def output = new ByteArrayOutputStream()
314
def error = new ByteArrayOutputStream()
315
316
ant.setSaveStreams(false) // Disable automatic stream saving
317
318
// Redirect streams for specific task
319
System.setOut(new PrintStream(output))
320
System.setErr(new PrintStream(error))
321
322
try {
323
ant.exec(executable: "git", dir: ".", failonerror: false) {
324
arg(value: "status")
325
arg(value: "--porcelain")
326
}
327
} finally {
328
System.setOut(System.out)
329
System.setErr(System.err)
330
}
331
332
def gitStatus = output.toString()
333
println "Git status: $gitStatus"
334
```
335
336
### Error Handling and Logging
337
```groovy
338
def ant = new AntBuilder()
339
def project = ant.getProject()
340
341
// Add custom build listener for logging
342
project.addBuildListener(new org.apache.tools.ant.DefaultLogger() {
343
void messageLogged(org.apache.tools.ant.BuildEvent event) {
344
if (event.priority <= org.apache.tools.ant.Project.MSG_WARN) {
345
println "ANT: ${event.message}"
346
}
347
}
348
})
349
350
try {
351
// Potentially failing task
352
ant.exec(executable: "nonexistent-command", failonerror: true)
353
354
} catch (org.apache.tools.ant.BuildException e) {
355
println "Build failed: ${e.message}"
356
357
// Continue with alternative approach
358
ant.echo(message: "Falling back to alternative method")
359
}
360
```
361
362
### Integration with Gradle/Maven Builds
363
```groovy
364
// In a Gradle task
365
task customBuild {
366
doLast {
367
def ant = new AntBuilder()
368
369
// Use Gradle's project properties
370
ant.property(name: "gradle.version", value: project.version)
371
ant.property(name: "gradle.buildDir", value: project.buildDir.path)
372
373
// Execute Ant-based build steps
374
ant.echo(message: "Building ${project.name} version ${project.version}")
375
376
// Complex file operations not easily done in Gradle
377
ant.copy(todir: "${project.buildDir}/processed") {
378
fileset(dir: "src/templates") {
379
include(name: "**/*.template")
380
}
381
mapper(type: "glob", from: "*.template", to: "*.properties")
382
filterset {
383
filter(token: "PROJECT_NAME", value: project.name)
384
filter(token: "VERSION", value: project.version)
385
}
386
}
387
}
388
}
389
```
390
391
## Advanced Features
392
393
### Project Configuration
394
```groovy
395
def ant = new AntBuilder()
396
def project = ant.getProject()
397
398
// Configure project settings
399
project.setName("MyBuildProject")
400
project.setBaseDir(new File("."))
401
project.setDefaultTarget("build")
402
403
// Add custom properties
404
project.setProperty("build.timestamp", new Date().toString())
405
project.setProperty("build.user", System.getProperty("user.name"))
406
```
407
408
### Task Customization
409
```groovy
410
def ant = new AntBuilder()
411
412
// Create custom task definitions
413
ant.presetdef(name: "myjavac") {
414
javac(includeantruntime: false,
415
source: "1.8",
416
target: "1.8",
417
debug: true) {
418
classpath(refid: "compile.classpath")
419
}
420
}
421
422
// Use preset task
423
ant.myjavac(srcdir: "src", destdir: "build/classes")
424
```