|
Keep the Ant, Hold the XML (Continued)
The XML names of many Ant tasks do not match the names of their corresponding Java classes. For instance, the task run with an XML call to execute an apply refers to the Transform class. The org/apache/tools/ant/taskdefs/defaults.properties file included in the free Ant source provides a reference to aid in mapping between the XML and Java class names, such as explaining that apply=org.apache.tools.ant.taskdefs.Transform.
In Java code that uses Ant programmatically, set the classpath to include the ant.jar archive. If you want to use the optional Ant tasks, include optional.jar also. Some Ant tasks, such as Javac, require the tools.jar archive located in the lib directory of the Java SDK home directory. Set the classpath in your Java program to include this JAR file.
Ant tasks and types must refer to a non-null instance of a project. As soon as you construct an instance of any of these classes, set its project to such a variable. Without doing so, your programs will crash and issue a stream of null-pointer exceptions.
Because the Ant documentation does not cover the techniques needed to invoke tasks programmatically, you may find it useful to first write your tasks in XML and then translate them into Java. As the XML often corresponds closely to the Java, this process can simplify the job of determining the specific Java instructions needed for your project. As you get familiar with the Ant classes, coding first in XML will become unnecessary.
When stumped, review the Ant source code. The programmers who have contributed their effort to the Apache project have already handled many of the problems you will encounter while using Ant programmatically.
Handling the Overhead
I have provided two objects to aid in writing Ant in Java: ProgramMain, to mimic much of the functionality available in the Ant Main class, and ProgramBuild, an interface to serve as a repository for the build logic. (Download them here.)
ProgramMain provides an entry point for executing Ant Tasks programmatically. This class will handle much of the overhead associated with running Ant in Java. When constructed, ProgramMain creates an instance of the Ant Project class to serve as the central representation of the Ant build. Most Ant classes used in your build will require this Project instance. ProgramMain also creates an instance of Ant's BuildLogger to carry out the function of recording output messages issued during the build.
You can manipulate the manner in which a build is managed by using methods in ProgramMain that follow the add, get, set, and is formats defined in the JavaBeans standard. With these methods, you can manipulate BuildListeners, the ProgramBuild, the OutputPrintStream, and the ErrorPrintStream; set whether logged output should be formatted in unadorned EmacsMode; and assign the MessageOutputLevel to specify how verbose logging should be.
Back to top
|