tags:

views:

31

answers:

1

Using only native ANT tasks, how can I create a custom ANT task to do the following:

  • Calculate the the number of days since January 1, 2000 local time and store it in a property.
  • Calculate the number of seconds since midnight local time, divided by 2 and store it in a property.

The above property values will then be appended to others and written to a file.

+1  A: 

ANT is not a general purpose programming language, so you need to write a custom task or alternatively use something like the groovy plugin

The following example demonstrates how a groovy task using the Joda Time library can set the properties as you've specified.

<taskdef name="groovy" classname="org.codehaus.groovy.ant.Groovy" classpathref="build.path"/>
<groovy>
    import org.joda.time.*

    def now      = new DateTime()
    def midnight = new DateMidnight()
    def year2000 = new DateTime(2000,1,1,0,0,0,0)

    properties["year2000.days"] = Days.daysBetween(year2000, now).days
    properties["midnight.seconds"] = Seconds.secondsBetween(midnight, now).seconds
    properties["midnight.seconds.halved"] = Seconds.secondsBetween(midnight, now).dividedBy(2).seconds
</groovy>

I can't recommend Joda Time highly enough, standard Date and Time manipulation in Java just sucks!

Additional notes

The groovy task above will require the following jars on your classpath:

  • groovy-all-1.7.4.jar
  • joda-time-1.6.1.jar

I'd recommend using the ivy plugin to manage these by adding a "resolve" target that downloads the jars and sets the classpath automatically:

<target name="resolve">
    <ivy:resolve/>
    <ivy:cachepath pathid="build.path"/>
</target>

The following is the ivy.xml that lists the dependencies to be downloaded:

<ivy-module version="2.0">
    <info organisation="org.myspotontheweb" module="demo"/>
    <dependencies>
        <dependency org="org.codehaus.groovy" name="groovy-all" rev="1.7.4" conf="default"/>
        <dependency org="joda-time" name="joda-time" rev="1.6.1" conf="default"/>
    </dependencies>
</ivy-module>
Mark O'Connor