Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Maven 2: How to package current project version in a WAR file?

I am using Maven 2 to build my Java project and I am looking for a way to present the current version number of the pom.xml to the user (using a Servlet or JSP for example).

As far as I can see, the best way would be that Maven packages the version number as a text file into the WAR. This allows me to read the version from that file and present it the way I want.

Does anyone know of a plugin that can do something like that for me? Maybe the WAR plugin can be configured to do so? Or maybe using some other approach all together?

like image 630
Tom van Zummeren Avatar asked Dec 15 '09 09:12

Tom van Zummeren


1 Answers

I solved this problem a little differently, as I had a desire to display version, svn revision, etc. on the index page of a service. I used the buildnumber-maven-plugin and the war-plugin to store the values in the manifest.

pom.xml snippet:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>buildnumber-maven-plugin</artifactId>
    <executions>
      <execution>
        <phase>validate</phase>
        <goals>
          <goal>create</goal>
        </goals>
      </execution>
    </executions>
  </plugin>
  <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
      <archive>
        <manifest>
          <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
        </manifest>
        <manifestEntries>
          <Implementation-Environment>${env}</Implementation-Environment>
          <Implementation-Build>${buildNumber}</Implementation-Build>
        </manifestEntries>
      </archive>
    </configuration>
    <executions>
      <execution>
        <phase>package</phase>
        <goals>
          <goal>war</goal>
        </goals>
        <configuration>
          <classifier>${env}</classifier>
        </configuration>
      </execution>
    </executions>
  </plugin>

The JSP to pull them out was fairly trivial:

<%@ page language="java" pageEncoding="UTF-8"%>
<% 
java.util.jar.Manifest manifest = new java.util.jar.Manifest();
manifest.read(pageContext.getServletContext().getResourceAsStream("/META-INF/MANIFEST.MF"));
java.util.jar.Attributes attributes = manifest.getMainAttributes();

%>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Health Check</title>
  </head>
  <body>
    <h1>Health Check</h1>
    <h2>Version: <%=attributes.getValue("Implementation-Version")%>-<%=attributes.getValue("Implementation-Environment")%></h2>
    <h2>SVN Revision: <%=attributes.getValue("Implementation-Build")%></h2>
  </body>
</html>

This displayed something like:

Version: 2.0.1-SNAPSHOT-QA

SVN Revision: 932
like image 194
Mike Cornell Avatar answered Nov 15 '22 08:11

Mike Cornell