/**
* Copyright (c) 2010 Perforce Software. All rights reserved.
*/
package com.perforce.maven.scm.provider;
import java.io.InputStream;
import java.net.URL;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.Manifest;
/**
* Prints information from the JAR file's manifest.
*/
public class Metadata {
/**
* Public main method, used solely for allowing customers to print version
* and other metadata information from the enclosing JAR file's manifest.
* This information is printed to stdout; errors are printed to stderr.
*
* @param args
* not used.
*/
public static void main(String[] args) {
try {
Manifest manifest = getManifest();
Attributes attr = manifest.getMainAttributes();
System.out.println(attr.getValue(Name.IMPLEMENTATION_TITLE));
StringBuilder version = new StringBuilder(
attr.getValue(Name.IMPLEMENTATION_VERSION));
//String changelist = attr.getValue("Build-Changelist");
//if (changelist != null) {
// version.append('/').append(changelist);
//}
//String type = attr.getValue("Build-Type");
//if (type != null) {
// version.append('/').append(type);
//}
System.out.println(version);
} catch (Exception exception) {
System.err.println(exception.getLocalizedMessage());
}
}
/**
* Get the JAR Manifest associated with this class instance, if it exists.
* The interpretation of the attributes in this manifest is not defined here
* and will depend on how the jar was built; for a full list of normal
* Perforce release build attributes, contact support, but in general, most
* of the normal Maven build attributes will probably exist, as will
* Name.IMPLEMENTATION_TITLE and Name.IMPLEMENTATION_VERSION (but this is
* not guaranteed).
*
* @return non-null Manifest object if it exists and is retrievable.
* @throws Exception
* if the manifest can't be found or retrieved for any reason.
*/
public static Manifest getManifest() throws Exception {
String className = Metadata.class.getSimpleName() + ".class";
URL classURL = Metadata.class.getResource(className);
if (classURL == null) {
throw new Exception("Error retrieving class as resource: "
+ className);
}
String classPath = classURL.toString();
if (!classPath.startsWith("jar")) {
throw new Exception("Not running from jar file: " + classPath);
}
int separator = classPath.lastIndexOf('!');
if (separator != -1 && separator + 1 >= classPath.length()) {
throw new Exception("Invalid jar file class path: " + classPath);
}
String manifestPath = classPath.substring(0, separator + 1)
+ "/META-INF/MANIFEST.MF";
InputStream inStream = null;
try {
inStream = new URL(manifestPath).openStream();
return new Manifest(inStream);
} finally {
if (inStream != null) {
inStream.close();
}
}
}
}