Tag Archives: version

Read version of package from META-INF in Java JSF Bean

vers
Often you need to show the software version in JSF page.
How to make it as follows:

1. Create JSF Bean

public class PropertiesBean implements Serializable {

    private static final long serialVersionUID = 8607941655014578684L;

    private static final String METAINF_LOCATION = "META-INF/MANIFEST.MF";
    private static final String VERSION_PREFIX = "Implementation-Version: ";
    private static final Pattern VERSION_PATTERN = Pattern.compile("(\\d+\\.\\d+\\.\\d+)");
    
    public String getVersion() {
        try {
            InputStream is = null;
            Scanner scanner = null;
            try {
                is = this.getClass().getClassLoader().getResourceAsStream(METAINF_LOCATION);
                scanner = new Scanner(is);
                while (scanner.hasNext()) {
                    String line = scanner.nextLine();
                    if (line.startsWith(VERSION_PREFIX)) {
                        Matcher matcher = VERSION_PATTERN.matcher(line);
                        if (matcher.find()) {
                            String group = matcher.group();
                            return group;
                        }
                    }
                }
            } finally {
                if (scanner != null) {
                    scanner.close();
                }
                if (is != null) {
                    is.close();
                }
            }
        } catch (Exception e) {
            // TODO: log error!
        }
        return null;
    }
}

2. Register bean in faces-config.xml

    <managed-bean>
        <managed-bean-name>PropertiesBean</managed-bean-name>
        <managed-bean-class>com.someproject.presentation.PropertiesBean</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
    </managed-bean>

3. Use it on JSF page:

<h:outputText value="[v#{PropertiesBean.version}]" rendered="#{PropertiesBean.version != null}" />

Profit!

See also, http://stackoverflow.com/a/4782124