Showing posts with label Ant. Show all posts
Showing posts with label Ant. Show all posts

Thursday, November 29, 2007

Custom Condition in ANT

Here is an example of custom ant task.

The custom condition validates the current execution time with the time interval specified.


package com.package.ant.customTask;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.taskdefs.condition.Condition;
import org.joda.time.DateTime;
import org.joda.time.MutableDateTime;

/**
* This class checks whether the current time lies between the specified time
* range.
*
* @author Srikanth NT
*
*/
public class BetweenTimeRangeCondition implements Condition {
private String startTimePeriod = "00:01";
private String endTimePeriod = "06:30";

/**
* @see org.apache.tools.ant.Task#execute()
*/
public boolean eval() throws BuildException {
DateTime startsAt = getValidTime(startTimePeriod);
DateTime endsAt = getValidTime(endTimePeriod);

if (startsAt.isAfter(endsAt)) {
throw new BuildException("Start time period cannot be greater than End time period.");
}

return (startsAt.isBeforeNow() && endsAt.isAfterNow());
}

/**
* Validates the given time.
* @param timePeriod
* @return
* @throws BuildException
*/
private DateTime getValidTime(String timePeriod) throws BuildException {
MutableDateTime testCalendar = new MutableDateTime();
if (timePeriod.indexOf(':') != 2 && timePeriod.lastIndexOf(':') != 2) {
throw new BuildException("Time period '" + timePeriod + "' should be in the format 'hh:mm' (24 Hour).");
}

try {
testCalendar.setHourOfDay(Integer.parseInt(timePeriod.split(":")[0]));
testCalendar.setMinuteOfHour(Integer.parseInt(timePeriod.split(":")[1]));
testCalendar.setSecondOfMinute(0);
} catch (Exception e) {
throw new BuildException("Time period '" + timePeriod + "' should be in the format 'hh:mm' (24 Hour).");
}
return testCalendar.toDateTime();
}

/**
* @param startTimePeriod
*/
public void setStartTimePeriod(String startTimePeriod) {
this.startTimePeriod = startTimePeriod;
}

/**
* @param endTimePeriod
*/
public void setEndTimePeriod(String endTimePeriod) {
this.endTimePeriod = endTimePeriod;
}

}


And in the build.xml include the following lines.

<typedef name="betweentime" classname="com.package.ant.customTask.BetweenTimeRangeCondition" classpath="BetweenTimeRangeCondition.class" />

<fail message="Failing the build.">
<condition>
<not>
<betweentime startTimePeriod="00:01" endTimePeriod="06:30" />
</not>
</condition>
</fail>

Wednesday, November 28, 2007

Today I had a chance to create a custom task in ant.
I created a new class extending Task and had few instance variables to suit my business needs. Then I overridden the execute method to validate a condition and based on the output, a property in build.xml was set to either true or false. Tommorrow I will post the sample code!

I also worked on Apache redirection using regular expression rules. It worked very well. Hopefuly I would post the procedure tommorrow.

Bye for now....