Monday, May 23, 2011

Is it possible to alter Ant properties after they've been initialized?

I was working on an Ant script (yes, I am using maven2 too for other projects, but in this case I just want to use plain vanilla Ant script) and along the way came upon this need to change an Ant property after it has been initialized.


Did a bit of googling and came upon this forum discussion. Not a very bright and encouraging note at the end - essence being "No; property values, once set, cannot be changed. Attempts to do so will fail silently."


Well, guess what? I am not the kind who give up that easily.


Here are the steps (for contribution back to the community) to change an Ant property after it have been initiatlized. Snaplets of code for illustration purpose only.


Before we dive into codes, just some overview of the approach. I am using javascript within the Ant script to accomplish this. So, you will need to download dependency libraries. The one that is really needed is js.jar from from Mozilla and don't forget to grab also the bsf jar too. For more information, you should check the Ant user manual here (scroll to the table containing js.jar and follow the link). For my side, I have both bsf-all-3.1.jar and js-14.jar within the lib directory of ant. I am running Ant version 1.7.1 for this example.


OK, now that we have covered the basics, here goes:



<project name="myProject" default="myTarget">
<property name="message" value="Hello, me!"/>
<target name="myTarget">
    <echo message="${message}"/>
    <script language = "javascript"><![CDATA[
           myProject.setProperty("message", "Hello world!");
     ]]></script>
     <echo message="${message}"/>
</target>
</project>


The portion of code that changed the property value is highlighted. The output should be similar to this:


Buildfile: build.xml


myTarget:
          [echo] Hello, me!
          [echo] Hello world!


BUILD SUCCESSFUL
Total time: 0 seconds


Never give up so easily in life.... that's the lesson. Have fun!

No comments: