Discuss Apache ANT ”; Previous Next Apache ANT is a Java based build tool from Apache Software Foundation. Apache ANT’s build files are written in XML and they take advantage of being open standard, portable and easy to understand. This tutorial will teach you how to use Apache ANT to automate the build and deployment process in simple and easy steps. After completing this tutorial, you will find yourself at a moderate level of expertise in using Apache ANT from where, you can take yourself to next levels. Print Page Previous Next Advertisements ”;
Category: Ant
ANT – JUnit Integration
Ant – JUnit Integration ”; Previous Next JUnit is the commonly used unit testing framework for Java-based developments. It is easy to use and easy to extend. There are a number of JUnit extensions available. If you are unfamiliar with JUnit, you should download it from www.junit.org and read its manual. This chapter shows how to execute JUnit tests by using Ant. The use of Ant makes it straight forward through the JUnit task. The attributes of the JUnit task are presented below − Sr.No Properties & Description 1 dir Where to invoke the VM from. This is ignored when fork is disabled. 2 jvm Command used to invoke the JVM. This is ignored when fork is disabled. 3 fork Runs the test in a separate JVM. 4 errorproperty The name of the property to set if there is a JUnit error. 5 failureproperty The name of the property to set if there is a JUnit failure. 6 haltonerror Stops execution when a test error occurs. 7 haltonfailure Stops execution when a failure occurs. 8 printsummary Advises Ant to display simple statistics for each test. 9 showoutput Advises Ant to send the output to its logs and formatters. 10 tempdir Path to the temporary file that Ant will use. 11 timeout Exits the tests that take longer to run than this setting (in milliseconds). Let us continue the theme of the Hello World Fax web application and add a JUnit target. The following example shows a simple JUnit test execution − <target name=”unittest”> <junit haltonfailure=”true” printsummary=”true”> <test name=”com.tutorialspoint.UtilsTest”/> </junit> </target> This example shows the execution of JUnit on the com.tutorialspoint.UtilsTest junit class. Running the above code produces the following output − test: [echo] Testing the application [junit] Running com.tutorialspoint.UtilsTest [junit] Tests run: 12, Failures: 0, Errors: 0, Time elapsed: 16.2 sec BUILD PASSED Print Page Previous Next Advertisements ”;
ANT – Quick Guide
Ant – Quick Guide ”; Previous Next Ant – Introduction ANT stands for Another Neat Tool. It is a Java-based build tool from computer software development company Apache. Before going into the details of Apache Ant, let us first understand why we need a build tool. Need for a Build Tool On an average, a developer spends a substantial amount of time doing mundane tasks like build and deployment that include − Compiling the code Packaging the binaries Deploying the binaries to the test server Testing the changes Copying the code from one location to another To automate and simplify the above tasks, Apache Ant is useful. It is an Operating System build and deployment tool that can be executed from the command line. History of Apache Ant Ant was created by software developer James Duncan Davidson who is also the original creator of webserver application Tomcat. Ant was originally used to build Tomcat, and was bundled as a part of Tomcat distribution. It was born out of the problems and complexities associated with the Apache Make tool. It was promoted as an independent project in Apache in the year 2000. The latest version of Apache Ant as on October 2021 is 1.10.12. Features of Apache Ant The features of Apache Ant are listed below − It is the most complete Java build and deployment tool available. It is platform neutral and can handle platform specific properties, such as file separators. It can be used to perform platform specific tasks such as modifying the modified time of a file using ”touch” command. Ant scripts are written using plain XML. If you are already familiar with XML, you can learn Ant pretty quickly. Ant is good at automating complicated repetitive tasks. Ant comes with a big list of predefined tasks. Ant provides an interface to develop custom tasks. Ant can be easily invoked from the command line and it can integrate with free and commercial IDEs. Ant – Environment Setup Apache Ant is distributed under the Apache Software License which is a fully-fledged open source license certified by the open source initiative. The latest Apache Ant version, including its full-source code, class files, and documentation can be found at https://ant.apache.org. Installing Apache Ant It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions available at file:///C:/java/java_environment_setup.htm Ensure that the JAVA_HOME environment variable is set to the folder, where your JDK is installed. Download the binaries from https://ant.apache.org Unzip the zip file to a convenient location c:folder by using Winzip, winRAR, 7-zip or similar tools. Create a new environment variable called ANT_HOME that points to the Ant installation folder. In this case, it is c:apache-ant-1.10.12-bin folder. Append the path to the Apache Ant batch file to the PATH environment variable. In our case, this would be the c:apache-ant-1.10.12-binbin folder. Verifying the Installation To verify the successful installation of Apache Ant on your computer, type ant on your command prompt. You should see an output as given below − C:>ant -version Apache Ant(TM) version 1.10.12 compiled on October 13 2021 If you do not see the above output, then please verify that you have followed the installation steps properly. Installing Eclipse This tutorial also covers integration of Ant with Eclipse integrated development environment (IDE). Hence, if you have not installed Eclipse, please download and install Eclipse. Steps to install Eclipse Download the latest Eclipse binaries from www.eclipse.org Unzip the Eclipse binaries to a convenient location, say c:folder. Run Eclipse from c:eclipseeclipse.exe. Ant – Build Files Typically, Ant”s build file, called build.xml should reside in the base directory of the project. However, there is no restriction on the file name or its location. You are free to use other file names or save the build file in some other location. For this exercise, create a file called build.xml anywhere in your computer with the following contents − <?xml version=”1.0″?> <project name=”Hello World Project” default=”info”> <target name=”info”> <echo>Hello World – Welcome to Apache Ant!</echo> </target> </project> Note that there should be no blank line(s) or whitespace(s) before the xml declaration. If you allow them, the following error message occurs while executing the ant build − The processing instruction target matching “[xX][mM][lL]” is not allowed. All build files require the project element and at least one target element. The XML element project has three attributes which are as follows − Sr.No Attributes & Description 1 name The Name of the project. (Optional) 2 default The default target for the build script. A project may contain any number of targets. This attribute specifies which target should be considered as the default. (Mandatory) 3 basedir The base directory (or) the root folder for the project. (Optional) A target is a collection of tasks that you want to run as one unit. In our example, we have a simple target to provide an informational message to the user. Targets can have dependencies on other targets. For example, a deploy target may have a dependency on the package target, the package target may have a dependency on the compile target and so forth. Dependencies are denoted using the depends attribute. For example − <target name=”deploy” depends=”package”> …. </target> <target name=”package” depends=”clean,compile”> …. </target> <target name=”clean” > …. </target> <target name=”compile” > …. </target> The target element has the following attributes − Sr.No Attributes &
Ant – If Else Arguments ”; Previous Next Ant allows to run targets based on passed conditions. We can use if statement or unless statement. Syntax <target name=”copy” if=”copyFile”> <echo>Files are copied.</echo> </target> <target name=”move” unless=”copyFile”> <echo>Files are moved.</echo> </target> We”ll be using -Dproperty to pass varible like copyFile to the build task. The variable is to be defined, the value of variable is of no relevance here. Example Create build.xml with the following content − <?xml version=”1.0″?> <project name=”sample” basedir=”.” default=”copy”> <target name=”copy” if=”copyFile”> <echo>Files are copied.</echo> </target> <target name=”move” unless=”copyFile”> <echo>Files are moved.</echo> </target> </project> Output Running Ant on the above build file produces the following output − F:tutorialspointant>ant -DcopyFile=true Buildfile: F:tutorialspointantbuild.xml copy: [echo] Files are copied. BUILD SUCCESSFUL Total time: 0 seconds F:tutorialspointant>ant move Buildfile: F:tutorialspointantbuild.xml move: [echo] Files are moved. BUILD SUCCESSFUL Total time: 0 seconds F:tutorialspointant>ant move -DcopyFile=true Buildfile: F:tutorialspointantbuild.xml move: BUILD SUCCESSFUL Total time: 0 seconds F:tutorialspointant>ant move -DcopyFile=false Buildfile: F:tutorialspointantbuild.xml move: BUILD SUCCESSFUL Total time: 0 seconds F:tutorialspointant>ant move -DcopyFile=true Buildfile: F:tutorialspointantbuild.xml move: BUILD SUCCESSFUL Total time: 0 seconds F:tutorialspointant>ant move Buildfile: F:tutorialspointantbuild.xml move: [echo] Files are moved. BUILD SUCCESSFUL Total time: 0 seconds F:tutorialspointant> Print Page Previous Next Advertisements ”;
ANT – Extending Ant
Ant – Extending Ant ”; Previous Next Ant comes with a predefined set of tasks, however you can create your own tasks, as shown in the example below. Custom Ant Tasks should extend the org.apache.tools.ant.Task class and should extend the execute() method. Below is a simple example − package com.tutorialspoint.ant; import org.apache.tools.ant.Task; import org.apache.tools.ant.Project; import org.apache.tools.ant.BuildException; public class MyTask extends Task { String message; public void execute() throws BuildException { log(“Message: ” + message, Project.MSG_INFO); } public void setMessage(String message) { this.message= message; } } To execute the custom task, you need to add the following to the Hello World Fax web application − <target name=”custom”> <taskdef name=”custom” classname=”com.tutorialspoint.ant.MyTask” /> <custom message=”Hello World!”/> </target> Executing the above custom task prints the message ”Hello World!” c:>ant custom test: [custom] Message : Hello World! elapsed: 0.2 sec BUILD PASSED This is just a simple example. You can use the power of Ant to do whatever you want to improve your build and deployment process. Print Page Previous Next Advertisements ”;
ANT – Useful Resources
Apache ANT – Useful Resources ”; Previous Next The following resources contain additional information on Apache ANT. Please use them to get more in-depth knowledge on this. Useful Video Courses Learn Maven and Ant the easy way! Most Popular 35 Lectures 4 hours Karthikeya T More Detail Distributed Antenna Systems (DAS) Network Deployment 49 Lectures 11 hours Hussein Rashad More Detail Fountain Of Youth – Anti-Aging Secrets for Youth, Health & Longevity 11 Lectures 56 mins Prof. Paul Cline, Ed.D More Detail Anti-Money Laundering (AML) Risk Assessment 18 Lectures 2.5 hours Vlad Karols More Detail All-Inclusive Guide to Anti-Money Laundering Compliance 2023 33 Lectures 2 hours Hassita Nowbuth More Detail Anti Money Laundering and Combating Financial Terrorism and CDD: Complete Guide 7 Lectures 1 hours Owais Ahmed Qureshi More Detail Print Page Previous Next Advertisements ”;
Ant – Using Command Line Arguments ”; Previous Next Ant can read command line arguments easily to pass data to its tasks. Commnd Line Arguments Options ant [options] [target [target2 [target3] …]] Options: -help, -h print this message and exit -projecthelp, -p print project help information and exit -version print the version information and exit -diagnostics print information that might be helpful to diagnose or report problems and exit -quiet, -q be extra quiet -silent, -S print nothing but task outputs and build failures -verbose, -v be extra verbose -debug, -d print debugging information -emacs, -e produce logging information without adornments -lib <path> specifies a path to search for jars and classes -logfile <file> use given file for log -l <file> ”” -logger <classname> the class which is to perform logging -listener <classname> add an instance of class as a project listener -noinput do not allow interactive input -buildfile <file> use given buildfile -file <file> ”” -f <file> ”” -D <property>=<value> use value for given property -keep-going, -k execute all targets that do not depend on failed target(s) -propertyfile <name> load all properties from file with -D properties taking precedence -inputhandler <class> the class which will handle input requests -find <file> (s)earch for buildfile towards the root of -s <file> the filesystem and use it -nice number A niceness value for the main thread:1 (lowest) to 10 (highest); 5 is the default -nouserlib Run ant without using the jar files from ${user.home}/.ant/lib -noclasspath Run ant without using CLASSPATH -autoproxy Java 5+ : use the OS proxies -main <class> override Ant”s normal entry point We”ll be using -Dproperty to pass varibles to the build task. Example Create a src folder with text1.txt file with following contents − This is a sample text written in 2021. Create build.xml with the following content − <?xml version=”1.0″?> <project name=”sample” basedir=”.” default=”copy”> <target name=”copy”> <copy todir=”${dest.dir}” filtering=”true”> <fileset dir=”${src.dir}”/> </copy> </target> </project> Output Here we”re using src.dir and dest.dir properties without defining them. We”ll pass them using command line arguments. Running Ant on the above build file produces the following output − F:tutorialspointant>ant -Dsrc.dir=src -Ddest.dir=build Buildfile: F:tutorialspointantbuild.xml copy: [copy] Copying 1 file to F:tutorialspointantbuild BUILD SUCCESSFUL Total time: 0 seconds F:tutorialspointant> Verify the content of copied file to build folder. This is a sample text written in 2021. Print Page Previous Next Advertisements ”;
ANT – Listeners and Loggers
Ant – Listeners & Loggers ”; Previous Next Ant allows the build process to be monitored using listeners and loggers. Listeners Ant provides following events to be captured using listeners. build started build finished target started target finished task started task finished message logged Custom listeners can be registered on command line using -listener argument. Loggers Loggers extends listeners capabilities and add the following features Can log information to console or file using -logfile argument Can log using logging levels like -quiet, -verbose, -debug Are emacs-mode aware Built-in Listeners/loggers org.apache.tools.ant.DefaultLogger − The logger used implicitly unless overridden with the -logger command-line switch. org.apache.tools.ant.NoBannerLogger − This logger omits output of empty target output. org.apache.tools.ant.listener.MailLogger − Extends DefaultLogger such that output is still generated the same, and when the build is finished an e-mail can be sent. org.apache.tools.ant.listener.AnsiColorLogger − Colorifies the build output. org.apache.tools.ant.listener.Log4jListener − Passes events to Apache Log4j for highly customizable logging. org.apache.tools.ant.XmlLogger − Writes the build information to an XML file. org.apache.tools.ant.TimestampedLogger − Prints the time that a build finished org.apache.tools.ant.listener.BigProjectLogger − Prints the project name every target org.apache.tools.ant.listener.SimpleBigProjectLogger − Prints the project name for subprojects only, otherwise like NoBannerLogger Since Ant 1.8.1 org.apache.tools.ant.listener.ProfileLogger − The default logger, with start times, end times and durations added for each task and target. Example Create build.xml with the following content: <?xml version=”1.0″?> <project name=”sample” basedir=”.” default=”copy”> <target name=”copy”> <echo>File Copied</echo> </target> </project> Output Running Ant on the above build file produces the following output − F:tutorialspointant>ant -logger org.apache.tools.ant.listener.TimestampedLogger Buildfile: F:tutorialspointantbuild.xml copy: [echo] File Copied BUILD SUCCESSFUL – at 03/12/21, 11:24 AM Total time: 0 seconds F:tutorialspointant>ant -logger org.apache.tools.ant.XmlLogger -verbose -logfile build_log.xml Apache Ant(TM) version 1.10.12 compiled on October 13 2021 Trying the default build file: build.xml Buildfile: F:tutorialspointantbuild.xml Now you can check build_log.xml file is created with relevant logs. Print Page Previous Next Advertisements ”;
ANT – Packaging Applications
Ant – Packaging Applications ”; Previous Next We have learnt the different aspects of Ant using the Hello World Fax web application in bits and pieces. Now, it is time to put everything together to create a full and complete build.xml file.Consider build.properties and build.xml files as follows − build.properties The file is given below for build.properties. deploy.path=c:tomcat6webapps build.xml The build.xml file is as follows − <?xml version=”1.0″?> <project name=”fax” basedir=”.” default=”usage”> <property file=”build.properties”/> <property name=”src.dir” value=”src”/> <property name=”web.dir” value=”war”/> <property name=”javadoc.dir” value=”doc”/> <property name=”build.dir” value=”${web.dir}/WEB-INF/classes”/> <property name=”name” value=”fax”/> <path id=”master-classpath”> <fileset dir=”${web.dir}/WEB-INF/lib”> <include name=”*.jar”/> </fileset> <pathelement path=”${build.dir}”/> </path> <target name=”javadoc”> <javadoc packagenames=”faxapp.*” sourcepath=”${src.dir}” destdir=”doc” version=”true” windowtitle=”Fax Application”> <doctitle><![CDATA[<h1>= Fax Application =</h1>]]></doctitle> <bottom><![CDATA[Copyright © 2011. All Rights Reserved.]]></bottom> <group title=”util packages” packages=”faxapp.util.*”/> <group title=”web packages” packages=”faxapp.web.*”/> <group title=”data packages” packages=”faxapp.entity.*:faxapp.dao.*”/> </javadoc> </target> <target name=”usage”> <echo message=””/> <echo message=”${name} build file”/> <echo message=”———————————–“/> <echo message=””/> <echo message=”Available targets are:”/> <echo message=””/> <echo message=”deploy –> Deploy application as directory”/> <echo message=”deploywar –> Deploy application as a WAR file”/> <echo message=””/> </target> <target name=”build” description=”Compile main source tree java files”> <mkdir dir=”${build.dir}”/> <javac destdir=”${build.dir}” source=”1.5″ target=”1.5″ debug=”true” deprecation=”false” optimize=”false” failonerror=”true”> <src path=”${src.dir}”/> <classpath refid=”master-classpath”/> </javac> </target> <target name=”deploy” depends=”build” description=”Deploy application”> <copy todir=”${deploy.path}/${name}” preservelastmodified=”true”> <fileset dir=”${web.dir}”> <include name=”**/*.*”/> </fileset> </copy> </target> <target name=”deploywar” depends=”build” description=”Deploy application as a WAR file”> <war destfile=”${name}.war” webxml=”${web.dir}/WEB-INF/web.xml”> <fileset dir=”${web.dir}”> <include name=”**/*.*”/> </fileset> </war> <copy todir=”${deploy.path}” preservelastmodified=”true”> <fileset dir=”.”> <include name=”*.war”/> </fileset> </copy> </target> <target name=”clean” description=”Clean output directories”> <delete> <fileset dir=”${build.dir}”> <include name=”**/*.class”/> </fileset> </delete> </target> </project> In the above mentioned example − We first declare the path to the webapps folder in Tomcat in the build properties file as the deploy.path variable. We also declare the source folder for the java files in the src.dir variable. Then, we declare the source folder for the web files in the web.dir variable. javadoc.dir is the folder for storing the java documentation, and build.dir is the path for storing the build output files. After that, we declare the name of the web application, which is fax in our case. We also define the master class path, which contains the JAR files present in the WEB-INF/lib folder of the project. We also include the class files present in the build.dir in the master class path. The Javadoc target produces the javadoc required for the project and the usage target is used to print the common targets that are present in the build file. The above example shows two deployment targets: deploy and deploywar. The deploy target copies the files from the web directory to the deploy directory preserving the last modified date time stamp. This is useful, when deploying to a server that supports hot deployment. The clean target clears all the previously built files. The deploywar target builds the war file and then, copies the war file to the deploy directory of the application server. Print Page Previous Next Advertisements ”;
ANT – Create WAR Files
Ant – Create WAR Files ”; Previous Next Creating Web Archive (WAR) files with Ant is extremely simple, and very similar to the creating JAR files task. After all, WAR file, like JAR file is just another ZIP file. The WAR task is an extension to the JAR task, but it has some nice additions to manipulate what goes into the WEB-INF/classes folder, and generating the web.xml file. The WAR task is useful to specify a particular layout of the WAR file. Since, the WAR task is an extension of the JAR task, all attributes of the JAR task apply to the WAR task. Sr.No Attributes & Description 1 webxml Path to the web.xml file. 2 lib A grouping to specify what goes into the WEB-INFlib folder. 3 classes A grouping to specify what goes into the WEB-INFclasses folder. 4 metainf Specifies the instructions for generating the MANIFEST.MF file. Continuing our Hello World Fax Application project, let us add a new target to produce the jar files. But before that, let us consider the war task. Consider the following example − <war destfile=”fax.war” webxml=”${web.dir}/web.xml”> <fileset dir=”${web.dir}/WebContent”> <include name=”**/*.*”/> </fileset> <lib dir=”thirdpartyjars”> <exclude name=”portlet.jar”/> </lib> <classes dir=”${build.dir}/web”/> </war> As per the previous examples, the web.dir variable refers to the source web folder, i.e., the folder that contains the JSP, css, javascript files etc. The build.dir variable refers to the output folder. This is where the classes for the WAR package can be found. Typically, the classes will be bundled into the WEB-INF/classes folder of the WAR file. In this example, we are creating a war file called fax.war. The WEB.XML file is obtained from the web source folder. All files from the ”WebContent” folder under web are copied into the WAR file. The WEB-INF/lib folder is populated with the jar files from the thirdpartyjars folder. However, we are excluding the portlet.jar as this is already present in the application server”s lib folder. Finally, we are copying all classes from the build directory”s web folder and putting them into the WEB-INF/classes folder. Wrap the war task inside an Ant target (usually package) and run it. This will create the WAR file in the specified location. It is entirely possible to nest the classes, lib, metainf and webinf directors, so that they live in scattered folders anywhere in the project structure. But, best practices suggest that your Web project should have the Web Content structure that is similar to the structure of the WAR file. The Fax Application project has its structure outlined using this basic principle. To execute the war task, wrap it inside a target, most commonly, the build or package target, and run them. <target name=”build-war”> <war destfile=”fax.war” webxml=”${web.dir}/web.xml”> <fileset dir=”${web.dir}/WebContent”> <include name=”**/*.*”/> </fileset> <lib dir=”thirdpartyjars”> <exclude name=”portlet.jar”/> </lib> <classes dir=”${build.dir}/web”/> </war> </target> Running Ant on this file will create the fax.war file for us. The following outcome is the result of running the Ant file − C:>ant build-war Buildfile: C:build.xml BUILD SUCCESSFUL Total time: 12.3 seconds The fax.war file is now placed in the output folder. The contents of the war file will be as mentioned below − fax.war: +—jsp This folder contains the jsp files +—css This folder contains the stylesheet files +—js This folder contains the javascript files +—images This folder contains the image files +—META-INF This folder contains the Manifest.Mf +—WEB-INF +—classes This folder contains the compiled classes +—lib Third party libraries and the utility jar files WEB.xml Configuration file that defines the WAR package Print Page Previous Next Advertisements ”;