下面列出了怎么用java.util.jar.Attributes的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns whether the XDG flag in the manifest (if any) is set to "true".
* @return true if XDG directories are enabled, false otherwise
*/
private static boolean checkXDGFlag() {
JarFile jarFile = Utils.getJarFile();
if (jarFile == null)
return false;
try {
Manifest manifest = jarFile.getManifest();
if (manifest == null)
return false;
Attributes attributes = manifest.getMainAttributes();
String value = attributes.getValue("Use-XDG");
return (value != null && value.equalsIgnoreCase("true"));
} catch (IOException e) {
return false;
}
}
@SuppressWarnings("deprecation")
@Test
public void testInstallBundle() throws Exception {
Map<String, String> manifest = ImmutableMap.of(
Attributes.Name.MANIFEST_VERSION.toString(), "1.2.3",
Constants.BUNDLE_VERSION, "4.5.6",
Constants.BUNDLE_SYMBOLICNAME, "myname");
generatedJar = bundleMaker.copyAddingManifest(emptyJar, manifest);
Bundle bundle = bundleMaker.installBundle(generatedJar, false);
assertEquals(bundle.getSymbolicName(), "myname");
assertEquals(bundle.getVersion(), new Version("4.5.6"));
// Confirm it really is installed in the management context's OSGi framework
Bundle bundle2 = Osgis.bundleFinder(mgmt.getOsgiManager().get().getFramework())
.symbolicName("myname")
.version("4.5.6")
.findUnique()
.get();
assertEquals(bundle2, bundle);
}
URL[] getClassPath() throws IOException {
if (index != null) {
return null;
}
if (metaIndex != null) {
return null;
}
ensureOpen();
parseExtensionsDependencies();
if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) { // Only get manifest when necessary
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;
}
@Override
public void actionPerformed(final ActionEvent e) {
final com.jogamp.opencl.JoclVersion jv = com.jogamp.opencl.JoclVersion.getInstance();
final Set<?> names = jv.getAttributeNames();
final ArrayList<String> lines = new ArrayList<>();
for (final Object name : names) {
lines.add(String.format("%s: %s\n", name, jv.getAttribute((Attributes.Name) name)));
}
Collections.sort(lines);
final StringBuilder sb = new StringBuilder();
sb.append("JOCL Attributes\n");
for (final String line : lines) {
sb.append(line);
}
final InfoTextPanel itp = new InfoTextPanel(sb.toString());
final NotifyDescriptor.Message msg = new NotifyDescriptor.Message(itp);
msg.setTitle(Bundle.CTL_JoclVersionAction());
DialogDisplayer.getDefault().notify(msg);
}
private byte[] manifestContent(@Nullable String targetLabel, @Nullable String injectingRuleKind)
throws IOException {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
Attributes.Name createdBy = new Attributes.Name("Created-By");
if (attributes.getValue(createdBy) == null) {
attributes.put(createdBy, "bazel");
}
if (targetLabel != null) {
// Enable add_deps support. add_deps expects this attribute in the jar manifest.
attributes.putValue("Target-Label", targetLabel);
}
if (injectingRuleKind != null) {
// add_deps support for aspects. Usually null.
attributes.putValue("Injecting-Rule-Kind", injectingRuleKind);
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
manifest.write(out);
return out.toByteArray();
}
@Test
public void Mojo1668Test()
throws Exception
{
Assume.assumeTrue( isSvn18() );
File projDir = resources.getBasedir( "MOJO-1668" );
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" );
File artifact = new File( testDir, "target/buildnumber-maven-plugin-MOJO-1668-1.0-SNAPSHOT.jar" );
JarFile jarFile = new JarFile( artifact );
Attributes manifest = jarFile.getManifest().getMainAttributes();
jarFile.close();
String buildDate = manifest.getValue( "Build-Date" );
Assert.assertTrue( buildDate.length() > 0 );
}
@Test
public void mBuildNum83Test()
throws Exception
{
File projDir = resources.getBasedir( "MBUILDNUM-83" );
MavenExecution mavenExec = maven.forProject( projDir );
MavenExecutionResult result = mavenExec.execute( "clean", "verify" );
result.assertErrorFreeLog();
File testDir = result.getBasedir();
File artifact = new File( testDir, "target/buildnumber-maven-plugin-basic-it-svnjava-1.0-SNAPSHOT.jar" );
JarFile jarFile = new JarFile( artifact );
Attributes manifest = jarFile.getManifest().getMainAttributes();
jarFile.close();
String scmRev = manifest.getValue( "SCM-Revision" );
Assert.assertEquals( "booom", scmRev ); // ??? biim?
}
/**
* Retrieves BAR's implementation date
*
* @return the implementation date or an empty strong if date could not be
* retrieved.
*/
private static String buildDate() {
// http://stackoverflow.com/questions/1272648/
if (BUILD_DATE == null) {
final Class<Utils> clazz = Utils.class;
final String className = clazz.getSimpleName() + ".class";
final String classPath = clazz.getResource(className).toString();
final String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1)
+ "/META-INF/MANIFEST.MF";
try {
final Manifest manifest = new Manifest(new URL(manifestPath).openStream());
final Attributes attr = manifest.getMainAttributes();
BUILD_DATE = attr.getValue("Implementation-Date");
BUILD_DATE = BUILD_DATE.substring(0, BUILD_DATE.lastIndexOf("T"));
} catch (final Exception ignored) {
BUILD_DATE = "";
}
}
return BUILD_DATE;
}
/**
* Specify Add-Exports in JAR file manifest
*/
public void testWithAddExportsInManifest() throws Exception {
Manifest man = new Manifest();
Attributes attrs = man.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attrs.put(Attributes.Name.MAIN_CLASS, "TryAccess");
attrs.put(new Attributes.Name("Add-Exports"), "java.base/sun.security.x509");
Path jarfile = Paths.get("x.jar");
Path classes = Paths.get(TEST_CLASSES);
JarUtils.createJarFile(jarfile, man, classes, Paths.get("TryAccess.class"));
run(jarfile, "reflectPublicMemberNonExportedPackage", successNoWarning());
run(jarfile, "setAccessibleNonPublicMemberExportedPackage", successWithWarning());
// attempt two illegal accesses, one allowed by Add-Exports
run(jarfile, "reflectPublicMemberNonExportedPackage,"
+ "setAccessibleNonPublicMemberExportedPackage",
successWithWarning());
}
private static String checkJar(File jarFile) {
try (JarFile jarFile1 = new JarFile(jarFile)) {
Manifest manifest = jarFile1.getManifest();
Attributes attributes = manifest.getMainAttributes();
String mainClass = attributes.getValue(Attributes.Name.MAIN_CLASS);
if (mainClass == null) {
return jarFile.getAbsolutePath() + "中没有找到对应的MainClass属性";
}
JarClassLoader jarClassLoader = JarClassLoader.load(jarFile);
try {
jarClassLoader.loadClass(mainClass);
} catch (ClassNotFoundException notFound) {
return jarFile.getAbsolutePath() + "中没有找到对应的MainClass:" + mainClass;
}
} catch (Exception e) {
DefaultSystemLog.getLog().error("解析jar", e);
return jarFile.getAbsolutePath() + " 解析错误:" + e.getMessage();
}
return null;
}
/**
* Test that a JAR file with a Main-Class attribute that is not in the module
*/
public void testMissingMainClassPackage() throws IOException {
Manifest man = new Manifest();
Attributes attrs = man.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
attrs.put(Attributes.Name.MAIN_CLASS, "p.Main");
Path dir = Files.createTempDirectory(USER_DIR, "mods");
createDummyJarFile(dir.resolve("m.jar"), man);
// Main-Class should be ignored because package p is not in module
Optional<ModuleReference> omref = ModuleFinder.of(dir).find("m");
assertTrue(omref.isPresent());
ModuleDescriptor descriptor = omref.get().descriptor();
assertFalse(descriptor.mainClass().isPresent());
}
/**
* 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());
}
}
private static void parseRequirement(BundleInfo bundleInfo, Attributes mainAttributes,
String headerName, String type, String versionAttr) throws ParseException {
ManifestHeaderValue elements = new ManifestHeaderValue(mainAttributes.getValue(headerName));
for (ManifestHeaderElement element : elements.getElements()) {
String resolution = element.getDirectives().get(ATTR_RESOLUTION);
String attVersion = element.getAttributes().get(versionAttr);
VersionRange version = null;
try {
version = versionRangeOf(attVersion);
} catch (ParseException e) {
throw new ParseException("The " + headerName + " has an incorrect version: "
+ attVersion + " (" + e.getMessage() + ")", 0);
}
for (String name : element.getValues()) {
bundleInfo.addRequirement(new BundleRequirement(type, name, version, resolution));
}
}
}
@Override
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("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;
}
/**
* Test that java -jar fails when the executable JAR has the
* Launcher-Agent-Class attribute and the class does not define an
* agentmain method.
*/
public void testNoAgentMain() throws Exception {
// manifest for the executable JAR
Manifest man = new Manifest();
Attributes attrs = man.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
attrs.put(Attributes.Name.MAIN_CLASS, "Main");
// the main class does not define the agentmain method
attrs.put(new Attributes.Name("Launcher-Agent-Class"), "Main");
Path app = Paths.get("app.jar");
Path dir = Paths.get(System.getProperty("test.classes"));
JarUtils.createJarFile(app, man, dir, Paths.get("Main.class"));
// java -jar app.jar
int exitCode = exec(app).shouldContain("NoSuchMethodException").getExitValue();
assertNotEquals(exitCode, 0);
}
@SuppressWarnings("deprecation")
@Override
protected Manifest getMeta() {
Manifest retManifest = new Manifest();
Attributes main = retManifest.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("Patch-Name", name);
try {
fillManifest(main);
} catch (IOException e) {
e.printStackTrace();
return null;
}
return retManifest;
}
@Test
public void testNonSealedIsCompatibleToSealed() throws Exception {
File file = File.createTempFile(FOO, BAR);
try {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
manifest.getMainAttributes().put(Attributes.Name.SEALED, Boolean.TRUE.toString());
URL url = new ByteBuddy().subclass(Object.class).name("foo.Bar").make().toJar(file, manifest).toURI().toURL();
ClassLoader classLoader = new URLClassLoader(new URL[]{url}, null);
Package definedPackage = classLoader.loadClass("foo.Bar").getPackage();
assertThat(new PackageDefinitionStrategy.Definition.Simple(FOO, BAR, QUX, BAZ, FOO + BAR, QUX + BAZ, null)
.isCompatibleTo(definedPackage), is(false));
} finally {
file.deleteOnExit();
}
}
@Test
public void testCreate() throws Exception {
Map<String, String> manifest = ImmutableMap.of(
Attributes.Name.MANIFEST_VERSION.toString(), "1.2.3",
Constants.BUNDLE_VERSION, "4.5.6",
Constants.BUNDLE_SYMBOLICNAME, "myname");
generatedJar = bundleMaker.createTempBundle("test", manifest,
ImmutableMap.of(new ZipEntry("myfile.txt"), new ByteArrayInputStream("mytext".getBytes())));
assertJarContents(generatedJar, ImmutableMap.of("myfile.txt", "mytext"), true);
@SuppressWarnings("deprecation")
Bundle bundle = bundleMaker.installBundle(generatedJar, false);
assertEquals(bundle.getSymbolicName(), "myname");
assertEquals(bundle.getVersion(), new Version("4.5.6"));
}
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;
}
private static Map<String, String> load(InputStream stream) {
Map<String, String> props = Maps.newConcurrentMap();
try {
Manifest manifest = new Manifest(stream);
Attributes attributes = manifest.getMainAttributes();
for (Object key : attributes.keySet()) {
String value = attributes.getValue((Attributes.Name) key);
props.put(key.toString(), value);
}
} catch (Throwable t) {
logger.error("#load(): failed", t);
} finally {
try {
stream.close();
} catch (IOException e) {
// ignored
}
}
return props;
}
URL[] getClassPath() throws IOException {
if (index != null) {
return null;
}
if (metaIndex != null) {
return null;
}
ensureOpen();
parseExtensionsDependencies();
if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) { // Only get manifest when necessary
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 {
if (index != null) {
return null;
}
if (metaIndex != null) {
return null;
}
ensureOpen();
parseExtensionsDependencies();
if (SharedSecrets.javaUtilJarAccess().jarFileHasClassPathAttribute(jar)) { // Only get manifest when necessary
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;
}
@Nullable
private static Map<Resource.Attribute, String> getAttributes(@Nullable Attributes attributes) {
if (attributes == null) return null;
Map<Resource.Attribute, String> map = null;
for (Pair<Resource.Attribute, Attributes.Name> p : PACKAGE_FIELDS) {
String value = attributes.getValue(p.second);
if (value != null) {
if (map == null) map = new EnumMap<Resource.Attribute, String>(Resource.Attribute.class);
map.put(p.first, value);
}
}
return map;
}
private String[] computeExported(boolean useOSGi, Collection<String> arr, Attributes attr) {
if (!useOSGi) {
return arr.toArray(ZERO_STRING_ARRAY);
}
String pkgs = attr.getValue("Export-Package"); // NOI18N
if (pkgs == null) {
return arr.toArray(ZERO_STRING_ARRAY);
}
StringTokenizer tok = createTokenizer(pkgs); // NOI18N
while (tok.hasMoreElements()) {
arr.add(beforeSemicolon(tok));
}
return arr.toArray(ZERO_STRING_ARRAY);
}
protected synchronized boolean checkExtension(final String extensionName,
final Attributes attr)
throws ExtensionInstallationException
{
debug("Checking extension " + extensionName);
if (checkExtensionAgainstInstalled(extensionName, attr))
return true;
debug("Extension not currently installed ");
ExtensionInfo reqInfo = new ExtensionInfo(extensionName, attr);
return installExtension(reqInfo, null);
}
static void checkOrder(Attributes.Name k0, String v0,
Attributes.Name k1, String v1,
Attributes.Name k2, String v2) {
Attributes x = new Attributes();
x.put(k0, v0);
x.put(k1, v1);
x.put(k2, v2);
Map.Entry<?,?>[] entries
= x.entrySet().toArray(new Map.Entry<?,?>[3]);
if (!(entries.length == 3
&& entries[0].getKey() == k0
&& entries[0].getValue() == v0
&& entries[1].getKey() == k1
&& entries[1].getValue() == v1
&& entries[2].getKey() == k2
&& entries[2].getValue() == v2)) {
throw new AssertionError(Arrays.toString(entries));
}
Object[] keys = x.keySet().toArray();
if (!(keys.length == 3
&& keys[0] == k0
&& keys[1] == k1
&& keys[2] == k2)) {
throw new AssertionError(Arrays.toString(keys));
}
}
private void addJarClassPath(String jarFileName, boolean warn) {
try {
String jarParent = new File(jarFileName).getParent();
JarFile jar = new JarFile(jarFileName);
try {
Manifest man = jar.getManifest();
if (man == null) return;
Attributes attr = man.getMainAttributes();
if (attr == null) return;
String path = attr.getValue(Attributes.Name.CLASS_PATH);
if (path == null) return;
for (StringTokenizer st = new StringTokenizer(path);
st.hasMoreTokens();) {
String elt = st.nextToken();
if (jarParent != null)
elt = new File(jarParent, elt).getCanonicalPath();
addFile(elt, warn);
}
} finally {
jar.close();
}
} catch (IOException e) {
// log.error(Position.NOPOS,
// "error.reading.file", jarFileName,
// e.getLocalizedMessage());
}
}
/** Copy all the files in a manifest from input to output. */
private static void copyFiles(Manifest manifest, JarFile in, JarArchiveOutputStream out, long timestamp)
throws IOException {
final byte[] buffer = new byte[4096];
int num;
final Map<String, Attributes> entries = manifest.getEntries();
final List<String> names = new ArrayList<>(entries.keySet());
Collections.sort(names);
for (final String name : names) {
final JarEntry inEntry = in.getJarEntry(name);
if (inEntry.getMethod() == JarArchiveEntry.STORED) {
// Preserve the STORED method of the input entry.
out.putArchiveEntry(new JarArchiveEntry(inEntry));
} else {
// Create a new entry so that the compressed len is recomputed.
final JarArchiveEntry je = new JarArchiveEntry(name);
je.setTime(timestamp);
out.putArchiveEntry(je);
}
final InputStream data = in.getInputStream(inEntry);
while ((num = data.read(buffer)) > 0) {
out.write(buffer, 0, num);
}
out.flush();
out.closeArchiveEntry();
}
}
@Test public void testMergeRequiredBundles() throws Exception {
String packageName = getClass().getPackage().getName().replace('.', '/');
InputStream resourceAsStream = getClass().getResourceAsStream("/" + packageName + "/Test_Manifest.MF");
MergeableManifest manifest = new MergeableManifest(resourceAsStream);
Attributes attrs = manifest.getMainAttributes();
String before = ((String) attrs.get(MergeableManifest.REQUIRE_BUNDLE)).replaceAll("\\s","");
manifest.addRequiredBundles(Collections.singleton("foo.bar.baz"));
String after = (String) attrs.get(MergeableManifest.REQUIRE_BUNDLE);
assertEquals(before + ",foo.bar.baz", after.replaceAll("\\s",""));
}
private void addJarClassPath(String jarFileName, boolean warn) {
try {
String jarParent = new File(jarFileName).getParent();
JarFile jar = new JarFile(jarFileName);
try {
Manifest man = jar.getManifest();
if (man == null) return;
Attributes attr = man.getMainAttributes();
if (attr == null) return;
String path = attr.getValue(Attributes.Name.CLASS_PATH);
if (path == null) return;
for (StringTokenizer st = new StringTokenizer(path);
st.hasMoreTokens();) {
String elt = st.nextToken();
if (jarParent != null)
elt = new File(jarParent, elt).getCanonicalPath();
addFile(elt, warn);
}
} finally {
jar.close();
}
} catch (IOException e) {
// log.error(Position.NOPOS,
// "error.reading.file", jarFileName,
// e.getLocalizedMessage());
}
}