In javascript running from Ant, how can you get an

2019-02-09 07:41发布

问题:

I'm defining a macrodef in Ant, and using javascript to do the work. In this case I'm validating a timezone.

<macrodef name="validateTimeZone">
    <attribute name="zone" />
    <sequential>
        <echo>result: ${envTZResult}</echo>
        <echo>  validating timezone: @{zone}</echo>
        <script language="javascript"><![CDATA[
            importClass(java.util.TimeZone);
            importClass(java.util.Arrays);
            var tz = project.getProperty("zone");
            println("    got attribute: " + tz);
            var result = Arrays.asList(TimeZone.getAvailableIDs()).contains(tz); //testing if timezone is known
            project.setProperty("zoneIsValid", result);
        ]]> 
        </script>
    </sequential>
</macrodef>

The problem is project.getProperty() doesn't retrieve values of passed attributes. Does somebody know how you could get the value of the attribute from within the javascript?

回答1:

Turns out I was using the wrong type of tag. For using scripting to define an ant task, I should have used scriptdef and not macrodef. With scriptdef there are predefined objects to access the attributes and nested elements in your task.

This works for accessing attributes from javascript in Ant:

<scriptdef name="validateTimeZone" language="javascript">
    <attribute name="zone" />
    <![CDATA[
        importClass(java.util.TimeZone);
        importClass(java.util.Arrays);
        var tz = attributes.get("zone"); //get attribute defined for scriptdef
        println("    got attribute: " + tz);
        var result = Arrays.asList(TimeZone.getAvailableIDs()).contains(tz); //testing if timezone is known
        project.setProperty("zoneIsValid", result);
    ]]> 
</scriptdef>


回答2:

Best is to create a property with attribute as value, i.e.

<macrodef name="validateTimeZone">
    <attribute name="zone" />
    <sequential>
        <echo>result: ${envTZResult}</echo>
        <echo>  validating timezone: @{zone}</echo>
        <!-- edit use local with ant 1.8.x -->
        <local name="zone"/>
        <property name="zone" value="@{zone}"/>
        <script language="javascript"><![CDATA[
            importClass(java.util.TimeZone);
            importClass(java.util.Arrays);
            var tz = project.getProperty("zone");
            println("    got attribute: " + tz);
            var result = Arrays.asList(TimeZone.getAvailableIDs()).contains(tz); //testing if timezone is known
            project.setProperty("zoneIsValid", result);
        ]]> 
        </script>
    </sequential>
</macrodef>