ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Diagnostic Tests with Ant
Pages: 1, 2, 3, 4, 5

Availability of Files and Classpaths

We can go further and automate some tests to see if a file or Java class is found:

<target name="files">
    <echo message="Testing availability of 
        needed files..."/>
    <available classname="org.apache.fop.apps.Fop" 
    <available file="build/scripts" type="dir" 

  <target name="fopNotFound" depends="files" 
    <echo level="error" message="ERROR: Fop 
        (class org.apache.fop.apps.Fop) not found 
        in classpath."/>

  <target name="scriptsDirNotFound" 
      depends="files" unless="scriptsdir.exists">
    <echo level="error" message="ERROR: 
        Directory build/scripts doesn't exist."/>

The first target performs two tests: first it tests if the class org.apache.fop.apps.Fop is found in the class path. Second, it tests if the directory build/scripts exists. By changing type to file, the available task will test for the existence of a file with the specified name. The next two targets show error messages in case the class isn't available or the directory doesn't exist, respectively.

Minimum Required Java Version

We can do even more, but to do so we have to write custom Ant tasks. Let's check if the installed Java version is greater than a minimum required version for our Java code. Our diagnostics build file should show an error if the version isn't OK. The source code of our JavaVersionTask class is as follows:

import org.apache.tools.ant.*;

 JavaVersionTask is an Ant task for testing if
 the installed Java version is greater than a 
 minimum required version.
public class JavaVersionTask extends Task {

  // Minimum required Java version.
  private String minVersion;
  // Installed Java version.
  private String installedVersion;
  // The name of the property that gets set when
  // the installed Java version is ok.
  private String propertyName;

   * Constructor of the JavaVersionTask class.
  public JavaVersionTask() {
    installedVersion = System.getProperty

   * Set the attribute minVersion.
  public void setMinVersion(String version) {
    minVersion = version;

   Set the property name that the task sets when
   the installed Java version is ok.
  public void setProperty(String propName) {
    propertyName = propName;

   * Execute the task.
  public void execute() throws BuildException {
    if (propertyName==null) {
      throw new BuildException("No property name 
    } else if (minVersion==null) {
      throw new BuildException("No minimum version 

       >= 0) {

Pages: 1, 2, 3, 4, 5

Next Pagearrow