All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.sparta.springwebutils.ManifestUtils Maven / Gradle / Ivy

package net.sf.sparta.springwebutils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.jar.Manifest;

import javax.servlet.ServletContext;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/** 
 * @author Carlos Eduardo Endler Genz – Sparta Java Team 
 * 
 * History: 
 *    Apr 9, 2014 - Carlos Eduardo Endler Genz
 *  
 */ 
public class ManifestUtils {
	private static final Logger LOGGER = LoggerFactory.getLogger(ManifestUtils.class);
	
	private static final String MANIFEST = "META-INF/MANIFEST.MF";
	
	@Autowired
	private ServletContext servletContext;
	
	/**
	 * Reads the manifest entries for this application. Returns empty if anything fails.
	 *
	 * @return
	 */
	public Map getManifestAttributes() {
		Map manifestAttributes = new HashMap();
		
		FileInputStream fis = null;
		try {
			if (servletContext != null) {
				final String appServerHome = servletContext.getRealPath("/");
				final File manifestFile = new File(appServerHome, MANIFEST);
				
				fis = new FileInputStream(manifestFile);
				Manifest mf = new Manifest(fis);
				manifestAttributes = mf.getMainAttributes();
			}

		} catch (Exception e) {
			LOGGER.warn("Unable to read the manifest file from the servlet context. Trying to load from classpath.");
			LOGGER.debug("Unable to read the manifest file", e);
			
			manifestAttributes = getClassPathManifestAttributes();
		} finally {
			IOUtils.closeQuietly(fis);
		}
		return manifestAttributes;
	}
	
	/**
	 * Reads the manifest entries for this application (classpath). Returns empty if anything fails.
	 *
	 * @return
	 */
	private Map getClassPathManifestAttributes() {
		Map manifestAttributes = new HashMap();
		try {
		  Manifest manifest = new Manifest(getClass().getClassLoader().getResourceAsStream(MANIFEST));
		  manifestAttributes = manifest.getMainAttributes();
		} catch (IOException e) {
			LOGGER.warn("Unable to read the manifest from the classpath");
			LOGGER.debug("Unable to read the manifest from the classpath", e);
		}
		return manifestAttributes;
	}
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy