08 August 2012

Maven Build Info for Web Applications

Problem

* You want to include build info like build number, revision number etc. as a web resource in your web applications.
* You have a multi-module Maven project with more than one WAR module and a number of JAR modules.
* You want to minimize copy-and-paste configuration in your POMs.
* The mechanism should not depend on a CI server.

Solution

This can be achieved using the Build Number Maven Plugin and the overlay feature of the Maven WAR plugin.

buildinfo Module

Create a new Maven module myproject-buildinfo with war packaging containing nothing but a pom.xml and a resource src/main/webapp/version.txt with the following contents:

{
  "release"  : "${project.version}",
  "date"     : "${build.date}",
  "revision" : "${buildNumber}",
  "branch"   : "${scmBranch}"
}

The properties in this file shall be interpolated by Maven resource filtering. To make this work, add these definitions to myproject-buildinfo/pom.xml:


<properties>
    <maven.build.timestamp.format>yyyy-MM-dd HH:mm</maven.build.timestamp.format>
    <build.date>${maven.build.timestamp}</build.date>
  </properties>

  <build>
    <plugins>
      
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>buildnumber-maven-plugin</artifactId>
      </plugin>

      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <configuration>
          <webResources>
            <resource>
              <directory>src/main/webapp</directory>
              <filtering>true</filtering>
            </resource>            
          </webResources>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </plugin>
      
    </plugins>
  </build>

The Build Number Plugin sets the buildNumber and scmBranch properties after querying your SCM system (Subversion or Git).

Web Application Configuration


To include the interpolated build info resource in your web applications, simply add your build info WAR as a dependency to each of your WAR projects:

<dependency>
  <groupId>${project.groupId}</groupId>
  <artifactId>myproject-buildinfo</artifactId>
  <version>${project.version}</version>
  <type>war</type>
</dependency>

No comments: