Home > Articles

Global Concepts

This chapter is from the book

This chapter is from the book

Creating Standard Ant Targets and What They Should Do

In every project that you do, and in just about every build file that you encounter, certain targets keep popping up. It helps to give these targets standard names so that everyone understands what the task does. Let's think about what you need to do in most projects. You need to set properties, create directories, compile, test, report on the tests, jar, perhaps war (if it's a Web app), generate JavaDocs, and deploy. You can name the corresponding targets accordingly. Here is a short list of common target names and what they do:

  • init sets properties for the entire build

  • prepare creates a build directory, test results directory, and so on

  • fetch fetches your source code updates from a source code repository

  • compile compiles, obviously

  • test executes JUnit tests and generates reports

  • jar creates a JAR file

  • war creates a WAR file

  • docs generates JavaDocs documentation

  • deploy copies or FTPs the JAR/WAR/EAR to a deployment machine

Steve Loughran, in "Ant In Anger," also suggests the following targets:

  • build performs an incremental build

  • publish to "output the source and binaries to any distribution site"

  • all performs an entire build from start to finish

  • main performs a default build; generally just a build and test

  • init-debug is called from init to set up properties for a debug build

  • init-release is called from init to set up properties for a release build

  • staging moves the complete project to a pre-production area

Let's discuss each of these targets and what they do.

Setting Properties with the init Target

The init target's duty is to set properties and not much else. So, it will basically be a bunch of <property> tags that set up all the properties you'll use in any target in your build file. Or, it could contain one statement that looks like Listing 3.6.

Listing 3.6 Loading Properties from a File

<target name="init">
  <loadproperties srcFile="build.properties"/>
</target>

As you can see, the <loadproperties> tag takes a .properties file and loads it up as Ant properties. This is equivalent to you setting them all in individual <property> statements. Chapter 4, "Built-in Tasks," has more information about this.

Another important thing to do in init is to set up a path-like structure that will be used as your class path. I cover this topic later in this chapter, but Listing 3.7 gives an example.

Listing 3.7 Building a Path-Like Structure

<target name="init">
  <loadproperties srcFile="build.properties"/>
  <path id="classpath">
    <pathelement path="${oro.jar}"/>
    <fileset dir="${struts.dir}">
      <include name="*.jar"/>
    </fileset>
  </path>
  <property name="classpath" refid="classpath"/>
</target>

If you heed Mr. Loughran's suggestion to have init targets set up things differently depending on whether you are doing a debug or release build, you would define init-debug and init-release targets. Each of these will either directly set properties that they need, or will load a different properties file. To determine which one will be called, you can make use of command-line properties and the unless and if attributes of Ant targets. Listing 3.8 shows an example of this.

Listing 3.8 Using Discrete init Targets for Debug and Release Builds

<target name="init">
  <property name="name" value="chapter3"/>
  <tstamp/>
</target>

<target name="init-debug" unless="release.build">
  <loadproperties srcFile="debug.properties"/>
</target>

<target name="init-release" if="release.build">
  <loadproperties srcFile="release.properties"/>
</target>

<target name="prepare" depends="init, init-debug, init-release">
  <!-- other tasks -->
</target>

Notice the presence of an unless attribute in init-debug and an if attribute in init-release. These attributes conditionally execute a target if a certain property has been defined or unless a certain property has been defined. Here, if you execute Ant with -Drelease.build=true on the command line, init-release will be executed; otherwise, init-debug will be run. By putting both targets in the prepare target's depends attribute, the proper target will be called based on the presence or absence of the release.build property.

The listing also has an init target that could set up properties that will be useful regardless of the type of build being conducted.

CAUTION

In "Ant In Anger," Mr. Loughran suggests that to do this, you should define the two init-xxx targets, and then use the <antcall> task to execute them. This obviously worked in a previous version of Ant, but in the current releases, any properties set in a target that is executed via <antcall> will be visible only inside the target that is being called with <antcall>. This is definitely not what you want.

Preparing the Environment with the prepare Target

