Calling an Ant Target via Java

I like to use Apache’s Ant for writing small ‘jobs’ like moving/copying files or something else. There are a simple way to call those targets via Java:

/**
 * LGPL
*/
public static void runTarget(File buildFile, String targetName, Map properties) {
      ProjectHelper projectHelper = ProjectHelper.getProjectHelper();
      Project project = new Project();

      project.setUserProperty("ant.file", buildFile.getAbsolutePath());
      if (properties != null)
         for (String key : properties.keySet()) {
            project.setProperty(key, properties.get(key));
         }
      project.init();

      project.addReference("ant.projectHelper", projectHelper);
      projectHelper.parse(project, buildFile);
      try {
         project.executeTarget(targetName);
      } catch (BuildException e) {
         throw new RuntimeException(String.format("Run %s [%s] failed: %s", buildFile, targetName, e.getMessage()), e);
      }
   }

The ‘properties’ are regular properties that can be used inside an ant target.

,

  1. #1 by erik on 2012/08/22 - 04:14

    I was drawn to this because I want to call a Task class directly from within another task. The code described here appears to more about running a Target rather than a Task in a build file. Any clues on how to setup task.execute()?

    • #2 by Thilo on 2012/08/22 - 14:55

      In my post I’ve mixed the terms ‘target’ and ‘task’, – it’s fixed.

      A quick look to the Ant-API shows that there isn’t any methode to call a task directly. It works at the same way like the ‘build.xml’. A task can exist inside a target only.
      I guess you could build a target per API.

      • #3 by erik on 2012/08/22 - 21:57

        I did discover the Task class method bindToOwner() call that would appear to allow task chaining from java. The doc on this method has more details.

        Thanks for the help.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.