下面列出了java.util.jar.Attributes#getValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* 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.
*
* @since 2011.1
* @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());
}
}
@Test
public void basicItTest()
throws Exception
{
Assume.assumeTrue( isSvn18() );
File projDir = resources.getBasedir( "basic-it" );
MavenExecution mavenExec = maven.forProject( projDir );
MavenExecutionResult result = mavenExec.execute( "clean" );
result.assertErrorFreeLog();
File testDir = result.getBasedir();
FileUtils.copyDirectoryStructure( new File( testDir, "dotSvnDir" ), new File( testDir, ".svn" ) );
result = mavenExec.execute( "clean", "verify" );
result.assertLogText( "Storing buildNumber: 14069" );
result.assertLogText( "Storing buildScmBranch: trunk" );
File artifact = new File( testDir, "target/buildnumber-maven-plugin-basic-it-1.0-SNAPSHOT.jar" );
JarFile jarFile = new JarFile( artifact );
Attributes manifest = jarFile.getManifest().getMainAttributes();
jarFile.close();
String scmRev = manifest.getValue( "SCM-Revision" );
Assert.assertEquals( "14069", scmRev );
}
private void updateMIDletList() {
String j = jarFile.getText();
if(j != null && j.length() > 0) {
File file = new File(j);
if(file.exists() && file.isFile()) {
try {
JarFile zip = new JarFile(file);
Attributes m = zip.getManifest().getMainAttributes();
Vector v = new Vector();
for (int i = 1 ; m.getValue("MIDlet-" + i) != null ; i++) {
v.addElement(m.getValue("MIDlet-" + i));
}
midletPicker.setModel(new DefaultComboBoxModel(v));
} catch (IOException ex) {
ex.printStackTrace();
JOptionPane.showMessageDialog(this, "An IO Error occured while accessing\n" +
"the MIDlet JAR:\n" + ex.getMessage(), "IO Error", JOptionPane.ERROR_MESSAGE);
}
}
}
}
static String extractCodeName(Attributes attr, boolean[] osgi) {
String codename = attr.getValue("OpenIDE-Module");
if (codename != null) {
return codename;
}
codename = attr.getValue("Bundle-SymbolicName");
if (codename == null) {
return null;
}
codename = codename.replace('-', '_');
if (osgi != null) {
osgi[0] = true;
}
int params = codename.indexOf(';');
if (params >= 0) {
return codename.substring(0, params);
} else {
return codename;
}
}
private boolean isOSGiBundle(Path bundlePath, String bundleSymbolicName) throws IOException, CarbonToolException {
if (Files.exists(bundlePath)) {
boolean validSymbolicName, exportPackageAttributeCheck, importPackageAttributeCheck;
try (FileSystem zipFileSystem = BundleGeneratorUtils.createZipFileSystem(bundlePath, false)) {
Path manifestPath = zipFileSystem.getPath(Constants.JAR_MANIFEST_FOLDER, Constants.MANIFEST_FILE_NAME);
Manifest manifest = new Manifest(Files.newInputStream(manifestPath));
Attributes attributes = manifest.getMainAttributes();
String actualBundleSymbolicName = attributes.getValue(Constants.BUNDLE_SYMBOLIC_NAME);
validSymbolicName = ((actualBundleSymbolicName != null) && ((bundleSymbolicName != null)
&& bundleSymbolicName.equals(actualBundleSymbolicName)));
exportPackageAttributeCheck = attributes.getValue(Constants.EXPORT_PACKAGE) != null;
importPackageAttributeCheck = attributes.getValue(Constants.DYNAMIC_IMPORT_PACKAGE) != null;
}
return (validSymbolicName && exportPackageAttributeCheck && importPackageAttributeCheck);
} else {
return false;
}
}
URL[] getClassPath() throws IOException {
Manifest man = jar.getManifest();
if (man != null) {
Attributes attr = man.getMainAttributes();
if (attr != null) {
String value = attr.getValue(Name.CLASS_PATH);
if (value != null) {
return parseClassPath(csu, value);
}
}
}
return null;
}
URL[] getClassPath() throws IOException {
Manifest man = jar.getManifest();
if (man != null) {
Attributes attr = man.getMainAttributes();
if (attr != null) {
String value = attr.getValue(Name.CLASS_PATH);
if (value != null) {
return parseClassPath(csu, value);
}
}
}
return null;
}
private void getManifestAttributes() throws OpenAS2Exception {
Enumeration<?> resEnum;
URL openAS2Manifest = null;
try {
resEnum = Thread.currentThread().getContextClassLoader().getResources(JarFile.MANIFEST_NAME);
while (resEnum.hasMoreElements()) {
try {
URL url = (URL) resEnum.nextElement();
InputStream is = url.openStream();
if (is != null) {
Manifest manifest = new Manifest(is);
Attributes mainAttribs = manifest.getMainAttributes();
is.close();
String vendor = mainAttribs.getValue(MANIFEST_VENDOR_ID_ATTRIB);
if (vendor != null && VENDOR_ID.equals(vendor)) {
// We have an OpenAS2 jar at least - check the project name
String project = mainAttribs.getValue(MANIFEST_TITLE_ATTRIB);
if (project != null && PROJECT_NAME.equals(project)) {
if (openAS2Manifest != null) {
// A duplicate detected
throw new OpenAS2Exception("|Duplicate manifests detected: " + openAS2Manifest.getPath() + " ::: " + url.getPath());
}
openAS2Manifest = url;
manifestAttributes = mainAttribs;
}
}
}
} catch (Exception e) {
// Silently ignore wrong manifests on classpath?
}
}
} catch (IOException e1) {
// Silently ignore wrong manifests on classpath?
}
if (openAS2Manifest == null) {
LOGGER.warn("Failed to find a MANIFEST.MF with the desired vendor and project name.");
} else {
LOGGER.info("Using MANIFEST " + openAS2Manifest.getPath());
}
}
private boolean isSealed(String name, Manifest man) {
Attributes attr = SharedSecrets.javaUtilJarAccess()
.getTrustedAttributes(man, name.replace('.', '/').concat("/"));
String sealed = null;
if (attr != null) {
sealed = attr.getValue(Name.SEALED);
}
if (sealed == null) {
if ((attr = man.getMainAttributes()) != null) {
sealed = attr.getValue(Name.SEALED);
}
}
return "true".equalsIgnoreCase(sealed);
}
/**
* Returns the a manifest attribute from the JAR file containing the
* specified class.
*/
public static String getManifestAttribute(Class klass, String attributeName) {
Attributes manifestInfo = getManifestAttributes(klass);
String version = manifestInfo.getValue(attributeName);
if (version != null) {
return version;
} else {
return "N/A";
}
}
static String getMainClassFromJar(String jarname) {
String mainValue = null;
try (JarFile jarFile = new JarFile(jarname)) {
Manifest manifest = jarFile.getManifest();
if (manifest == null) {
abort(null, "java.launcher.jar.error2", jarname);
}
Attributes mainAttrs = manifest.getMainAttributes();
if (mainAttrs == null) {
abort(null, "java.launcher.jar.error3", jarname);
}
mainValue = mainAttrs.getValue(MAIN_CLASS);
if (mainValue == null) {
abort(null, "java.launcher.jar.error3", jarname);
}
/*
* Hand off to FXHelper if it detects a JavaFX application
* This must be done after ensuring a Main-Class entry
* exists to enforce compliance with the jar specification
*/
if (mainAttrs.containsKey(
new Attributes.Name(FXHelper.JAVAFX_APPLICATION_MARKER))) {
return FXHelper.class.getName();
}
return mainValue.trim();
} catch (IOException ioe) {
abort(ioe, "java.launcher.jar.error1", jarname);
}
return null;
}
/**
* Changes the (Implementation-Vendor,Implementation-Title) pairs
* by the corresponding (Implementation-Vendor-Id, Implementation-Title) pair
* when the Implementation-Vendor-Id is available.
* Targets the fact that, by default, project.groupId is assigned to Implementation-Vendor-Id
* and project.organization.name is assigned to Implementation-Vendor on the META-INF/MANIFEST.MF file.
*/
private void findVendorIdForGroups() {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
//Checks every META-INF/MANIFEST.MF file found in the classpath
Enumeration<URL> urls = loader.getResources("META-INF/MANIFEST.MF");
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
Manifest manifest = new Manifest(url.openStream());
Attributes attributes = manifest.getMainAttributes();
String vendor = attributes.getValue("Implementation-Vendor");
String vendorId = attributes.getValue("Implementation-Vendor-Id");
String id = attributes.getValue("Implementation-Title");
if (StringUtil.isNullOrEmpty(vendor) || StringUtil.isNullOrEmpty(vendorId) || StringUtil.isNullOrEmpty(id)) {
continue;
}
GroupIdPair query = new GroupIdPair(vendor, id);
if (groups.contains(query)) {
groups.remove(query);
groups.add(new GroupIdPair(vendorId, id));
}
}
} catch (IOException exc) {
Log.getLogger().fine("An exception was thrown while looking for manifest files. Message: " + exc.getMessage());
}
}
public static Collection<File> readClasspathManifest(File file) {
try (FileInputStream fis = new FileInputStream(file);
JarInputStream jarStream = new JarInputStream(fis);) {
Manifest mf = jarStream.getManifest();
Attributes att = mf.getMainAttributes();
String cp = att.getValue(Attributes.Name.CLASS_PATH);
String[] parts = cp.split("file:");
return Arrays.stream(parts)
.filter(part -> !part.isEmpty())
.map(part -> new File(part.trim()))
.collect(Collectors.toList());
} catch (IOException ex) {
throw new RuntimeException("Could not read classpath jar manifest", ex);
}
}
public List<File> getJarClassPath(File file) throws IOException {
String parent = file.getParent();
JarFile jarFile = new JarFile(file);
try {
Manifest man = jarFile.getManifest();
if (man == null)
return Collections.emptyList();
Attributes attr = man.getMainAttributes();
if (attr == null)
return Collections.emptyList();
String path = attr.getValue(Attributes.Name.CLASS_PATH);
if (path == null)
return Collections.emptyList();
List<File> list = new ArrayList<File>();
for (StringTokenizer st = new StringTokenizer(path); st.hasMoreTokens(); ) {
String elt = st.nextToken();
File f = (parent == null ? new File(elt) : new File(parent, elt));
list.add(f);
}
return list;
} finally {
jarFile.close();
}
}
/**
* Defines a new package by name in this ClassLoader. The attributes
* contained in the specified Manifest will be used to obtain package
* version and sealing information. For sealed packages, the additional
* URL specifies the code source URL from which the package was loaded.
*
* @param name the package name
* @param man the Manifest containing package version and sealing
* information
* @param url the code source url for the package, or null if none
* @exception IllegalArgumentException if the package name duplicates
* an existing package either in this class loader or one
* of its ancestors
* @return the newly defined Package object
*/
protected Package definePackage(String name, Manifest man, URL url)
throws IllegalArgumentException
{
String specTitle = null, specVersion = null, specVendor = null;
String implTitle = null, implVersion = null, implVendor = null;
String sealed = null;
URL sealBase = null;
Attributes attr = SharedSecrets.javaUtilJarAccess()
.getTrustedAttributes(man, name.replace('.', '/').concat("/"));
if (attr != null) {
specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
sealed = attr.getValue(Name.SEALED);
}
attr = man.getMainAttributes();
if (attr != null) {
if (specTitle == null) {
specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
}
if (specVersion == null) {
specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
}
if (specVendor == null) {
specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
}
if (implTitle == null) {
implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
}
if (implVersion == null) {
implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
}
if (implVendor == null) {
implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
}
if (sealed == null) {
sealed = attr.getValue(Name.SEALED);
}
}
if ("true".equalsIgnoreCase(sealed)) {
sealBase = url;
}
return definePackage(name, specTitle, specVersion, specVendor,
implTitle, implVersion, implVendor, sealBase);
}
private Package(String name, Manifest man, URL url, ClassLoader loader) {
String path = name.replace('.', '/').concat("/");
String sealed = null;
String specTitle= null;
String specVersion= null;
String specVendor= null;
String implTitle= null;
String implVersion= null;
String implVendor= null;
URL sealBase= null;
Attributes attr = man.getAttributes(path);
if (attr != null) {
specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
sealed = attr.getValue(Name.SEALED);
}
attr = man.getMainAttributes();
if (attr != null) {
if (specTitle == null) {
specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
}
if (specVersion == null) {
specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
}
if (specVendor == null) {
specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
}
if (implTitle == null) {
implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
}
if (implVersion == null) {
implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
}
if (implVendor == null) {
implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
}
if (sealed == null) {
sealed = attr.getValue(Name.SEALED);
}
}
if ("true".equalsIgnoreCase(sealed)) {
sealBase = url;
}
pkgName = name;
this.specTitle = specTitle;
this.specVersion = specVersion;
this.specVendor = specVendor;
this.implTitle = implTitle;
this.implVersion = implVersion;
this.implVendor = implVendor;
this.sealBase = sealBase;
this.loader = loader;
}
private static String valueOf(Attributes mainAttributes, String tag) {
String value = mainAttributes.getValue(tag);
return value == null ? UNAVAILABLE : value;
}
/**
* Creates an App Package object.
*
* If app directory is to be processed, there may be resource leak in the class loader. Only pass true for short-lived
* applications
*
* If contentFolder is not null, it will try to create the contentFolder, file will be retained on disk after App Package is closed
* If contentFolder is null, temp folder will be created and will be cleaned on close()
*
* @param input
* @param contentFolder the folder that the app package will be extracted to
* @param processAppDirectory
* @throws java.io.IOException
*/
public AppPackage(InputStream input, File contentFolder, boolean processAppDirectory) throws IOException
{
try (final ZipArchiveInputStream zipArchiveInputStream =
new ZipArchiveInputStream(input, "UTF8", true, true)) {
if (contentFolder != null) {
FileUtils.forceMkdir(contentFolder);
cleanOnClose = false;
} else {
cleanOnClose = true;
contentFolder = Files.createTempDirectory("dt-appPackage-").toFile();
}
directory = contentFolder;
Manifest manifest = extractToDirectory(directory, zipArchiveInputStream);
if (manifest == null) {
throw new IOException("Not a valid app package. MANIFEST.MF is not present.");
}
Attributes attr = manifest.getMainAttributes();
appPackageName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_NAME);
appPackageVersion = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_VERSION);
appPackageGroupId = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_GROUP_ID);
dtEngineVersion = attr.getValue(ATTRIBUTE_DT_ENGINE_VERSION);
appPackageDisplayName = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_DISPLAY_NAME);
appPackageDescription = attr.getValue(ATTRIBUTE_DT_APP_PACKAGE_DESCRIPTION);
String classPathString = attr.getValue(ATTRIBUTE_CLASS_PATH);
if (appPackageName == null || appPackageVersion == null || classPathString == null) {
throw new IOException("Not a valid app package. App Package Name or Version or Class-Path is missing from MANIFEST.MF");
}
classPath.addAll(Arrays.asList(StringUtils.split(classPathString, " ")));
File confDirectory = new File(directory, "conf");
if (confDirectory.exists()) {
processConfDirectory(confDirectory);
}
resourcesDirectory = new File(directory, "resources");
File propertiesXml = new File(directory, "META-INF/properties.xml");
if (propertiesXml.exists()) {
processPropertiesXml(propertiesXml, null);
}
if (processAppDirectory) {
processAppDirectory(false);
}
}
}
private Package(String name, Manifest man, URL url, ClassLoader loader) {
String path = name.replace('.', '/').concat("/");
String sealed = null;
String specTitle= null;
String specVersion= null;
String specVendor= null;
String implTitle= null;
String implVersion= null;
String implVendor= null;
URL sealBase= null;
Attributes attr = man.getAttributes(path);
if (attr != null) {
specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
sealed = attr.getValue(Name.SEALED);
}
attr = man.getMainAttributes();
if (attr != null) {
if (specTitle == null) {
specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
}
if (specVersion == null) {
specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
}
if (specVendor == null) {
specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
}
if (implTitle == null) {
implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
}
if (implVersion == null) {
implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
}
if (implVendor == null) {
implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
}
if (sealed == null) {
sealed = attr.getValue(Name.SEALED);
}
}
if ("true".equalsIgnoreCase(sealed)) {
sealBase = url;
}
pkgName = name;
this.specTitle = specTitle;
this.specVersion = specVersion;
this.specVendor = specVendor;
this.implTitle = implTitle;
this.implVersion = implVersion;
this.implVendor = implVendor;
this.sealBase = sealBase;
this.loader = loader;
}
/**
* Defines a new package in this ClassLoader. The attributes in the specified
* Manifest are use to get the package version and sealing information.
*
* @throws IllegalArgumentException if the package name duplicates an
* existing package either in this class loader or one of its ancestors
*/
private Package definePackage(String pn, Manifest man, URL url) {
String specTitle = null;
String specVersion = null;
String specVendor = null;
String implTitle = null;
String implVersion = null;
String implVendor = null;
String sealed = null;
URL sealBase = null;
if (man != null) {
Attributes attr = man.getAttributes(pn.replace('.', '/').concat("/"));
if (attr != null) {
specTitle = attr.getValue(Attributes.Name.SPECIFICATION_TITLE);
specVersion = attr.getValue(Attributes.Name.SPECIFICATION_VERSION);
specVendor = attr.getValue(Attributes.Name.SPECIFICATION_VENDOR);
implTitle = attr.getValue(Attributes.Name.IMPLEMENTATION_TITLE);
implVersion = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
implVendor = attr.getValue(Attributes.Name.IMPLEMENTATION_VENDOR);
sealed = attr.getValue(Attributes.Name.SEALED);
}
attr = man.getMainAttributes();
if (attr != null) {
if (specTitle == null)
specTitle = attr.getValue(Attributes.Name.SPECIFICATION_TITLE);
if (specVersion == null)
specVersion = attr.getValue(Attributes.Name.SPECIFICATION_VERSION);
if (specVendor == null)
specVendor = attr.getValue(Attributes.Name.SPECIFICATION_VENDOR);
if (implTitle == null)
implTitle = attr.getValue(Attributes.Name.IMPLEMENTATION_TITLE);
if (implVersion == null)
implVersion = attr.getValue(Attributes.Name.IMPLEMENTATION_VERSION);
if (implVendor == null)
implVendor = attr.getValue(Attributes.Name.IMPLEMENTATION_VENDOR);
if (sealed == null)
sealed = attr.getValue(Attributes.Name.SEALED);
}
// package is sealed
if ("true".equalsIgnoreCase(sealed))
sealBase = url;
}
return definePackage(pn,
specTitle,
specVersion,
specVendor,
implTitle,
implVersion,
implVendor,
sealBase);
}