How to display project version in Java

H

Sometimes, it’s useful to display the project version in your application. That version can be found in the MANIFEST.MF file. It’s located in every JAR or WAR file in the META-INF folder.

example.war -> META-INF -> MANIFEST.MF

If you open that file, you can see some project information. We need to get the Implementation-Version. Here is an example of a MANIFEST.MF file

Manifest-Version: 1.0
Archiver-Version: Plexus Archiver
Created-By: Apache Maven
Built-By: hudson
Build-Jdk: 1.6.0_27
Hudson-Build-Number: 667
Hudson-Project: example
Hudson-Version: 1.400
Implementation-Version: 2.3.1-SNAPSHOT

To get that version I’ll give you a class ManifestInfo.java. The ‘getVersion’ method gives you that implementation-version. Don’t forget to init the class.

package com.laurenthinoul.webapp;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.ServletContextAware;

public class ManifestInfo implements ServletContextAware {

    private static final String VERSION_ROW = "Implementation-Version";
    private static final String MANIFEST_NAME = "/META-INF/MANIFEST.MF";
    private static final Properties MANIFESTINFO = new Properties();
    private static ServletContext servletContext;
    private static final Logger LOGGER = LoggerFactory.getLogger(ManifestInfo.class);

    private static void setContext(ServletContext servletContext) {
        ManifestInfo.servletContext = servletContext;
    }

    public void init() {
        final String name = MANIFEST_NAME;

        try {
            ManifestInfo.MANIFESTINFO.load(servletContext.getResourceAsStream(name));
        } catch (final IOException e) {
            LOGGER.warn(e.getMessage());
        } catch (final NullPointerException e) {
            LOGGER.warn(e.getMessage());
        }

    }

    public String getVersion() {
        return (String) ManifestInfo.MANIFESTINFO.get(VERSION_ROW);
    }

    @Override
    public void setServletContext(ServletContext servletContext) {
        ManifestInfo.setContext(servletContext);
    }
}

When you use Spring, you need to add the line below:

<bean id="manifestInfo" class="com.laurenthinoul.webapp.ManifestInfo" init-method="init" />

Hope this works for you, enjoy!

1 comment

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Tag Cloud

Categories