jLuger.de - Replace connection properties in persistence.xml with ant

When developing a JPA based application you may want to have different database settings for unit testing and production. The easy way is to have two persistence.xml files and let the ant task select which one to copy to your build artifacts. This approach gets very painful in the long run. You always have to remember to make changes in both files. And when you require a third connection you need to maintain three files. Wouldn't it be better when there is one persistence.xml and the different parts are in templates? Well I think so and the good news is that you can do this completely with ant.

It's pretty easy. You just load the template file in a property and then use a replace task to replace the connection settings. See the following code:
<loadfile property="test_connection_properties" srcFile="${template_dir}/test_connection.template"/>
<replaceregexp file="${build_dir}/META_INF/persistence.xml"
    match="&lt;properties&gt;.*&lt;/properties&gt;"
    replace="${test_connection_properties}"
    byline="false"
    flags="gs"
/>

The code in detail: