Populate Properties Resource File in Gradle

Since Gradle is built in Groovy and not XML like Ant or Maven, you can do a lot of things in the build process very easily. Here's how I'm using Gradle to update the version, build date and Wicket Deployment Type in a properties resource file as part of my WAR build.

Here's the property file we're starting with. Each of the properties we're updating is in the {$text-to-be-replaced} format, though it can be anything or nothing.

For kicks, here are the properties as shown on the web page during the Gradle build.

Okay, let's look at the code. The Gradle task will first copy the config.properties file from its location in /resources to the WAR Temporary Directory. The WAR temp directory is defined in Gradle as /build/tmp/war.

One of the nice features of Gradle is that it includes an instance of groovy.ant.AntBuilder as part of the build. That means that anything that can be done with Ant can be handled inside a Gradle build. We're using AntBuilder copy and properties functions, then Gradle's WAR from() method to copy from the temporary location to the WAR.

tasks.withType(War).all { War war ->
    war.doFirst {
        String warType = war.extension
        if (war.classifier) warType = war.classifier
        String fileName = "config.properties"
        ant.copy(file: "${project.rootDir}/src/main/resources/${fileName}",
                tofile: "${war.temporaryDir}/${fileName}")

        ant.propertyfile(file: "${war.temporaryDir}/${fileName}") {
            if (project.hasProperty('deploy')) {
                entry(key: "configuration.type", value: "DEPLOYMENT")
            } else {
                entry(key: "configuration.type", value: "DEVELOPMENT")
            }
            entry(key: "version", value: project.version)
            entry(key: "build.date", value: new Date())
        }

        String intoPath = "${warType}"
        war.from(war.temporaryDir) {
            include fileName
            intoPath = "WEB-INF/classes"
            into(intoPath)
        }

    }
}

The version property is set in the root gradle.properties file. Gradle.properties is automatically read by the build.gradle file, so it's very cool how we're setting the application version in a single location with that value populated to multiple locations with Gradle.

Setting the Wicket Configuration Type property is done at the command line.

$ gradle -Pdeploy war

Easy! For normal builds in development a simple $ gradle war does the job.

So you know it works, here is our WAR post-build config.properties file in development mode.

Source Code Notes for this Post

Topics discussed in this post can be found in the v0.0.1 Branch of my Spring-Wicket-Bootstrap repository on GitHub.

More Like This Post