Saturday, February 14, 2009

Running Ant tasks from Java

let's face it, Ant is great but it's a pain in the butt when it comes to writing complex code, with variables, loops, conditions etc.
That's why I love the idea of running Ant tasks directly from Java.
Here is how.
The trick is to bear in mind the Ant object model: A Project contains Targets, a Target contains Tasks. A Task can't run without a Project, otherwise you get a NPE (my compliments to Ant developers for handling so gracefully this exception :o) ).

Of course you can build a "Ant Wrapper" framework on top of this paradygm...


package com.pierre.ant;

import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.Target;
import org.apache.tools.ant.taskdefs.Copy;

public class AntRunner {

public static void main(String[] args) {
AntRunner runner = new AntRunner();
runner.scp();
}
/**
Copy file from a to b, locally
*/
public void scp() {
Project project = new Project();
Target target = new Target();
project.addTarget("ciao", target);
Copy scp = new Copy();
scp.setFile(new File("c:/tmp/vacations.xsd"));
scp.setTodir(new File("c:/temp"));
scp.setProject(project);
target.addTask(scp);
target.execute();
}
}





2 comments:

koevet said...

You can achieve the same fluency using Gant or Grale, Groovy based, Ant compatible build tools.

Pierre said...

http://gradle.org/

http://gant.codehaus.org/

Thanks, but I am not going to touch Groovy even with a barge pole... you touch it, your break it.