Sunday, January 22, 2012

Own Custom Task in Ant

Many times when developing complicated Ant scripts we feel the need of custom Ant tags or need to develop our own task in Ant. Here is a step by step guide to achieve the same
Prerequisites:
Download and set up the Apache ant.
 1.Create a new Java Project in eclipse.Right click on Project->Properties->Java Build Path->Add external Jar. Browse to Ant.jar file in ANT_HOME/lib folder.



2.Make a new class say Hello which has to extend class org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;

public class HelloWorld extends Task {
 private String retproperty = null;
 private String msg;

 public String getRetProperty() {
  return retproperty;
 }

 public void setRetProperty(String property) {
  this.retproperty = property;
 }

 public void setMsg(String msg) {
  this.msg = msg;
 }

 public void execute() throws BuildException {
  System.out.println(msg);
  Project project = getProject();
  project.setProperty(retproperty,
    "This is Value Returned By Custom task to Ant script");
 }
}

In this program we will learn how to pass a value to java class from ant and how to get the value as return value from Java Custom task.
3.Once you have the java code ready in eclipse click on File=>Export=>Choose Jar and expost to any suitable location on your system. as shown in below screenshot

4. Now its time to write Ant script which will call this custom task pass a value and also read the value returned by the task.So write a similar Ant script.Here classpath should be location where jar in Step 3 was exported.

  
  
   
   
  


5.Now we can run the Ant script through command prompt or eclipse as per convenience. We will get output as below
In developing Ant custom task whatever Java variables we want to be accessed through ant we should make them private with public getter and setter methods.Now when through Ant below line is executed



This executes method of the HelloWorld class is invoked and msg variable is initialised with value passed. Similarly 
project.setProperty(retproperty,
    "This is Value Returned By Custom task to Ant script");

The above line sets the value into property val  which is again defined in retproperty. So that in Ant script variable val will hold the value returned or set inside the class so we can use it for further processing.

Please comment me if you face any issue implementing it.


1 comment:

Unknown said...

Hi Amol,

When i tried your example iam getting the below error in the build file.
Multiple markers at this line
- Default target build does not exist in this
project
- 9 changed lines

Could you please help me with your valuable suggestions.
Thanks.