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


(Christian Abegg) #1

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);

(Peter Niederwieser) #2

‘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’.


(Christian Abegg) #3

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 http://stackoverflow.com/questions/13831846/how-to-use-apache-ants-task-in-my-java-code I have the following solution:

@TaskAction
 public void copyFiltered() {
    FileSet fileset = new FileSet();
  fileset.setDir(from);
    for (String include : includes) {
   fileset.setIncludes(include);
  }
    AntCopy copy = new AntCopy();
  copy.setTodir(into);
  copy.addFileset(fileset);
    FilterSet filterSetPercentage = copy.createFilterSet();
  filterSetPercentage.setBeginToken("%{");
  filterSetPercentage.setEndToken("}");
  for (String key : tokens.keySet()) {
   filterSetPercentage.addFilter(key, tokens.get(key));
  }
    copy.execute();
 }

(Peter Niederwieser) #4

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