Thursday, October 20, 2011

Ant replaceregexp example against the requirement to customize log4j e-mails

Check new series of the articles. Review and user experience on test management systems. Functionality and usability.
-------------------

Requirement:
- to customize log4j.xml so that all the e-mails are changed to some custom one
- facility: ANT tool

However there was lack of examples of replaceregexp ant task on the ant official page. So here is one extra example that addresses the following functional requirements
- replace all the entities like
old@yourdomain.com
so that old is replaced with new
- replace all the entities like
so that old is replaced with new

The solution is below:

  <target name="customize">
   <replaceregexp byline="true">
    <fileset dir="${BUILD_ROOT}" id="build_root_dir">
     <include name="**/log4j.xml" />
    </fileset>
    <regexp pattern="(.*?&gt;).+?(@yourdomain\.com.*)"/>
    <substitution expression="\1${reciever-alias-to-substitute}\2" />
   </replaceregexp>
   <replaceregexp byline="true">
    <fileset dir="${BUILD_ROOT}" id="build_root_dir">
     <include name="**/log4j.xml" />
    </fileset>
    <regexp pattern="(.*?value\=&quot;).+?(@yourdomain\.com&quot;.*)"/>
    <substitution expression="\1${reciever-alias-to-substitute}\2" />
   </replaceregexp>
  </target>

As you can see here it is used two replaceregexp tasks. It is done because unfortunately replaceregexp does not support several patterns inside, so once we need to process the files with two different patterns we should use two different replaceregexp tasks.

The one more thing it is useful to know is that you should use backslash symbol to specify which group (for the set located by your regular expression) you are going to use. In the example above I use two groups. The whole part of the string before original e-mail and the one after that. Then I'm saying to Ant that I'd like to preserve those strings \1 and \2 but change only the string between them.

Thanks

2 comments:

  1. You saved me with that last comment. "Then I'm saying to Ant that I'd like to preserve those strings \1 and \2 but change only the string between them" I had no idea you can do this and there is barely any documentation on what replaceregex does. Sometimes it complains about $ not being escaped other times when you escape it, it complains too.

    ReplyDelete