Tutorial of java programming with Apache Ant

SHARE & COMMENT :

This article guides you through java programming with Apache Ant with the steps listed as below. The following are the steps used in the articles to explain the Ant script creation. If you have any questions, please write it in the comments section. If you are interested in receiving the future articles on Java, please subscribe here.

  1. Create a simple java program(WelcomeToJavaBeat) and run it from command prompt.
  2. Build the JAR and use the JAR to run the WelcomeToJavaBeat application.
  3. Use Apache Ant to create a buildfile for WelcomeToJavaBeat application.
  4. Build WelcomeToJavaBeat application to include external library(log4j) and hence create Apache Ant buildfile for this application

We have taken some references from the Apache Ant web site for the above tasks. We created this post as there was chance for better clarification.

Task 1: Create a simple java program(WelcomeToJavaBeat) and run it from command prompt

  1. Create the following directory structure ( here [basedir] can be any directory):[basedir]\src\net\javaBeat
    [basedir]\build\classes
    [basedir]\build\jarFolder build contains all the generated files.Folder [basedir]\build\classes shall include all compiled files and [basedir]\build\jar folder shall contain the JAR-file.
  2. Create a simple java program(WelcomeToJavaBeat.java) in [basedir]\src\net\javaBeat and run it from command prompt.
    package net.javaBeat;
    public class WelcomeToJavaBeat {
        public static void main(String[] args) {
            System.out.println("Welcome To JavaBeat");
        }
    }
  3. Compile and run the code as follows:
    javac -sourcepath src -d build\classes src\net\javaBeat\WelcomeToJavaBeat.java
    java -cp build\classes net.javaBeat.WelcomeToJavaBeat

    The second command runs the application by calling the class fileOutput:

    Welcome To JavaBeat

Task2: Build the JAR and use the JAR to run the WelcomeToJavaBeat application

Build a JAR file for the java application and use the JAR command to run the application

  1. Create a manifest file.
    • echo Main-Class: net.javaBeat.WelcomeToJavaBeat>myManifest:
    • Do not have blanks around the “>”sign in the echo Main-Class instruction because it would falsify it.
    • This command creates a myManifest file in the [basedir]
  2. Create the JAR. (Don’t miss the “dot” at the end of the command.)
    • jar cfm build\jar\WelcomeToJavaBeat.jar myManifest -C build\classes .
  3. Run the application.
    • java -jar build\jar\WelcomeToJavaBeat.jar

Task3: Use Apache Ant to create a buildfile for WelcomeToJavaBeat application

Ant uses build.xml as the name for a build file by default, so our [basedir]\build.xml would be as follows. It’s a good practice to have a “clean” target, which deletes all the existing stuff from the directories. The clean target must be the first task to be running after starting the Ant script.

<project>

    <target name="clean">
        <delete dir="build"/>
    </target>

    <target name="compile">
        <mkdir dir="build/classes"/>
        <javac srcdir="src" destdir="build/classes"/>
    </target>

    <target name="jar">
        <mkdir dir="build/jar"/>
        <jar destfile="build/jar/WelcomeToJavaBeat.jar" basedir="build/classes">
            <manifest>
                <attribute name="Main-Class" value="net.javaBeat.WelcomeToJavaBeat"/>
            </manifest>
        </jar>
    </target>

    <target name="run">
        <java jar="build/jar/WelcomeToJavaBeat.jar" fork="true"/>
    </target>

</project>

Use the following command to compile,package and run the application:
ant compile jar run

The above build file can be enhanced as follows:

  • Many a times we reference the same directories and main-class.We can address this problem using properties.
  • jar-name are hard coded,which can be taken care of by using a special property – an attribute of the <project>-tag
  • While invocation we need to remember right order of build steps.This can be dealt with by using dependencies.
<project name="WelcomeToJavaBeat" basedir="." default="main">

    <property name="src.dir"     value="src"/>
    <property name="build.dir"   value="build"/>
    <property name="classes.dir" value="${build.dir}/classes"/>
    <property name="jar.dir"     value="${build.dir}/jar"/>
    <property name="main-class"  value="net.javaBeat.WelcomeToJavaBeat"/>

   <target name="clean">
        <delete dir="${build.dir}"/>
    </target>

    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <javac srcdir="${src.dir}" destdir="${classes.dir}"/>
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="${jar.dir}"/>
        <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            <manifest>
                <attribute name="Main-Class" value="${main-class}"/>
            </manifest>
        </jar>
    </target>

    <target name="run" depends="jar">
        <java jar="${jar.dir}/${ant.project.name}.jar" fork="true"/>
    </target>

    <target name="clean-build" depends="clean,jar"/>

    <target name="main" depends="clean,run"/>

