JaVa
   

A Skeleton Task Example

As you might have guessed, all Ant tasks are just Java classes either built into Ant or specified by the <taskdef> element. The only requirement of the class is that it have an execute() method that can be called by the Ant app. So, we might design a new class like the following:

package com.company.ant;
public class NewTask {
 public void execute() {
 // do something
}


With this class we could have an Ant task like this:

<taskdef ame="todo" classname="com.company.ant.NewTask">


Of course, a real Ant task has various attributes and conditions, like unless, which we probably want to be able to access from the Ant build script. In order to have access to this information, we must extend org.apache.tools.ant.Task. For example:

package com.company.ant;
import org.apache.tools.ant.Task;
public class NewTask extends org.apache.tools.ant.Task{
 public void execute() {
 // do something
}


The Task class gives us the ability to access the varous attributes contained in the build script. The methods available in the Ant Task class are shown in the following table.

Method

Description

void execute()

Called by Ant to execute the work of the task.

java.lang.String getDescription()

Returns the description of this task.

Location getLocation()

Returns a Location object specifying where the Ant task appears in the build script.

Target getOwningTarget()

Returns a Target object containing the parent of this Ant task.

Project getProject()

Returns a Project object for this task.

java.lang.String getTaskName()

Gets the name of this task.

Void init()

Called by this Ant tasks project.

void log(String msg)

Logs a message.

void log(String msg, int msgLevel)

Logs a message.

void setDescription(String desc)

Sets the description.

void setLocation(Location location)

Sets the file location of this task.

void setOwningTarget(Target target)

Sets the target of this task.

void setTaskName(String name)

Sets the name of this task

As you've probably already seen in your Ant experience to this point, there are times when the Ant app will encounter an error in the build and halt the process. We can do the same things using the BuildException exception. Here is a more fully defined class:

package com.company.ant;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.BuildException;
public class NewTask extends org.apache.tools.ant.Task{
 public void execute() throws BuildException {
 try {
 // something
 } catch (Exception e) {
 throw new BuildException(e)
 }
}


If there are any issues with the task, the BuildException exception is thrown and Ant terminates the build. This is all of the code that we need to use the use the new task. Here's an example build script:

<taskdef classname="com.company.ant.NewTask"
classpath="${newtask.dir}"
/>
<NewTask>
</NewTask>


Of course, the task won't do anything, but Ant will do the necessary work of launching the task.


JaVa
   
Comments