Chapter 7. Executing External Programs

Part of the build process involves testing what you've built, and an obvious way of doing that is to run the results of a build. Doing so from Ant involves using the tasks detailed in this chapter: java, exec, and apply. You can check the return code from your build to ensure things worked out; if not, you can halt the build before you deploy faulty build results.

Executing code to test it is a fundamental part of the build process, and this chapter covers that aspect of Ant. Besides running your code, you can start and stop external programs needed to test your code, such as when you want to run a JUnit test on a Web application and need to start a web server. The tasks in this chapter do more than the usual internal Ant tasks, and because they're designed to deal with the external run-time environment, so they're a little more involved than usual.

Executing Java Code

The java task is part of Ant's core functionality; it executes a Java class in the current JVM, or forks another JVM and runs the class in the new JVM. You can recover the exit code of the Java class and stop the build if the build results you're testing create an error.

Here's an example using this task. Say you have this code, Project.java, which reads what the user enters on the command line and displays it:

public class Project 
{
    public static void main(String args[]) 
    {
        System.out.println("You said: " + args[0]);    
        System.exit(0);
    }
}

After compiling this code you can run ...

Get Ant: The Definitive Guide, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.