Wednesday, March 18, 2009

Getting started with Ant

Each one of us has used Ant knowingly or unknowingly, while building our projects. But, most of us are not aware of its existence. Thanks to IDEs like Eclipse & NetBeans !!

But, I feel that one must know how things happen. How a series of commands are executed when you build your project and how you can control and alter this flow.

This entry is not meant to give you insight into the build process but it is meant to introduce the tool (Ant) to beginners like me. We will go through installation and normal usage of Ant Tool.

So, lets get started :-)

What is ANT ?

Ant is a Java-based build tool used for automating the build process.
Ant is written in Java and that's what makes it platform-independent. This also means that you lose out on doing certain things (issuing certain OS-specific commands in build.xml) that could be done fastly in a OS-dependent manner.
ANT is an acronym for "Another Neat Tool". :-)
It accepts input in form of XML files (like build.xml) and can be used to perform repeatitive task in an efficient manner.

Installing ANT

Download the binary distribution from here.
Now, all you have to do to install ant and run from command line is to set following environment variables:
  • ANT_HOME : Set this variable to the path where you have unzipped the downloaded binary distribution
  • PATH : Append the ANT_HOME/bin to the already existing PATH value. This is needed so that we can run ant from command line.
  • JAVA_HOME : Set this variable(if not already set) to the path where JDK is installed
And Bingo !! you are done with installation. It's time to test whether we have installed Ant correctly or not

Test Your Installation

To test whether you have successfully installed Ant or not, type
>ant
on command line and press enter

It will give an error like
Buildfile: build.xml doesn't exist!
Build failed
because right now there is no build.xml file existing in the current directory. Ant tool makes use of build.xml to automate the build process.

Congratulations !!
You have successfully installed ANT if you can see this error message. :-)

What is build.xml ?

It is nothing but a normal XML file that is used to automate the build process. It contains certain commands that are executed in a defined/prescribed manner. You can think of it as writing a Shell Script which will be executed by Ant tool. Actually it's more like a make-file that we have in Linux/Unix environment.

A normal build.xml file would consist of following sections, in that order:
  1. Clean - It removes all the previously deployed files of the same application, if any.
  2. Init - Creating the directories and subdirectories according to your choice
  3. Compile - Used to compile the *.java files & servlets or jsp's with the help of libraries
  4. Copy - It copies the compiled class files and servlets in their appropriate locations
  5. Create-war - Finally, we create a .war file of our application and copy it to your server's deplyoment directory so that you can run the application.
All these steps are not neccessary and it depends entirely on you that what you wanna keep in your build.xml.
A look at a simple build.xml would simply what seems so tough right now. :-)


BUILD.XML


Lets see what it really means:

1. Root Element



First line tells us that it is a XML file.
Then comes the root element, project. Rest of the code for this project will come in between project tags. It has 3 attributes:
  1. name (optional) - Name of the project
  2. default (required) - The default target to use when no target is specified
  3. basedir (optional) - This tells the basedir for all the paths mentioned in the in this script. If it is missing, then parent directory of this build script will be used as basedir

2. User-defined variables



These 2 lines declare user-defined variables which are used later in the file.
src holds the location of the current directory as given by '.'
build holds the location "basedir/build" where basedir was defined in project name above.
Remember all the paths mentioned are relative to basedir

So, property tag is used to give name-value pairs, but same effect could have been achieved by mentioning these name-value pairs in an external file (named build.properties) and using them in build.xml as they are used now.


3. Clean your earlier deployment



Target tag is like a function which you can call again to perform a reusable task.
These lines are pretty simple to understand.
The echo tag will echo/display whats written to the output console, and the delete command will delete the build directory

${build} is way to evaluate the build variable that we have defined above using property tag

4. Initialization - Creating Directory Structure for deployment



Here, we just create a directory using mkdir command.
The thing to note here is the depends attribute of target tag. This attribute is used throughout build.xml to create a chain of targets, to give a sequential flow i.e. it helps in specifying the dependencies of one module over another and tells us how the targets will be called.


5. Compiling source files and copying them to destination folder



This function compiles the source files present in src directory and stores the resulting .class files in build directory.
I have deliberately not added more steps like creating a war file and deploying it on server, because that would make this entry long and complicated un-neccessarily. Time to run what we have done so far.

Running this script

To run this script, create a folder and name it Test and copy this build.xml file in it. And to test whether your script works or not, create any correct java file in this Test folder, which we will compile.

Your directory structure should look like this.

Test
|
|------ build.xml
|
|-------HelloWorld.java


To run your build script, go to Test Folder, and type ant

C:\Users\Agraj\Desktop\Test>ant

If everything goes correct, it will give output

Buildfile: build.xml

clean:
[echo] Deleting build
[delete] Deleting directory C:\Users\Agraj\Desktop\Test\build

init:
[echo] Creating new directory: build
[mkdir] Created dir: C:\Users\Agraj\Desktop\Test\build

compile:
[echo] Compiling source files present in . to build
[javac] Compiling 1 source file to C:\Users\Agraj\Desktop\Test\build

BUILD SUCCESSFUL
Total time: 2 seconds

