0

I have written my own ANT task to perform some function. However, I need this task to invoke a java task as a nest task. So I have the following code in my build file:

<mytask ... >
  <java ... />
</mytask>

I would like to run a piece of code after the java task finishes executing but before mytask completes, for the purpose of cleanup.

Is this a broken design, not recommended in build files? If not, which method should I over-ride in order to run the cleanup method?

Neel
  • 2,100
  • 5
  • 24
  • 47
  • And one thing: change the title of this Q&A to `Run nested task in custom task` or similar... may draw more attention. – Dante WWWW May 10 '12 at 07:56

1 Answers1

1

Let your task implement the org.apache.tools.ant.TaskContainer interface, write your own addTask(Task task) method.

For example (it should only take a task named "java"):

private List<Task> _nestedTask = new ArrayList<>();

public void addTask(Task task) {
    if (task.getTaskName().equals("java")) {
        _nestedTasks.add(task);
    }
    else {
        throw new BuildException("Support only nested <java> task.");
    }
}

Please note that if you write multiple nested <java> tasks in your build file, you need to handle them by your self. To execute the nested <java> tasks, just iterate through the list and call execute() method for each task.

Update:

When a nested task is added, it doesn't run automatically. It won't even run if its execute() method is not called in your custom task.

So... A very basic and simple example:

// your custom task's execute...
public void execute() {
    //do something

    for (Task task : _nestedTask) {
        task.perform(); // here the nested task is executed.
    }

    //do something
}
Dante WWWW
  • 2,729
  • 1
  • 17
  • 33
  • yes, I have this code to add the nested task, but here is the problem: the `addTask` method gets called only before the nested task is executed, so where should I call the `cleanup` method so that it gets called after the java task? – Neel May 15 '12 at 12:50
  • @Neel `addTask` and calling `task.execute` is two seperate steps. `addTask` is called by Ant, but it doesn't mean that the nested task is executed when it is added. The nested task won't run until you call its `execute` method. See my updated answer. – Dante WWWW May 15 '12 at 14:48
  • 1
    If I understand the [tutorial](http://ant.apache.org/manual/develop.html#taskcontainer) correctly, you should call `task.perform()` in the loop. – Christian Gawron Aug 30 '16 at 21:25