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="<properties>.*</properties>"
replace="${test_connection_properties}"
byline="false"
flags="gs"
/>
The code in detail:
- loadfile reads the file with the new connection settings into a property. That's needed because I haven't found a way to tell replaceregexp to use a whole file as replace token.
- replaceregexp is an optional task. Since jdk 1.4 there is no need to install additional libraries as the jdk has a regexp library.
- The file which is operated on is in the build dir. Don't take the file from the source directory.
- < and > need to be masked as < and > because as an ant file is xml and xml doesn't allow this characters out of CDDATA in attributes. But despite this it will recognize <properties> and </properties>
- .* is java regexp and means any character zero or more times.
- The value of flags are from the net. I have to admit that I don't know what they are triggering but without them it won't work. From the tool sed I know that g is for globally and s for substitution but I doubt that they have the same meaning here.