How to use the AntBuilder in a custom task implented in Java?

I am migrating the following task from the build.gradle file to a custom task implemented in Java.

task filterCssWithStringToken() << {
  ant.copy(todir: outputDirectory) {
   fileset(dir: inputDirectory, includes: "**/*.css")
  filterset(begintoken: "%{", endtoken: "}") {
    filter(token: "TOKEN_NAME", value: "TOKEN_VALUE")

I am using “ant.copy” to be able to set a String as “begintoken” value instead of a Char.

How can I use the AntBuilder to implement this behaviour?

My first attempt (see below) fails with “copy doesn’t support the ‘fileset’ attribute”. So how do I add the nested ‘fileset’ element?

AntBuilder ant = getProject().getAnt();
  Map<String, String> fileset = new HashMap<String, String>();
fileset.put("dir", from.getPath());
fileset.put("includes", "**/*.css");
    Map<String, Object> main = new HashMap<String,Object>();
main.put( "todir", into.getPath());
main.put( "fileset", fileset);
    ant.invokeMethod( "copy", main);

‘AntBuilder’ is based on Groovy’s dynamic builder support, and using it from Java will be difficult (probably infeasible). But instead of ‘ant.copy’, you can simply use Gradle’s ‘project.copy’.

My problem with the ‘project.copy’ task is, that is does not support a String as a token delimiter. Therefore I use the Ant task. Following the hint from I have the following solution:

 public void copyFiltered() {
    FileSet fileset = new FileSet();
    for (String include : includes) {
    AntCopy copy = new AntCopy();
    FilterSet filterSetPercentage = copy.createFilterSet();
  for (String key : tokens.keySet()) {
   filterSetPercentage.addFilter(key, tokens.get(key));

Directly using Ant’s ‘Copy’ task is an option, but I’d prefer to use ‘project.copy’ together with ‘’ (as demonstrated in the user guide).