Checking for the Existence of Properties

Problem

You want to check for the existence of several properties and/or environment variables before you perform a build.

Solution

Define a “checkProperties” target that uses the fail task to abort the build if any properties are undefined.

Discussion

Suppose that various parts of your buildfile require several environment variables. First, specify a target that checks those properties:

<target name="checkProperties">
  <fail unless="env.TOMCAT_HOME">TOMCAT_HOME must be set</fail>
  <fail unless="env.JUNIT_HOME">JUNIT_HOME must be set</fail>
  <fail unless="env.JBOSS_HOME">JBOSS_HOME must be set</fail>
</target>

This causes the build to fail if any one of these environment variables is not set. To execute this target, list it as a dependency from some other target:

<target name="compile" depends="checkProperties">
  ...
</target>

The dependency ensures that the checkProperties target executes before Ant attempts to compile your code.

See Also

The previous two recipes showed how to define environment variables and Ant properties.

Get Java Extreme Programming Cookbook 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.