Wednesday, July 14, 2010

Using Apache Ant as template engine while building an Application


Target audience: Beginners
There will be situations where we may have more than one properties files having same values for keys. For Example, there can be different properties files but have the same value for server URL or JNDI Provider URL. These values will vary depends on the environment we deploy the Application. For Example, Server URL will be http://172.12.34.5:8080/myapp in UAT (User Acceptance Testing) environment and it will be http://201.12.34.6:80/myapp in production. We have to change all the places in all properties file whenever we deploy the application. It is Ok, if it’s only in one or two places. But what if there are several places to be changed and lot of values like this Server URL. It’ll be a headache.

What can be done?
What we can do is, we can use keys for all the configuration values and replace all the keys with the actual values when the application is built.

Let me explain, we can use a key for Server URL and this key will be used in all properties file. Where ever the Server URL is used, this key will be used instead. Ok, Assume that now we are going to use a key myapp.config.serverurl in all the places where Server URL is used. And we are going to replace this key with the actual value when we build the application. The idea is to replace all the actual values while building. We can keep the actual values in a configuration file with key value pair.

It sounds better, and how can we do this?
We can do this with Apache Ant. As you all know, Ant is a Java-based build tool widely used for building java projects. We can make use of replace task and do out work.Suppose, My application has properties file called myapp.properties, then I’ll make a myapp.properties.template file and myapp.config files. The myapp.properties.template file will have all configuration values replace with keys and the myapp.config will have entries for those keys and values. At the build time the Ant build system that I am going to create will generate the final file myapp.properties which will be used for deployment

I keep all files myapp.properties.template, myapp.config and build.xml in one folder and myapp.properties file also will be generated in the same folder

The myapp.properties.template
serverUrl=myapp.config.server.url

The myapp.config
myapp.config.server.url=http://localhost:8080/myapp


Ant build file























replacefilterfile="${project.conf}/myapp.config"
includes="*.properties" />


Once you run the ant task, the myapp.properties file will be generated. The generated file will look like the following
serverUrl=http://localhost:8080/myapp

No comments:

Post a Comment