For starters, it doesn't and shouldn't work right away :-)
I said shouldn't because if it does, then perhaps you won't enjoy and learn more about Ant.

Having said that, the problem that occurs most commonly is that Ant tool is unable to parse the build.xml file correctly. This is so because even a space or tab inserted in xml file can cause Ant to fail. You can get to know about the extra spaces/tabs using vi editor on linux/unix machines, but it can be pretty frustating on windows to look out for such an error

Although, most of us will never change the build.xml while development but still it helps a lot when you know what happens when you build your project and you don't feel alien to the environment :-)

Random Notes :
  • Make sure that your CLASSPATH variable doesn't have any single quotes or double quotes ( ' or " ) in it even if there is a space in the path because, the presence of them will make ANT to fail.
  • Also make sure that there is no ending forward or backward slash ( / or \ ) in your CLASSPATH
  • For more on Ant, please refer to FAQ section here
  • For detailed installation from source or for setting optional parameters/preferences, one can go to the docs/manual/index.html page of the installation directory
Any comments, suggestions and corrections are welcome and required !!

Thursday, January 22, 2009

Checked Vs Unchecked Exceptions

In Java, there are 2 kinds of Exception:

Unchecked Exceptions which indicate some sort of programming error on the part of developer. Unchecked Exceptions are usually subclasses of RuntimeException class. Examples include: 
 --- NullPointerException (which is usually thrown when method is              invoked on a null object)
 --- DivideByZeroException (thrown when divide by zero happens in        your code)
 --- IllegalArgumentException (usually thrown when invalid argument        is passed to a method)
 --- ArrayIndexOutOfBoundsException (thrown when you try to access         array index beyond the memory allocated to it)
 --- ArithmeticException
 --- RuntimeException
If your methods throw an unchecked exception, then your method need not specify it as a part of its API i.e no need to write all the exceptions it throws using "throws" clause.

Checked Exceptions on the other hand, specifies conditions that are not due to human errors but due to conditions that are not in programmer's control. These include conditions such as database errors, network failures, file not found when searching or performing some operation on it. Examples include:
 --- FileNotFoundException
 --- SQLException
 --- PersistenceException
On the other hand, if your code throws any checked conditions, then either you must handle it or specify it using "throws" clause else your program will give compile-time error. 

Checked Vs Unchecked
Use Checked Exception in your code when you Client code (code that calls your code) is capable of dealing with the Exception and have ample knowledge why that Exception occurred in the first place and how to do away with it. 
Otherwise, it is always preferable to use Unchecked Exceptions since then the Client code is not forced to handle it and can choose to ignore it. Though that would not solve the problem and the exception would travel high up in hierarchy of function calls and perhaps finally encountered by the JVM, but at least the Client code is saved from the hassle of dealing with Exceptions that they don't know about it.
Let's take an example. Suppose we have a method throwing an SQLException:
The client code would never come to know that why this SQLException occurred, as it has no knowledge of underlying business logic and internal database design. Thus client is unable to handle the exception, so its always better to not force a client to handle an exception he do not know about.

Articles Worth Reading:

Saturday, January 3, 2009

Happy New Year 2009 !!

Wishing all the readers a very happy and prosperous new year ahead. :-)

Small Update About Me
I would soon be starting off with my training at ST Microelectronics, so I don't know how much time I would be able to devote to this passion of mine. But, I surely hope that this habit of mine doesn't die out so soon and I get enough opportunities to share my thoughts. 

Friday, December 26, 2008

Cygwin - An Intro

Cygwin is not something new for most of you but this blog post is meant for those students/developers who hate using(or at least installing) Linux/Unix on their system (because they have to partition their hard disk) but they have to install it just because they want to use gcc and g++
Because, I have seen many students in my department and in others too, who try to install Linux on their hard disk and in the process either corrupt it or delete some Windows partition accidently, so I hope this entry could be of some help to them.

Though, you always have the option of using Dev C++ or Visual C++, and Dev C++ also claims to be using gcc/g++. (Don't know abt Visual C++)
However, what do you do if you want to use gcc/g++/gdb/make on command line with some command line options like -o, -c, -I, or -shared. What if you want to create a shared library (or a DLL) using gcc on windows ?
One way out(the only way i know of :p) is to use Cygwin, which is nothing but a Unix-like environment for Windows. There are many packages that you can download & install along with the normal base packages to make it function just like Unix. 

I came across it when I started with JNI (Java Native Interface) (a way for Java code to interact with non-Java code....a topic big enough to span another blog entry :-)....see the tutorial for JNI here)
Because, I needed a GNU C/C++ compiler to register with an IDE (in my case NetBeans), so I downloaded Cygwin as per instructions in the tutorial and installed it, though with some problems. But, it was really good to have unix-like functionality on windows system, to be able to execute unix commands from my command line. Now, I do not need Dev C++ to compile my c/c++ programs on windows.
My advice to all budding programmers/students that they must try Cygwin at least once. Try installing it and even if you fumble, there is a lot to help you...try reading setup logs..google over the problem and you will be home surely.
More precise and accurate information about how to download and install Cygwin can be found here. A must try even if you are biased towards Java (like me) :-)