下面列出了怎么用java.util.jar.Manifest的API类实例代码及写法,或者点击链接到github查看源代码。
public void testSimpleDepOnJava() throws Exception {
StringBuilder writeTo = new StringBuilder();
Set<ProblemModule> modules = new HashSet<ProblemModule>();
{
Manifest mf = new Manifest();
mf.getMainAttributes().putValue("OpenIDE-Module", "root.module");
ProblemModule pm = new ProblemModule(mf);
pm.addProblem(Dependency.create(Dependency.TYPE_JAVA, "Java > 1.30"));
pm.addAttr("OpenIDE-Module-Name", "RootModule");
modules.add(pm);
}
NbProblemDisplayer.problemMessagesForModules(writeTo, modules, true);
String msg = writeTo.toString();
if (msg.indexOf("RootModule") == -1) {
fail("There should be noted the root module: " + msg);
}
}
@Test
public void shouldSortManifestAttributesAndEntries() throws InterruptedException, IOException {
Manifest fromJar =
createManifestWithExampleSection(ImmutableMap.of("foo", "bar", "baz", "waz"));
Manifest fromUser =
createManifestWithExampleSection(ImmutableMap.of("bar", "foo", "waz", "baz"));
String seenManifest =
new String(jarDirectoryAndReadManifestContents(fromJar, fromUser, true), UTF_8);
assertEquals(
Joiner.on("\r\n")
.join(
"Manifest-Version: 1.0",
"",
"Name: example",
"bar: foo",
"baz: waz",
"foo: bar",
"waz: baz",
"",
""),
seenManifest);
}
public String[] getVersion() throws Exception {
Enumeration<URL> resources = CommandLine.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
URL url = resources.nextElement();
try {
Manifest manifest = new Manifest(url.openStream());
if (isApplicableManifest(manifest)) {
Attributes attributes = manifest.getMainAttributes();
return new String[] { attributes.get(key("Implementation-Title")) + " version \"" + attributes.get(key("Implementation-Version")) + "\"" };
}
} catch (IOException ex) {
return new String[] { "Unable to read from " + url + ": " + ex };
}
}
return new String[0];
}
private byte[] generateConfigurationJar(final String family, final Properties userConfiguration) {
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
final Manifest manifest = new Manifest();
final Attributes mainAttributes = manifest.getMainAttributes();
mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
mainAttributes.putValue("Created-By", "Talend Component Kit Server");
mainAttributes.putValue("Talend-Time", Long.toString(System.currentTimeMillis()));
mainAttributes.putValue("Talend-Family-Name", family);
try (final JarOutputStream jar = new JarOutputStream(new BufferedOutputStream(outputStream), manifest)) {
jar.putNextEntry(new JarEntry("TALEND-INF/local-configuration.properties"));
userConfiguration.store(jar, "Configuration of the family " + family);
jar.closeEntry();
} catch (final IOException e) {
throw new IllegalStateException(e);
}
return outputStream.toByteArray();
}
@Test
public void testManifestEntries() throws Exception {
assertThat(prodModeTestResults.getResults()).hasSize(1);
Path jarPath = prodModeTestResults.getResults().get(0).getPath();
try (InputStream fileInputStream = new FileInputStream(jarPath.toFile())) {
try (JarInputStream stream = new JarInputStream(fileInputStream)) {
Manifest manifest = stream.getManifest();
assertThat(manifest).isNotNull();
assertThat(manifest.getEntries().size()).isEqualTo(1);
Attributes testAttributes = manifest.getEntries().get("Test-Information");
assertThat(testAttributes).isNotNull();
Attributes.Name testKey1 = new Attributes.Name("Test-Key-1");
Assert.assertTrue("Custom Manifest Entry for Test-Key-1 is missing",
testAttributes.containsKey(testKey1));
Assert.assertEquals("Custom Manifest Entry for Test-Key-1 value is not correct",
"Test Value 1", testAttributes.getValue(testKey1));
Assert.assertTrue("Custom Manifest Entry for Test-Key-2 is missing",
testAttributes.containsKey(new Attributes.Name("Test-Key-2")));
}
}
}
public static String getVersion() {
try {
ClassLoader classLoader = Jadx.class.getClassLoader();
if (classLoader != null) {
Enumeration<URL> resources = classLoader.getResources("META-INF/MANIFEST.MF");
while (resources.hasMoreElements()) {
try (InputStream is = resources.nextElement().openStream()) {
Manifest manifest = new Manifest(is);
String ver = manifest.getMainAttributes().getValue("jadx-version");
if (ver != null) {
return ver;
}
}
}
}
} catch (Exception e) {
LOG.error("Can't get manifest file", e);
}
return "dev";
}
public static ManifestFinder mockManifest(String releaseVersion) {
Attributes attributes = new Attributes();
attributes.putValue("Build-Time", "2014-05-27 12:52 -0500");
attributes.putValue("Implementation-Version", "1d073ed3f6");
attributes.putValue("Build-Jdk", "1.7.0_51");
attributes.putValue("Built-By", "Jenkinson");
attributes.putValue("Manifest-Version", "1.0");
attributes.putValue("Created-By", "Apache Maven 3.1.1");
attributes.putValue("Release", releaseVersion);
attributes.putValue("URL", "http://www.splicemachine.com");
attributes.putValue("Archiver-Version", "Plexus Archiver");
Manifest spliceManifest = mock(Manifest.class);
when(spliceManifest.getMainAttributes()).thenReturn(attributes);
ManifestFinder mockFinder = mock(ManifestFinder.class);
when(mockFinder.findManifest()).thenReturn(spliceManifest);
return mockFinder;
}
Manifest createMainClass(File javaFile) throws IOException {
javaFile.delete();
List<String> content = new ArrayList<>();
content.add("public class " + baseName(javaFile) + "{");
content.add("public static void main(String... args) {");
content.add("System.out.println(\"Hello World\\n\");");
content.add("System.exit(0);");
content.add("}");
content.add("}");
createFile(javaFile, content);
compile(javaFile.getName());
Manifest manifest = new Manifest();
manifest.clear();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().put(Attributes.Name.MAIN_CLASS, baseName(javaFile));
System.out.println(manifest.getMainAttributes().keySet());
System.out.println(manifest.getMainAttributes().values());
return manifest;
}
/**
* 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());
}
}
public PluginClassLoader(@Nonnull final File pluginFile) throws IOException {
super(new URL[] {Assertions.assertNotNull(pluginFile).toURI().toURL()}, PluginClassLoader.class.getClassLoader());
this.pluginFile = pluginFile;
this.connection = (JarURLConnection) new URL("jar", "", pluginFile.toURI() + "!/").openConnection();
final Manifest manifest = this.connection.getManifest();
Map<String, String> detectedAttributes = null;
if (manifest != null) {
final Attributes pluginAttributes = manifest.getEntries().get("nb-mindmap-plugin");
if (pluginAttributes != null) {
detectedAttributes = new HashMap<String, String>();
for (final Object key : pluginAttributes.keySet()) {
final String keyAsText = key.toString();
detectedAttributes.put(keyAsText, pluginAttributes.getValue(keyAsText));
}
}
}
if (detectedAttributes == null) {
throw new IllegalArgumentException("File is not a NB mind map plugin");
}
this.attributes = Collections.unmodifiableMap(detectedAttributes);
this.apiVersion = new Version(this.attributes.get(Attribute.API.getAttrName()));
}
private static String[] getClassPathEntries(final ResourceRoot resourceRoot) {
final Manifest manifest;
try {
manifest = VFSUtils.getManifest(resourceRoot.getRoot());
} catch (IOException e) {
throw new RuntimeException(e);
}
if (manifest == null) {
// no class path to process!
return EMPTY_STRING_ARRAY;
}
final String classPathString = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
if (classPathString == null) {
// no entry
return EMPTY_STRING_ARRAY;
}
return classPathString.split("\\s+");
}
private File createModuleJar(String manifest) throws IOException {
// XXX use TestFileUtils.writeZipFile
File jarFile = new File( getWorkDir(), "mymodule.jar" );
JarOutputStream os = new JarOutputStream(new FileOutputStream(jarFile), new Manifest(
new ByteArrayInputStream(manifest.getBytes())
));
JarEntry entry = new JarEntry("foo/mf-layer.xml");
os.putNextEntry( entry );
File l3 = new File(new File(new File(getDataDir(), "layers"), "data"), "layer3.xml");
InputStream is = new FileInputStream(l3);
FileUtil.copy( is, os );
is.close();
os.close();
return jarFile;
}
@SuppressWarnings("deprecation")
protected Manifest getMeta() {
Manifest manifest = new Manifest();
Attributes main = manifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
main.putValue("Created-By", "1.0 (ApkPatch)");
main.putValue("Created-Time", new Date(System.currentTimeMillis()).toGMTString());
main.putValue("From-File", baseFiles.get(0).getName());
main.putValue("To-File", newFiles.get(0).getName());
main.putValue("Patch-Name", name);
main.putValue(name + "-Patch-Classes", Formater.dotStringList(classes));
main.putValue(name + "-Prepare-Classes", Formater.dotStringList(prepareClasses));
main.putValue(name + "-Used-Methods", Formater.dotStringList(usedMethods));
main.putValue(name + "-Modified-Classes", Formater.dotStringList(modifiedClasses));
main.putValue(name + "-Used-Classes", Formater.dotStringList(usedClasses));
main.putValue(name + "-add-classes", Formater.dotStringList(addClasses));
return manifest;
}
private void definePackageInternal(String pkgname, Manifest man, URL url)
{
if (getAndVerifyPackage(pkgname, man, url) == null) {
try {
if (man != null) {
definePackage(pkgname, man, url);
} else {
definePackage(pkgname, null, null, null, null, null, null, null);
}
} catch (IllegalArgumentException iae) {
// parallel-capable class loaders: re-verify in case of a
// race condition
if (getAndVerifyPackage(pkgname, man, url) == null) {
// Should never happen
throw new AssertionError("Cannot find package " +
pkgname);
}
}
}
}
private Package getAndVerifyPackage(String pkgname,
Manifest man, URL url) {
Package pkg = getPackage(pkgname);
if (pkg != null) {
// Package found, so check package sealing.
if (pkg.isSealed()) {
// Verify that code source URL is the same.
if (!pkg.isSealed(url)) {
throw new SecurityException(
"sealing violation: package " + pkgname + " is sealed");
}
} else {
// Make sure we are not attempting to seal the package
// at this code source URL.
if ((man != null) && isSealed(pkgname, man)) {
throw new SecurityException(
"sealing violation: can't seal package " + pkgname +
": already loaded");
}
}
}
return pkg;
}
private static void logAegisthusVersion() {
String classPath = Aegisthus.class.getResource("Aegisthus.class").toString();
String manifestPath = classPath.replace("com/netflix/Aegisthus.class", "META-INF/MANIFEST.MF");
try (InputStream inputStream = new URL(manifestPath).openStream()) {
Manifest manifest = new Manifest(inputStream);
Attributes attr = manifest.getMainAttributes();
System.out.println("Running Aegisthus version " +
attr.getValue("Implementation-Version") +
" built from change " +
attr.getValue("Change") +
" on host " +
attr.getValue("Build-Host") +
" on " +
attr.getValue("Build-Date") +
" with Java " +
attr.getValue("Build-Java-Version")
);
} catch (IOException ignored) {
System.out.println("Unable to locate Aegisthus manifest file");
}
}
private void createJarFromClassPathResources(final FileOutputStream fos,
final String location) throws IOException {
final Manifest m = new Manifest();
m.clear();
final Attributes global = m.getMainAttributes();
if (global.getValue(Attributes.Name.MANIFEST_VERSION) == null) {
global.put(Attributes.Name.MANIFEST_VERSION, "1.0");
}
final File mylocation = new File(location);
global.putValue(BOOT_CLASSPATH, getBootClassPath(mylocation));
global.putValue(PREMAIN_CLASS, AGENT_CLASS_NAME);
global.putValue(AGENT_CLASS, AGENT_CLASS_NAME);
global.putValue(CAN_REDEFINE_CLASSES, "true");
global.putValue(CAN_RETRANSFORM_CLASSES, "true");
global.putValue(CAN_SET_NATIVE_METHOD, "true");
try(JarOutputStream jos = new JarOutputStream(fos, m)) {
addClass(Agent.class, jos);
addClass(CodeCoverageStore.class, jos);
addClass(InvokeReceiver.class, jos);
}
}
/** Creates a temporary file with the given metadata */
public File createTempBundle(String nameHint, Manifest mf, Map<ZipEntry, InputStream> files) {
File f2 = Os.newTempFile(nameHint, "zip");
ZipOutputStream zout = null;
ZipFile zf = null;
try {
zout = mf!=null ? new JarOutputStream(new FileOutputStream(f2), mf) : new ZipOutputStream(new FileOutputStream(f2));
writeZipEntries(zout, files);
} catch (IOException e) {
throw Exceptions.propagateAnnotated("Unable to read/write for "+nameHint, e);
} finally {
Streams.closeQuietly(zf);
Streams.closeQuietly(zout);
}
return f2;
}
private static Optional<String> findFirstManifestAttribute(JarFile jarFile, String... attributes) throws IOException {
Manifest manifest = jarFile.getManifest();
if (manifest == null) {
return Optional.empty();
}
Attributes mainAttributes = manifest.getMainAttributes();
for (String attribute : attributes) {
String value = mainAttributes.getValue(attribute);
if (value != null) {
return Optional.of(value);
}
}
return Optional.empty();
}
private boolean updateManifest(Manifest m, ZipOutputStream zos)
throws IOException
{
addVersion(m);
addCreatedBy(m);
if (ename != null) {
addMainClass(m, ename);
}
ZipEntry e = new ZipEntry(MANIFEST_NAME);
e.setTime(System.currentTimeMillis());
if (flag0) {
crc32Manifest(e, m);
}
zos.putNextEntry(e);
m.write(zos);
if (vflag) {
output(getMsg("out.update.manifest"));
}
return true;
}
private void repackageModule() throws IOException {
File destination = pluginModuleJar.getAbsoluteFile();
destination.delete();
JarFile jarFileSource = new JarFile(source);
JarWriter writer = new JarWriter(destination);
Manifest manifest = buildModuleManifest(jarFileSource);
try {
writer.writeManifest(manifest);
writer.writeEntries(jarFileSource);
writer.writeMarkEntry();
writeNestedLibraries(standardLibraries, Layouts.Module.module(), writer);
} finally {
jarFileSource.close();
try {
writer.close();
} catch (Exception ex) {
// Ignore
}
}
}
private void createJar(final File jarFile, final File[] files) throws IOException
{
final Manifest manifest = new Manifest();
final Attributes attributes = manifest.getMainAttributes();
attributes.putValue("Manifest-Version", "1.0");
attributes.putValue("Created-By", "RepoGen 1.0.0");
final FileOutputStream fos = new FileOutputStream(jarFile);
final JarOutputStream jos = new JarOutputStream(fos, manifest);
for (final File file : files)
{
final ZipEntry entry = new ZipEntry(file.getName());
jos.putNextEntry(entry);
final FileInputStream fis = new FileInputStream(file);
pipeStream(fis, jos);
fis.close();
}
jos.close();
}
/**
* Generate the classpath parameters to a temporary classpath.jar.
* @param classPaths - the classpath parameters
* @return the file path of the generate classpath.jar
* @throws IOException Some errors occur during generating the classpath.jar
*/
public static Path generateClasspathJar(String[] classPaths) throws IOException {
List<String> classpathUrls = new ArrayList<>();
for (String classpath : classPaths) {
classpathUrls.add(AdapterUtils.toUrl(classpath));
}
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
// In jar manifest, the absolute path C:\a.jar should be converted to the url style file:///C:/a.jar
String classpathValue = String.join(" ", classpathUrls);
attributes.put(Attributes.Name.CLASS_PATH, classpathValue);
Path tempfile = createTempFile("cp_" + getMd5(classpathValue), ".jar");
JarOutputStream jar = new JarOutputStream(new FileOutputStream(tempfile.toFile()), manifest);
jar.close();
return tempfile;
}
private ProjectInfo() {
String path = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
try(JarFile systemDsJar = new JarFile(path)) {
Manifest manifest = systemDsJar.getManifest();
Attributes mainAttributes = manifest.getMainAttributes();
properties = new TreeMap<>();
for (Object key : mainAttributes.keySet()) {
String value = mainAttributes.getValue((Name) key);
properties.put(key.toString(), value);
}
} catch (Exception e) {
throw new MLContextException("Error trying to read from manifest in SystemDS jar file", e);
}
}
private Manifest createManifestWithExampleSection(Map<String, String> attributes) {
Manifest manifest = new Manifest();
Attributes attrs = new Attributes();
for (Map.Entry<String, String> stringStringEntry : attributes.entrySet()) {
attrs.put(new Attributes.Name(stringStringEntry.getKey()), stringStringEntry.getValue());
}
manifest.getEntries().put("example", attrs);
return manifest;
}
/**
* Create a jar file using the list of files provided.
*
* @param jar
* @param files
* @throws IOException
*/
public static void createJar(File jar, List<File> files)
throws IOException {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION,
"1.0");
try (JarOutputStream target = new JarOutputStream(
new FileOutputStream(jar), manifest)) {
for (File file : files) {
add(file, target);
}
}
}
/**
* Generates the transitive closure of the Class-Path attribute for
* the specified jar file.
*/
List<String> getJarPath(String jar) throws IOException {
List<String> files = new ArrayList<String>();
files.add(jar);
jarPaths.add(jar);
// take out the current path
String path = jar.substring(0, Math.max(0, jar.lastIndexOf('/') + 1));
// class path attribute will give us jar file name with
// '/' as separators, so we need to change them to the
// appropriate one before we open the jar file.
JarFile rf = new JarFile(jar.replace('/', File.separatorChar));
if (rf != null) {
Manifest man = rf.getManifest();
if (man != null) {
Attributes attr = man.getMainAttributes();
if (attr != null) {
String value = attr.getValue(Attributes.Name.CLASS_PATH);
if (value != null) {
StringTokenizer st = new StringTokenizer(value);
while (st.hasMoreTokens()) {
String ajar = st.nextToken();
if (!ajar.endsWith("/")) { // it is a jar file
ajar = path.concat(ajar);
/* check on cyclic dependency */
if (! jarPaths.contains(ajar)) {
files.addAll(getJarPath(ajar));
}
}
}
}
}
}
}
rf.close();
return files;
}
@Test
public void testGetManifest() throws Exception {
Manifest manifest = ArchiveHandler.getManifest(ArchiveHandlerTest.class.getResourceAsStream(SAMPLE_MTAR), MAX_MANIFEST_SIZE);
Map<String, Attributes> entries = manifest.getEntries();
assertEquals(4, entries.size());
assertTrue(entries.containsKey("web/web-server.zip"));
assertTrue(entries.containsKey("applogic/pricing.zip"));
assertTrue(entries.containsKey("db/pricing-db.zip"));
assertTrue(entries.containsKey("META-INF/mtad.yaml"));
}
private static String getJarVersion(Class targetClass)
{
String manifestFileLocation = getManifestFileLocationOfClass(targetClass);
try
{
return new Manifest(new URL(manifestFileLocation).openStream())
.getMainAttributes().getValue(Attributes.Name.IMPLEMENTATION_VERSION);
}
catch (Exception e)
{
return null;
}
}
public void testCanExcludeOSGiWithAttributes() throws Exception {
Parameter p = new Parameter();
p.setName("excludeModules");
p.setValue("org.eclipse.core.jobs");
selector.setParameters(new Parameter[] { p });
Manifest m = createManifest ();
m.getMainAttributes().putValue("Bundle-SymbolicName", "org.eclipse.core.jobs; singleton:=true");
File aModule = generateJar(new String[0], m);
assertFalse("Refused", selector.isSelected(getWorkDir(), aModule.toString(), aModule));
}