</project>

To invoke the buildfile, type ant at the command line. This runs the main target in the buildfile.Note that the project tag defines the default task as main.

Output:

C:\>ant
Buildfile: build.xml

clean:

compile:
    [mkdir] Created dir: C:\build\classes
[javac] Compiling 1 source file to C:\build\classes

jar:
    [mkdir] Created dir: C:\build\jar
      [jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar

run:</pre>
<code>Welcome To JavaBeat</code>

<code>main:</code>

<code>BUILD SUCCESSFUL</code>

Task4: Build WelcomeToJavaBeat application to include external library(log4j) and hence create Apache Ant buildfile for this application</b></h3>Store external libraries in a new directory lib. Log4J can be downloaded from the Apache site. Create the lib directory and extract the log4j-1.2.17.jar into that lib-directory. Modify java source to use this library and also modify the buildfile so that this library could be accessed during compilation and run.evised Java Source:

 package net.javaBeat;

 import org.apache.log4j.BasicConfigurator;
 import org.apache.log4j.Logger;

 public class WelcomeToJavaBeat {

 static Logger logger = Logger.getLogger(WelcomeToJavaBeat.class);
 public static void main(String[] args) {
 BasicConfigurator.configure();
 logger.info("Welcome To JavaBeat");// the old System Out-statement
 }
}

Revised buildfile:

<project name="WelcomeToJavaBeat" basedir="." default="main">

    <property name="src.dir"     value="src"/>
    <property name="build.dir"   value="build"/>
    <property name="classes.dir" value="${build.dir}/classes"/>
    <property name="jar.dir"     value="${build.dir}/jar"/>
    <property name="lib.dir"     value="lib"/>
    <property name="main-class"  value="net.javaBeat.WelcomeToJavaBeat"/>

    <path id="classpath">
            <fileset dir="${lib.dir}" includes="**/*.jar"/>
    </path>

   <target name="clean">
        <delete dir="${build.dir}"/>
    </target>

    <target name="compile">
        <mkdir dir="${classes.dir}"/>
        <javac srcdir="${src.dir}" destdir="${classes.dir}" classpathref="classpath"/>
    </target>

    <target name="jar" depends="compile">
        <mkdir dir="${jar.dir}"/>
        <jar destfile="${jar.dir}/${ant.project.name}.jar" basedir="${classes.dir}">
            <manifest>
                <attribute name="Main-Class" value="${main-class}"/>
            </manifest>
        </jar>
    </target>

    <target name="run" depends="jar">
    	<java fork="true" classname="${main-class}">
                <classpath>
                    <path refid="classpath"/>
                    <path location="${jar.dir}/${ant.project.name}.jar"/>
                </classpath>
        </java>

    </target>
    <target name="clean-build" depends="clean,jar"/>
    <target name="main" depends="clean,run"/>
</project>

Following are the steps to modify the buildfile:

  • add property name lib.dir
  • add path element for classpath to include JARs in lib.dir
  • in the compile target, add classpathref to use the classpath which points to the external library JAR.
  • modify run task, such that it refers to the main-class,finds the project JAR and uses the classpath with the JARs in the library.
Run ant and the following output would be displayed:
C:\>ant
Buildfile: build.xml

clean:
   [delete] Deleting directory C:\build

compile:
    [mkdir] Created dir: C:\build\classes
[javac] Compiling 1 source file to C:\build\classes

jar:
    [mkdir] Created dir: C:\build\jar
      [jar] Building jar: C:\build\jar\WelcomeToJavaBeat.jar

run:
     


[main] INFO net.javaBeat.WelcomeToJavaBeat - Welcome To JavaBeat main: BUILD SUCCESSFUL

Summary

We saw stepwise to build a simple java application through command prompt.Then created buildfile to run this simple java application.Further we enhanced the application to include logging using external jar(log4j).We also modified the buildfile to include the external jars.On similar lines we can enhance this appliction to include Junit(testing tool).

If you have any questions, please write it in the comments section. If you are interested in receiving the future articles on Java, please subscribe here.

Comments

comments

About Manisha Patil

Manisha S Patil, currently residing at Pune India. She is currently working as freelance writer for websites. She had earlier worked at Caritor Bangalore, TCS Bangalore and Sungard Pune. She has 5 years of experience in Java/J2EE technologies.

Trackbacks

  1. [...] two features of ANT which are used to monitor the build process: Listeners and Loggers. In the previous articles on ANT we saw that ANT has logging feature(logging using external log4j). If the logger is not [...]

  2. [...] and get started with the Maven. Before the popularity of using Maven, most of the projects used Ant Script for the projects build which is used only for the build [...]

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better