Friday, June 25, 2010

Invoke ANT targets programmatically using java

You can invoke ant targets programmatically with java using below code. You need to be sure that the jar files inside ANT_HOME\lib are included in project.


import java.io.File;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.ProjectHelper;

public class Test {
public static void runAnt(){
File buildFile = new File("build.xml");
if(!buildFile.exists()){
System.out.println("ERROR :: File "+buildFile.getAbsolutePath()+" does not exist");
}
Project p = new Project();
p.setUserProperty("ant.file", buildFile.getAbsolutePath());
p.init();
ProjectHelper helper = ProjectHelper.getProjectHelper();
p.addReference("ant.projectHelper", helper);
helper.parse(p, buildFile);
p.executeTarget(p.getDefaultTarget());
}
public static void main(String... args){
runAnt();
}
}

3 comments:

  1. this is cool! Thank you so much!

    ReplyDelete
  2. thanks for sharing, but will this work as executable jar? and the build.xml is also inside that jar?
    thanks a lot!

    ReplyDelete
    Replies
    1. Yes it will work even as executable jar. If build.xml is inside the jar, then change the "File buildFile = new File("build.xml");" line accordingly to load using getClass().getResource() / getResourceAsStream() methods.

      Delete