Ant task generating random number

I created an ant task lately which generates random number and I thought that it might be useful for someone. The ant task will accept three parameters:

  • min
  • max
  • name of ant property to assign value to

Our class will extend org.apache.tools.ant.Task and the only thing which we have to do is really to override the execute method and to add setters for parameters. We can return value to ant environment using org.apache.tools.ant.Project which will give us a way of setting a property using its name. The code is as follows:


package your.package;

import java.util.Random;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;

public class RandomTask extends Task {
    private String min;
    private String max;
    private String property;
    private Random random = new Random(System.currentTimeMillis());

    @Override
    public void execute() throws BuildException {
        if (min == null || min.equals(""))
            throw new BuildException("Min property not specified");

        if (max == null || max.equals(""))
            throw new BuildException("Max property not specified");

        int minInt = Integer.parseInt(min);
        int maxInt = Integer.parseInt(max);

        if (minInt > maxInt)
            throw new BuildException("Min is bigger than max");

        int randomInt = calculateRandom(minInt, maxInt);

        getProject().setNewProperty(property, String.valueOf(randomInt));
    }

    protected int calculateRandom(int minInt, int maxInt) {
        return minInt + random.nextInt(maxInt - minInt + 1);
    }

    public void setMin(String min) {
        this.min = min;
    }

    public void setMax(String max) {
        this.max = max;
    }

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

After compiling and building a jar we should copy that jat to ANT_HOME/lib and define the new task in our build.xml, lets call it “random”:

    <taskdef name="random" classname="your.package.RandomTask"></taskdef>

Let’s try if it works. We will generate a rundom integer from the range <4;10>, assign to a property and print it to console:

    <target name="testRandom">
        <random min="4" max="10" property="randomValue"></random>
        <echo>Random:${randomValue}</echo>
    </target>

Popularity: 30% [?]

Leave a Comment

Close
E-mail It