Sunday, June 29, 2008

Java Development with Ant

Introduction
A defined process is one of the most necessary and important tool in the field of software development. There is no doubt that it is an overhead to define a process for compiling and building software applications, but the benefits are most visible when maintenance comes into picture. It definitely saves a lot of time and effort and increases maintainability for software applications. As the build process becomes more complex, for example, with EJB builds, it becomes more necessary to achieve such standardization. There arises, thus, a need for establishment, documentation, and automation of the exact series of steps as much as possible. Besides speeding up the migration of software from one platform to the other, a build process also removes many issues related to compilation, setting up of classpaths and references that might cost the project a lot during the maintenance phase.
The document describes the usage of Ant to define a process for building Java applications.
Open Source Java: Ant
Ant, an open source Java project, has been gaining in usage and attention lately and rightfully so. Ant is driving ease of use in cross-platform software development by dragging the redoubtable "make"-style of build tool into this new century. Ant supports the usage of a large number of built-in tasks in Ant without any customization. It is similar to make but is written in Java (requires the Java platform and is OS independent). It is best suited to building Java projects. The most immediately noticeable difference between Ant and make is that Ant uses an xml file (by default named as build.xml) to describe the build process and its dependencies.
Why Use Ant?
There are several reasons why ant has taken a rapid uptake in the development community. A few of them are worth mentioning here:
• Open
Ant is an open source project available under the Apache license. You can download and modify the source code as with all other open source projects. Ant's extensibility means, however, that most modifications you may require can be included via some predefined mechanisms (mostly by modifying the build.xml file only and not touching the code for Ant). Ant uses XML buildfiles. This means that anyone conversant with basic XML structures and formatting can comprehend and write an Ant file. And from a development point of view, almost everyone understands basic XML.

• Cross Platform
Along with XML, the use of Java to develop Ant makes it the perfect solution for those people developing programs designed to run or be built across a range of different operating systems.

• Extensible
Ant is extensible in two ways: new tasks and build listeners. New tasks are used to extend the capabilities of the build process, while build listeners are used to help hook into the build process to add extra error tracking functionality.

• Integration
Finally, the fact that Ant is extensible and open means that integration with your favorite editor or development environment becomes very easy. Indeed, several people have contributed packages to hook Ant into the most popular environments.

Some useful Ant commands
Here are some useful commands that are built in the Ant distribution.
Command Description
Ant Used to execute another ant process from within the current one.
Copydir Used to copy an entire directory.
Copyfile Used to copy a single file.
Delete Deletes either a single file or all files in a specified directory and its sub-directories.
Exec Executes a system command. When the os attribute is specified, then the command is only executed when Ant is run on one of the specified operating systems.
Jar Jars a set of files.
Java Executes a Java class within the running (Ant) VM or forks another VM if specified.
Javac Compiles a source tree within the running (Ant) VM.
Javadoc/Javadoc2 Generates code documentation using the javadoc tool.
Mkdir Makes a directory.
Property Sets a property (by name and value), or set of properties (from file or resource) in the project.


Example described
The following example file describes how to use Ant to perform simple compilation of java classes and creating a jar file.
Sample build.xml































The example assumes a typical Java project - a directory structure of source files which we want to build into a separate directory containing the compiled class files. The build.xml file describes about the project and the tasks that we want to perform over the project. Each task is called a target, in terms of Ant terminology. Before we look into each target, the first and the most important point to be noted here is that the build.xml file is a well-formed xml file (and hence the first line of the file that says this file is an xml file. The following describes each section in detail:
- Project
The project element describes the name of the project. This is the name of the project that we are trying to build. This element also mentions about a default target inside the build.xml file, that should be executed whenever we run “ant” over this file. And finally a base directory, where the source code is present, is also mentioned. The base directory is the one from where all path calculations are done.
- Target
A target is a set of tasks that need to be performed. Each project may have one or more targets. When starting Ant, any of the targets can be specified to be executed. When no target is mentioned, the default target is used. In the above mentioned example build file, we have used four targets, namely clean, init, compile and jar. Each target is defined to execute certain set of tasks.
A target can also depend on one or more other targets defined in the build.xml file. Dependency(s) specifies the order of execution of the ant tasks. It must be noted that it does not affect whether the target that specifies the dependency(s) gets executed if the dependent target(s) did not (need to) run.
- Tasks
A task is a piece of code that can be executed. Tasks have a common structure:
.
where name is the name of the task, attributeN is the name of the task and valueN is the value for the attributeN. The tasks used in our example build.xml file are delete, mkdir, javac, jar, etc. These tasks are mentioned inside a target.
- Properties
A project can have a set of properties. These might be set in the buildfile by the property task, or might be set outside Ant. A property has a name and a value; the name is case-sensitive. Properties may be used in the value of task attributes. This is done by placing the property name between "${" and "}" in the attribute value.
- Use of external tasks ( a method of extending the capabilities of Ant)
Ant supports a plug-in mechanism for using third party tasks (the tasks that are not defined by default in Ant). For using them in a build file, we need to place the implementation of those tasks in a path where Ant can find them and then declare the task inside the build file. This is done by using an Ant task called “taskdef”.




Running Ant – via command line
Ant can be run from the command line by running the command “ant”. Make sure that the path to the directory where ant.bat (or ant.sh) – usually at \bin - can be found. When no arguments are specified, ant looks for a file named build.xml in the current directory and then looks for a default target to be executed. To make Ant use a build file other than build.xml, use the command-line option -buildfile file, where file is the name of the build file you want to use.

Examples of running ant through command line:

- Command : ant
o runs Ant using the build.xml file in the current directory, on the default target.
- Command : ant -buildfile test.xml
o runs Ant using the test.xml file in the current directory, on the default target.
- Command : ant -buildfile test.xml dist
o runs Ant using the test.xml file in the current directory, on the target called dist.
- Command : ant -buildfile test.xml -Dbuild=build/classes dist
o runs Ant using the test.xml file in the current directory, on the target called dist, setting the build property to the value build/classes.
- Command : ant -lib /home/ant/extras
o runs Ant picking up additional task and support jars from the /home/ant/extras location

Running Ant – via Java
Ant can also be started from one of the two entry points –

• java -Dant.home=c:\ant org.apache.tools.ant.Main [options] [target]
• java -Dant.home=c:\ant org.apache.tools.ant.launch.Launcher [options] [target]

The first method runs Ant's traditional entry point. The second method uses the Ant Launcher introduced in Ant 1.6. The former method does not support the -lib option and all required classes are loaded from the CLASSPATH. You must ensure that all required jars are available. At a minimum the CLASSPATH should include:
• ant.jar and ant-launcher.jar
• jars/classes for your XML parser
• the JDK's required jar/zip files
The latter method supports the -lib, -nouserlib, -noclasspath options and will load jars from the specified ANT_HOME. You should start the latter with the most minimal classpath possible, generally just the ant-launcher.jar.
Some troubleshooting tips
If things do not work, especially simple things like ant -version, then something is wrong with the configuration. Here are a few tips/suggestions to check what might have gone wrong:
1. Check the environment variables. Are ANT_HOME and JAVA_HOME correct? If they have quotes or trailing slashes, remove them.
2. Unset CLASSPATH; if that is wrong things go horribly wrong. Ant does not need the CLASSPATH variable defined to anything to work.
3. Is your path correct? is Ant on it? What about JDK/bin? have you tested this? If you are using Jikes, is it on the path? A createProcess error (especially with ID=2 on windows) usually means executable not found on the path.
4. Which version of ant are you running? Other applications distribute a copy -it may be being picked up by accident.
5. If a task is failing to run, are there any libraries which it depends on missing?
6. If a task doesn't do what you expect, run ant -verbose or ant -debug to see what is happening.
Limitations
• Ant build files are written in XML. For unfamiliar users, both XML itself and the complex structure (hierarchical, partly ordered, and pervasively cross-linked) of Ant documents can be a barrier to learning. A GUI called Antidote was available for a time, but never gained a following and has been retired from the Apache project. Moreover, the language Ant uses is quite verbose and the build files of large or complex projects become unmanageably large; good design and modularization of build files can improve readability but not reduce size.
• Many of the older tasks—the core ones that are used every day, such as , and —use default values for options that are not consistent with more recent tasks. Changing those defaults would break existing tasks.
• When expanding properties in a string or text element, undefined properties are not raised as an error, but left as an unexpanded reference (e.g. ${unassigned.property}).
• Ant has limited fault handling rules, and no persistence of state, so it cannot be used as a workflow tool for any workflow other than classic build and test processes.
• The Ant target model does not treat artifacts as targets. In most build tools a target is an artifact created by the build -- a program, library, intermediate object file, PDF documentation, etc. -- and rules specify the dependencies between targets and the tasks to run to build a target when it is out of date. In Ant a target is a group of tasks rather than an artifact. This means that Ant is sometimes unable to determine the relationship between an artifact and the task sequence to build the artifact and this logic must be implemented by the programmer using Ant's control structures.
• Once a property is defined it cannot be changed by any of the core tasks. Antcontrib provides a variable task to go around this problem.
• Reuse of build file fragment is hard. Ant1.7 makes it easier, with and , but this does run the risk of providing even more complexity for new Ant users to get into trouble with.
Conclusion
As with any new tool, it's up to the various individuals and teams out there to decide if Ant fits with the way they currently work or the way they want to work. Many other Java open source projects now use Ant as the build tool. The usage of Ant emphasizes on the importance of a build process to construct your environment in an effective and efficient manner. Ant is an easy-to-learn platform-independent tool that provides expansion as needed. The XML involved in the buildfile is easy to read and understand, and a large number of already supported commands perform the vast majority of your build tasks without expansion. If any of the above mentioned limitations come into your way, you can expand Ant to include your modifications.

Unix Commands

Unix/Linux Command Reference
File Commands
ls – directory listing
ls -al – formatted listing with hidden files
cd dir – change directory to dir
cd – change to home
pwd – show current directory
mkdir dir – create a directory dir
rm file – delete file
rm -r dir – delete directory dir
rm -f file – force remove file
rm -rf dir – force remove directory dir
cp file1 file2 – copy file1 to file2
cp -r dir1 dir2 – copy dir1 to dir2; create dir2 if it doesn't exist
mv file1 file2 – rename or move file1 to file2 if file2 is an existing directory, moves file1 into directory file2
ln -s file link – create symbolic link link to file
touch file – create or update file
cat > file – places standard input into file
more file – output the contents of file
head file – output the first 10 lines of file
tail file – output the last 10 lines of file
tail -f file – output the contents of file as it grows, starting with the last 10 lines

Process Management
ps – display your currently active processes
top – display all running processes
kill pid – kill process id pid
killall proc – kill all processes named proc
bg – lists stopped or background jobs; resume a stopped job in the background
fg – brings the most recent job to foreground
fg n – brings job n to the foreground

File Permissionschmod octal file – change the permissions of file to octal, which can be found separately for user,
group, and world by adding:
4 – read (r)
2 – write (w)
1 – execute (x)
Examples:
chmod 777 – read, write, execute for all
chmod 755 – rwx for owner, rx for group and world
For more options, see man chmod.

SSH (Secure Shell)
ssh user@host – connect to host as user
ssh -p port user@host – connect to host on port port as user
ssh-copy-id user@host – add your key to host for user to enable a keyed or passwordless login

Searching
grep pattern files – search for pattern in files
grep -r pattern dir – search recursively for pattern in dir
command grep pattern – search for pattern in the output of command
locate file – find all instances of file

System Info
date – show the current date and time
cal – show this month's calendar
uptime – show current uptime
w – display who is online
whoami – who you are logged in as
finger user – display information about user
uname -a – show kernel information
cat /proc/cpuinfo – cpu information
cat /proc/meminfo – memory information
man command – show the manual for command
df – show disk usage
du – show directory space usage
free – show memory and swap usage
whereis app – show possible locations of app
which app – show which app will be run by default

Compression
tar cf file.tar files – create a tar named file.tar containing files
tar xf file.tar – extract the files from file.tar
tar czf file.tar.gz files – create a tar with Gzip compression
tar xzf file.tar.gz – extract a tar using Gzip
tar cjf file.tar.bz2 – create a tar with Bzip2 compression
tar xjf file.tar.bz2 – extract a tar using Bzip2
gzip file – compresses file and renames it to file.gz
gzip -d file.gz – decompresses file.gz back to file

Network
ping host – ping host and output results
whois domain – get whois information for domain
dig domain – get DNS information for domain
dig -x host – reverse lookup host
wget file – download file
wget -c file – continue a stopped download

Installation Shortcuts
Ctrl+C – halts the current command
Ctrl+Z – stops the current command, resume with fg in the foreground or bg in the background
Ctrl+D – log out of current session, similar to exit
Ctrl+W – erases one word in the current line
Ctrl+U – erases the whole line
Ctrl+R – type to bring up a recent command
!! - repeats the last command
exit – log out of current session