Skip to content

Instantly share code, notes, and snippets.

@basinilya
Created February 6, 2018 11:29
Show Gist options
  • Select an option

  • Save basinilya/339eed893d940bfafcbb41a41f259db9 to your computer and use it in GitHub Desktop.

Select an option

Save basinilya/339eed893d940bfafcbb41a41f259db9 to your computer and use it in GitHub Desktop.
manifestutil
package org.foo.manifestutil;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.jar.Manifest;
import org.apache.commons.io.IOUtils;
// https://stackoverflow.com/q/1272648/447503
public final class ManifestUtil {
private ManifestUtil() {}
public static Manifest getManifest(final Class<?> clazz) throws IOException {
final String resource = clazz.getName().replace('.', '/') + ".class";
final String fullPath = clazz.getClassLoader().getResource(resource).toString();
String archivePath = fullPath.substring(0, fullPath.length() - resource.length() - 1);
if (archivePath.endsWith(WEB_INF_CLASSES)) {
// Required for wars
archivePath = archivePath.substring(0, archivePath.length() - WEB_INF_CLASSES.length());
}
final String manifestPath = archivePath + "/META-INF/MANIFEST.MF";
InputStream in = null;
try {
in = new URL(manifestPath).openStream();
return new Manifest(in);
} catch (final FileNotFoundException e) {
return null;
} finally {
IOUtils.closeQuietly(in);
}
}
private static final String WEB_INF_CLASSES = "/WEB-INF/classes";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment