Andrew
Andrew

Reputation: 125

How can I change property values in a file using Ant?

Example input:

SERVER_NAME=server1
PROFILE_NAME=profile1
...

Example output:

SERVER_NAME=server3
PROFILE_NAME=profile3
...

This file will use in applicationContext.xml. I've tried

<copy file="${web.dir}/jexamples.css_tpl"
         tofile="${web.dir}/jexamples.css" >
    <filterchain>
       <replacetokens>
            <token key="SERVER_NAME" value="server2"/>
            <token key="PROFILE_NAME" value="profi"/>

        </replacetokens>
    </filterchain>
</copy>

but it doesn't work.

Upvotes: 10

Views: 21887

Answers (3)

<propertyfile file="mypropfile.properties">
    <entry key="Key-1" value="Val-1"/>
</propertyfile>

This works seamlessly as long as you have XMLtask defined in your build.xml file. example#

<taskdef name="xmltask" classname="com.oopsconsultancy.xmltask.ant.XmlTask">
        <classpath>
            <fileset dir="C:/lib">
                <include name="xmltask*.jar"/>
                <include name="xml-apis*.jar"/>
                <include name="xalan*.jar"/>
                <include name="xerces*.jar"/>
            </fileset>
        </classpath>
    </taskdef>
    <taskdef resource="net/sf/antcontrib/antlib.xml">
        <classpath>
            <pathelement location="C:/lib/ant-contrib.jar"/>
        </classpath>
    </taskdef>

Upvotes: 0

Jakub
Jakub

Reputation: 2384

Cleaner solution is using "propertyfile" ant task - see http://ant.apache.org/manual/Tasks/propertyfile.html

<copy file="${web.dir}/jexamples.css_tpl"
     tofile="${web.dir}/jexamples.css" />
<propertyfile file="${web.dir}/jexamples.css">
    <entry key="SERVER_NAME" value="server2"/>
</propertyfile>

Upvotes: 9

Peter Lang
Peter Lang

Reputation: 55524

Your filterchain is ok, but your source file should look like this:

SERVER_NAME=@SERVER_NAME@
PROFILE_NAME=@PROFILE_NAME@

This code (as provided by you)

<copy file="${web.dir}/jexamples.css_tpl"
         tofile="${web.dir}/jexamples.css" >
    <filterchain>
       <replacetokens>
            <token key="SERVER_NAME" value="server2"/>
            <token key="PROFILE_NAME" value="profi"/>
        </replacetokens>
    </filterchain>
</copy>

replaces the tokens and gives you

SERVER_NAME=server2
PROFILE_NAME=profi

If you want to keep your original file as you have it now, one way would be to use replaceregex:

<filterchain>
  <tokenfilter>
    <replaceregex pattern="^[ \t]*SERVER_NAME[ \t]*=.*$"
                  replace="SERVER_NAME=server2"/>
    <replaceregex pattern="^[ \t]*PROFILE_NAME[ \t]*=.*$"
                  replace="PROFILE_NAME=profi"/>
  </tokenfilter>
</filterchain>

This would replace every line starting with SERVER_NAME= by SERVER_NAME=server2 (same for PROFILE_NAME=). This will return get you the output you described.

[ \t]* is to ignore whitespace.

Upvotes: 15

Related Questions