The prepare target doesn't generally do much, but it's important nonetheless. You'll typically want to create your ${build.dir} and any subdirectories under it in the prepare target. If you'll be using the <record> task, this would be a good place to start it recording. <record> is covered in Chapter 5. Listing 3.9 shows a typical prepare target, turning on a recorder at the same time.

Listing 3.9 A Typical prepare Target

<target name="prepare" depends="init">
  <mkdir dir="${build.dir}"/>
  <record name="${name}.log" action="start"/>
</target>

Fetching Source Code from a Repository with the fetch Target

If you're on a project with more than a person or two, you'll most certainly store your source code in a repository of some sort, such as CVS or SourceSafe. You'll need a target to get the latest code updates from the repository so that you can ensure your code integrates with that of the rest of the team. The fetch target accomplishes this. You probably don't want to call this target every time you do a build because of the time it takes to get updates, but you do want it to be available when you need it. Listing 3.10 shows an example of getting source updates from CVS.

Listing 3.10 Fetching Code Updates with the fetch Target

<target name="fetch" depends="prepare">
  <cvspass cvsroot="${cvsroot}" password="${repo.pass}"/>
  <cvs cvsRoot="${cvsroot}" command="update -P -d" failonerror="true"/>
</target>

Compiling Your Classes with the compile Target

After you've set up the build directory it's time to compile your Java classes. The <javac> task makes building Java applications so much easier than doing it by hand. You generally don't need anything in this target other than <javac> itself. Listing 3.11 shows this.

Listing 3.11 A Typical compile Target

<target name="compile" depends="prepare">
  <javac srcdir="${src.dir}"
    destdir="${build.dir.classes}"
    classpath="${classpath}"/>
</target>

Testing and Reporting with the test Target

Unit testing and reporting on those tests are important steps that are too often left out of a development cycle. Ant automates everything but writing the tests themselves, so you really should try to utilize it. Putting both the <junit> and <junitreport> tasks in the same target is a good idea so that you don't forget to generate the reports from the raw output of <junit>. Listing 3.12 shows these two tasks in a test target.

Listing 3.12 A Typical test Target

<target name="test" depends="compile">
  <junit failureproperty="testsFailed">
    <classpath>
      <pathelement path="${classpath}"/>
      <pathelement path="${build.dir.classes}"/>
    </classpath>
    <formatter type="xml"/>
    <test name="chapter3.test.TestAll"
      todir="${reports.dir}"/>

  </junit>
  <junitreport todir="${reports.dir}">
    <fileset dir="${reports.dir}">
      <include name="**/TEST-*.xml"/>
    </fileset>
    <report format="frames" todir="${reports.dir.html}"/>
  </junitreport>
</target>

Creating a JAR File with the jar Target

Depending on what you're building, you might need to create a JAR file that contains your compiled classes. a JAR file can be easily created using the built-in <jar> task. Listing 3.13 shows a typical jar target.

Listing 3.13 A Typical jar Target

<target name="jar" depends="test" unless="testsFailed">
  <jar destfile="${build.dir}/${name}.jar"
    basedir="${build.dir}" includes="**/*.class"/>
</target>

The <jar> task here builds a JAR file with all .class files it finds under ${build.dir}. Also note that the target will not execute if the testsFailed property is present. This property is set by <junit> if any tests failed. This is a great way to conditionally execute targets.

Building a Web Archive with the war Target

If you're building a Web application, you'll most likely need to create a Web archive, or WAR file, out of it. A WAR file is just a JAR file with some special directories and file placement requirements. The <war> task is an extension of the <jar> task that makes creating WARs a simple matter. Listing 3.14 shows a sample war target.

Listing 3.14 Building a Web Archive with the war Target

<target name="war" depends="jar" unless="testsFailed">
  <war destfile="${name}.war" webxml="${etc.dir}/web.xml">
    <fileset dir="${src.dir}/jsp" includes="**/*.jsp"/>
    <classes dir="${build.dir}/web" includes="**/*.class"/>
    <lib dir="${struts.dir}" includes="*.jar"/>
    <webinf dir="${etc.dir}" includes="*.xml"
      excludes="web.xml"/>
  </war>
</target>

Generating Documentation with the docs Target

Because Java provides javaDoc, it is incumbent upon you as a developer to add JavaDoc comments to your code. The javaDoc tool takes these comments and creates excellent API documentation. Unfortunately, the options necessary to really tweak the generated documentation are lengthy and cumbersome. The built-in <javadoc> task makes it a piece of cake to generate JavaDocs exactly as you want them. Just look at Listing 3.15 for an example.

Listing 3.15 Generating JavaDocs

<target name="docs" depends="test" unless="testsFailed">
  <javadoc packagenames="com.mycompany.*" sourcepath="${src.dir}"
    classpath="${classpath}" destdir="${doc.api.dir}"
    author="true" version="true" use="true"
    windowtitle="MyProject Documentation">
    <bottom><![CDATA[<em>Copyright &copy; 2002</em></div>]]></bottom>
    <link href="http://java.sun.com/products/jdk/1.3/docs/api"/>
  </javadoc>
</target>

Notice that the docs target has an unless attribute. If there is a defined property called testsFailed, the documentation will not be generated because you generally don't want API documentation for broken code.

Deploying What You've Built with the deploy Target

After you've built a JAR or WAR file and generated your test reports and your JavaDocs, it's time to drop the JAR or WAR file somewhere for deployment. In the section in Chapter 8 called "Deploying What We've Built," you'll see an example of deploying to another box using FTP. Listing 3.16 is an example of a deploy target that uses the <copy> task to put the JAR file in a QA directory.

Listing 3.16 Deploying the Project

<target name="deploy" depends="jar" unless="testsFailed">
  <copy file="${name}.jar" todir="${qa.dir}"/>

</target>

Again, notice that this target depends on a previous target, and won't execute if any unit tests failed.

Turning again to "Ant In Anger," here are some examples for the targets that Mr. Loughran suggests. Notice that each of these targets makes extensive use of the antcall task to delegate work to other targets.

Performing an Incremental Build with the build Target

The build target could call the compile, jar, and/or war targets. Basically, it calls whatever it takes to do a build based on what you currently have on your system. However, it would not fetch source updates from your source control system. Listing 3.17 is an example.

Listing 3.17 Building the Project

<target name="build" depends="prepare">
  <antcall target="compile"/>
  <antcall target="jar"/>
</target>

Building and Testing with the main Target

A target called main would perform a build and test, generally, and not much else. It would not fetch source code from a repository, nor would it deploy anything. Listing 3.18 shows this.

Listing 3.18 Building and Testing with the main Target

<target name="main" depends="prepare">
  <antcall target="build"/>
  <antcall target="test"/>
</target>

Doing Everything with the all Target

A target named all does just what its name implies: calls all the relevant targets to get the project built. This would be a start-to-finish build, including removing all artifacts from previous builds, fetching source, building, testing, generating documentation, and deploying. You could leverage your existing main target by calling it instead of listing the compile and test steps directly. Listing 3.19 shows one possible implementation of this target.

Listing 3.19 Doing It All with the all Target

<target name="all" depends="prepare">
  <antcall target="clean"/>
  <antcall target="fetch"/>
  <antcall target="main"/>
  <antcall target="deploy"/>
</target>

If you use an all target, you should have an unless attribute on each target called by antcall to stop a build if a previous target doesn't complete successfully.

Publishing and Staging with the publish and staging Targets

Mr. Loughran recommends two additional targets: publish and staging. His concept of the staging target is essentially the same as the deploy target we've already discussed, in which our built and tested project is moved to a QA directory or machine. He differentiates the two targets by saying that the staging target is used for this purpose, whereas the deploy target actually moves the project into production. If you have a QA group, I think they will probably be the ones to move the final product into production, so having two different targets doesn't seem all that useful to me.

The publish target would essentially perform a build and test, and then zip the sources, binaries, and support files, and copy/FTP them to your distribution sites. This seems most useful for open source projects, such as Ant, in which you want to distribute binary versions of your product along with the source code.

This concludes our discussion of standard names for targets that you'll see in almost every build file.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020