下面列出了java.util.jar.Attributes#put ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void addJarManifest() {
Manifest manifest = new Manifest();
Attributes attrs = manifest.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attrs.put(Attributes.Name.MAIN_CLASS, Main.class.getName());
attrs.put(new Attributes.Name("Multi-Release"), "true");
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
manifest.write(out);
out.close();
byte[] bytes = out.toByteArray();
this.archive.addAsManifestResource(new ByteArrayAsset(bytes), "MANIFEST.MF");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* Test that java -jar fails when the executable JAR has the
* Launcher-Agent-Class attribute but the class cannot be loaded.
*/
public void testBadAgentClass() throws Exception {
Manifest man = new Manifest();
Attributes attrs = man.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
attrs.put(Attributes.Name.MAIN_CLASS, "Main");
// agent class does not exist
attrs.put(new Attributes.Name("Launcher-Agent-Class"), "BadAgent");
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("ClassNotFoundException").getExitValue();
assertNotEquals(exitCode, 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();
}
private static byte[] manifestContent(TurbineOptions turbineOptions) 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 (turbineOptions.targetLabel().isPresent()) {
attributes.put(TARGET_LABEL, turbineOptions.targetLabel().get());
}
if (turbineOptions.injectingRuleKind().isPresent()) {
attributes.put(INJECTING_RULE_KIND, turbineOptions.injectingRuleKind().get());
}
ByteArrayOutputStream out = new ByteArrayOutputStream();
manifest.write(out);
return out.toByteArray();
}
/**
* 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;
}
/**
* Specify Add-Opens in JAR file manifest
*/
public void testWithAddOpensInManifest() 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-Opens"), "java.base/java.lang");
Path jarfile = Paths.get("x.jar");
Path classes = Paths.get(TEST_CLASSES);
JarUtils.createJarFile(jarfile, man, classes, Paths.get("TryAccess.class"));
run(jarfile, "setAccessibleNonPublicMemberExportedPackage", successNoWarning());
run(jarfile, "reflectPublicMemberNonExportedPackage", successWithWarning());
// attempt two illegal accesses, one allowed by Add-Opens
run(jarfile, "reflectPublicMemberNonExportedPackage,"
+ "setAccessibleNonPublicMemberExportedPackage",
successWithWarning());
}
/** Remove the jar file to the classpath in the MANIFEST.MF file */
@Override
protected void updateClasspath(Manifest manifest) throws DeployException {
Attributes mainAttributes = manifest.getMainAttributes();
String classpath = null;
if (mainAttributes != null) {
classpath = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
}
String newJar = getJarFileNameWithDotSlash();
String newClasspath = null;
if (classpath != null) {
newClasspath = StringUtils.replace(classpath, newJar, "");
mainAttributes.put(Attributes.Name.CLASS_PATH, newClasspath);
if (classpath.length() < newClasspath.length()) {
System.out.println("Removed " + newJar + " from classpath");
}
}
}
/**
* java.util.jar.Attributes.put(java.lang.Object, java.lang.Object)
*/
public void test_putLjava_lang_ObjectLjava_lang_Object_Null() {
Attributes attribute = new Attributes();
assertFalse(attribute.containsKey(null));
assertFalse(attribute.containsValue(null));
attribute.put(null, null);
attribute.put(null, null);
assertEquals(1, attribute.size());
assertTrue(attribute.containsKey(null));
assertTrue(attribute.containsValue(null));
assertNull(attribute.get(null));
String value = "It's null";
attribute.put(null, value);
assertEquals(1, attribute.size());
assertEquals(value, attribute.get(null));
Attributes.Name name = new Attributes.Name("null");
attribute.put(name, null);
assertEquals(2, attribute.size());
assertNull(attribute.get(name));
}
public Manifest getManifest(String artefactName, String serviceVersion, Map<String, String> additionalInfo) {
boolean useRegistry = Boolean.valueOf(additionalInfo.get(ServiceMetadataDialog.USE_SERVICE_REGISTRY));
boolean logMessages = Boolean.valueOf(additionalInfo.get(ServiceMetadataDialog.LOG_MESSAGES));
boolean useSL = Boolean.valueOf(additionalInfo.get(ServiceMetadataDialog.USE_SL));
boolean useSAM = Boolean.valueOf(additionalInfo.get(ServiceMetadataDialog.USE_SAM));
boolean useBusinessCorrelation = Boolean.valueOf(additionalInfo.get(ServiceMetadataDialog.USE_BUSINESS_CORRELATION));
boolean useSecurityToken = Boolean.valueOf(additionalInfo.get(ServiceMetadataDialog.SECURITY_BASIC));
boolean useSecuritySAML = Boolean.valueOf(additionalInfo.get(ServiceMetadataDialog.SECURITY_SAML));
boolean useEncryption = useSecuritySAML && Boolean.valueOf(additionalInfo.get(ServiceMetadataDialog.ENCRYPTION));
Manifest manifest = new Manifest();
Attributes a = manifest.getMainAttributes();
a.put(Attributes.Name.MANIFEST_VERSION, "1.0"); //$NON-NLS-1$
a.put(new Attributes.Name("Bundle-Name"), artefactName); //$NON-NLS-1$
a.put(new Attributes.Name("Bundle-SymbolicName"), artefactName); //$NON-NLS-1$
a.put(new Attributes.Name("Bundle-Version"), serviceVersion); //$NON-NLS-1$
a.put(new Attributes.Name("Bundle-ManifestVersion"), "2"); //$NON-NLS-1$ //$NON-NLS-2$
IBrandingService brandingService = (IBrandingService) GlobalServiceRegister.getDefault().getService(
IBrandingService.class);
a.put(new Attributes.Name("Created-By"), brandingService.getFullProductName() + " (" + brandingService.getAcronym() + '_'
+ RepositoryPlugin.getDefault().getBundle().getVersion().toString() + ')');
a.put(new Attributes.Name("Import-Package"), //$NON-NLS-1$
"javax.xml.ws,org.talend.esb.job.controller" //$NON-NLS-1$
+ ",org.osgi.service.cm;version=\"[1.3,2)\"" //$NON-NLS-1$
+ ",org.apache.cxf,org.apache.cxf.metrics" //$NON-NLS-1$
+ (logMessages ? ",org.apache.cxf.feature" : "") //$NON-NLS-1$
+ (useSL ? ",org.talend.esb.servicelocator.cxf" : "") //$NON-NLS-1$
+ (useSAM ? ",org.talend.esb.sam.agent.feature" : "") //$NON-NLS-1$
+ (useBusinessCorrelation ? ",org.talend.esb.policy.correlation.feature" : "") //$NON-NLS-1$
+ (useSecurityToken || useRegistry ? ",org.apache.wss4j.dom.validate" : "") //$NON-NLS-1$
+ (useSecuritySAML || useRegistry ? ",org.talend.esb.security.saml" : "") //$NON-NLS-1$
+ (useEncryption || useRegistry ? ",org.apache.cxf.xkms.crypto" : "") //$NON-NLS-1$
);
return manifest;
}
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;
}
public Path generateBundle() throws IOException {
// Create an application bundle jar based on current application classpath
Path yarnBundledJarPath = Files.createTempFile(DREMIO_BUNDLE_PREFIX, ".jar");
try (JarGenerator jarGenerator = JarGenerator.of(new JarOutputStream(Files.newOutputStream(yarnBundledJarPath)))) {
// First add prefix classpath entries
// Second, add content of classpath to bundle jar
// Then add extra classpath entries
List<URI> jarEntries = addPathsToBundle(jarGenerator, Stream.concat(toPathStream(classPathPrefix), Stream.concat(toPathStream(classLoader), toPathStream(classPath))));
// After that add native libraries
List<URI> nativeLibrariesEntries = addPathsToBundle(jarGenerator, nativeLibraryPath.stream().map(Paths::get));
// After that add plugins
URI pluginsPathEntry = addPathToJar(jarGenerator, pluginsPath);
// Finally, add classpath and native library path entries in jar manifest
// Following spec for class-path, string is a list of URI separated by space...
Manifest manifest = new Manifest();
final Attributes mainAttributes = manifest.getMainAttributes();
mainAttributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
mainAttributes.put(Attributes.Name.CLASS_PATH,
jarEntries.stream()
.map(URI::toString)
.collect(Collectors.joining(DELIMITER)));
mainAttributes.putValue(X_DREMIO_LIBRARY_PATH_MANIFEST_ATTRIBUTE,
nativeLibrariesEntries.stream().map(URI::toString).collect(Collectors.joining(DELIMITER)));
mainAttributes.putValue(X_DREMIO_PLUGINS_PATH_MANIFEST_ATTRIBUTE, pluginsPathEntry.toString());
jarGenerator.addManifest(manifest);
}
return yarnBundledJarPath;
}
public void testExtraManifestsWithClassifier() {
File testJarPom = Paths.get("src/test/resources/unit/jar-packaging/pom-extramf-classifier-jar.xml").toFile();
assertNotNull(testJarPom);
assertTrue(testJarPom.exists());
assertTrue(testJarPom.isFile());
MavenProject mavenProject = new MavenProject(buildModel(testJarPom));
assertNotNull(mavenProject);
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0");
ProjectManifestCustomizer customizer = new ProjectManifestCustomizer();
Map<String, String> atts = customizer.getEntries(new PackageMojo() {
@Override
public void execute() {
}
@Override
public ScmManager getScmManager() {
return scmManager;
}
}, mavenProject);
atts.forEach(attributes::putValue);
assertThat(attributes.isEmpty()).isFalse();
assertThat(attributes.getValue("Manifest-Version")).isEqualTo("1.0");
assertThat(attributes.getValue(PROJECT_NAME.header())).isEqualTo("vertx-demo");
assertThat(attributes.getValue(BUILD_TIMESTAMP.header())).isNotNull().isNotEmpty();
assertThat(attributes.getValue(PROJECT_DEPS.header())).isEqualTo("com.example:example:3.4.1:vertx");
assertThat(attributes.getValue(PROJECT_GROUP_ID.header())).isEqualTo("org.vertx.demo");
assertThat(attributes.getValue(PROJECT_VERSION.header())).isEqualTo("1.0.0-SNAPSHOT");
}
public static Manifest createManifest(Map<String, String> map) {
Manifest manifest = new Manifest();
Attributes attributes = manifest.getMainAttributes();
attributes.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
for (Map.Entry<String, String> entry : map.entrySet()) {
attributes.put(new Attributes.Name(entry.getKey()), entry.getValue());
}
return manifest;
}
public static void main(String[] args) throws Throwable {
// Create Other.class in OTHER_DIR, off the default classpath
byte klassbuf[] = InMemoryJavaCompiler.compile("Other",
"public class Other {}");
ClassFileInstaller.writeClassToDisk("Other", klassbuf, OTHER_DIR);
// Create Other.jar in OTHER_DIR
JarUtils.createJarFile(OTHER_JAR_PATH,
Paths.get(OTHER_DIR),
Paths.get(OTHER_DIR, "Other.class"));
// Create Context.class
klassbuf = InMemoryJavaCompiler.compile("Context",
"public class Context {}");
ClassFileInstaller.writeClassToDisk("Context", klassbuf, TEST_CLASSES);
// Create Context.jar w/ "file:" entry for Other.jar
Manifest mf = new Manifest();
Attributes attrs = mf.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
String classPathEntry = "file:" + (IS_WINDOWS ? toUnixPath(OTHER_JAR_PATH.toString())
: OTHER_JAR_PATH.toString());
attrs.put(Attributes.Name.CLASS_PATH, classPathEntry);
System.out.println("Creating Context.jar with Class-Path: " + classPathEntry);
JarUtils.createJarFile(CONTEXT_JAR_PATH, mf,
Paths.get(TEST_CLASSES),
Paths.get(TEST_CLASSES, "Context.class"));
// Use URLClassLoader w/ Context.jar to load Other.class, which will
// load via the Class-Path entry
URL url = CONTEXT_JAR_PATH.toUri().toURL();
URLClassLoader ucl = new URLClassLoader(new URL[]{ url },
null); // don't delegate to App CL
Class<?> otherClass = Class.forName("Other", true, ucl); // ClassNotFoundException -> fail
System.out.println("Loaded: " + otherClass);
}
InputStream transform(InputStream inputStream) throws MojoExecutionException {
try (InputStream in = inputStream) { // No need for new variable in Java 9.
Manifest manifest = new Manifest(in);
Attributes attributes = manifest.getMainAttributes();
if (!attributes.containsKey(PREMAIN_CLASS)) {
throw new MojoExecutionException(PREMAIN_CLASS + " not found in MANIFEST.MF. This is a bug in promagent-maven-plugin.");
}
attributes.put(CREATED_BY, pluginArtifactId + ":" + pluginVersion);
ByteArrayOutputStream out = new ByteArrayOutputStream();
manifest.write(out);
return new ByteArrayInputStream(out.toByteArray());
} catch (IOException e) {
throw new MojoExecutionException("Failed to transform MANIFEST.MF: " + e.getMessage(), e);
}
}
private static File createMultiReleaseJar(
@NonNull final File loc,
final boolean hasMultiVersionAttr,
@NonNull final Collection<Pair<String,Collection<Integer>>> spec) throws IOException {
final Manifest mf = new Manifest();
final Attributes attrs = mf.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0"); //NOI18N
if (hasMultiVersionAttr) {
attrs.putValue(
"Multi-Release", //NOI18N
Boolean.TRUE.toString());
}
try (JarOutputStream jar = new JarOutputStream(new FileOutputStream(loc), mf)) {
for (Pair<String,Collection<Integer>> p : spec) {
final String fqn = p.first();
final Collection<Integer> versions = p.second();
final String path = FileObjects.convertPackage2Folder(fqn) + ".class"; //NOI18N
final String name = FileObjects.getBaseName(fqn,'.'); //NOI18N
final Collection<String[]> prefixes = new ArrayList<>();
for (Integer version : versions) {
if (version == 0) {
prefixes.add(new String[]{"","Base"}); //NOI18N
} else {
prefixes.add(new String[]{"META-INF/versions/"+version, version.toString()}); //NOI18N
}
}
for (String[] prefix : prefixes) {
final String pathWithScope = prefix[0].isEmpty() ?
path :
String.format("%s/%s", prefix[0], path); //NOI18N
jar.putNextEntry(new ZipEntry(pathWithScope));
jar.write(String.format("%s %s", name, prefix[1]).getBytes(Charset.forName("UTF-8"))); //NOI18N
jar.closeEntry();
}
}
}
return loc;
}
/**
* Basic test of java -jar with agent in the executable JAR
*/
public void testBasic() throws Exception {
Manifest man = new Manifest();
Attributes attrs = man.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
attrs.put(Attributes.Name.MAIN_CLASS, "Main");
attrs.put(new Attributes.Name("Launcher-Agent-Class"), "Agent");
// require all capabilities
attrs.put(new Attributes.Name("Can-Redefine-Classes"), "true");
attrs.put(new Attributes.Name("Can-Retransform-Classes"), "true");
attrs.put(new Attributes.Name("Can-Set-Native-Method-Prefix"), "true");
attrs.put(new Attributes.Name("Boot-Class-Path"), "helper.jar");
Path app = Paths.get("app.jar");
Path dir = Paths.get(System.getProperty("test.classes"));
Path[] paths = Stream.of("Main.class", "Agent.class")
.map(Paths::get)
.toArray(Path[]::new);
JarUtils.createJarFile(app, man, dir, paths);
// helper API to test that the BCP has been extended
Path helper = Paths.get("helper.jar");
JarUtils.createJarFile(helper, dir, "AgentHelper.class");
// java -jar app.jar
assertEquals(exec(app).getExitValue(), 0);
}
public static void main(String[] args) throws Exception {
// create content for JAR file
Path dir = Files.createTempDirectory("classes");
Path p = Files.createDirectory(dir.resolve("p"));
Files.createFile(p.resolve("Foo.class"));
Files.createFile(p.resolve("foo.properties"));
Path resources = Files.createDirectory(p.resolve("resources"));
Files.createFile(resources.resolve("bar.properties"));
// create the JAR file, including a manifest
Path jarFile = Paths.get("library-1.0.jar");
Manifest man = new Manifest();
Attributes attrs = man.getMainAttributes();
attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
JarUtils.createJarFile(jarFile, man, dir, p);
// get the module name
ModuleFinder finder = ModuleFinder.of(jarFile);
ModuleReference mref = finder.findAll().stream().findAny().orElse(null);
if (mref == null)
throw new RuntimeException("Module not found!!!");
String name = mref.descriptor().name();
// launch the test with the JAR file on the module path
if (ProcessTools.executeTestJava("-p", jarFile.toString(),
"--add-modules", name,
"-cp", TEST_CLASSES,
"Main", name)
.outputTo(System.out)
.errorTo(System.out)
.getExitValue() != 0)
throw new RuntimeException("Test failed - see output");
}
@Override
public void execute(Jar jar)
{
File archiveFile = jar.getArchivePath();
Path archivePath = archiveFile.toPath();
String name = archiveFile.getName();
File parent = archiveFile.getParentFile().getAbsoluteFile();
int p = name.lastIndexOf('.');
String prefix = name.substring(0, p);
String ext = name.substring(p);
String outName = prefix + "-boot" + ext;
Path outFile = parent.toPath().resolve(outName);
try (OutputStream fOs = Files.newOutputStream(outFile)) {
Manifest manifest = new Manifest();
Attributes attr = manifest.getMainAttributes();
attr.put(Attributes.Name.MANIFEST_VERSION, "1.0");
attr.putValue("Main-Class", BaratineBoot.class.getName());
attr.putValue("Boot-Main-Class", getMainClassName());
try (JarOutputStream zOs = new JarOutputStream(fOs, manifest)) {
zOs.setLevel(0);
ZipEntry entry = new ZipEntry("main/main.jar");
entry.setSize(archiveFile.length());
entry.setCompressedSize(archiveFile.length());
entry.setMethod(ZipEntry.STORED);
entry.setCrc(calculateCrc(archivePath));
zOs.putNextEntry(entry);
Files.copy(archivePath, zOs);
writeDependencies(zOs);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static Attributes getAttribute(String name, String value) {
Attributes a = new Attributes();
Attributes.Name attribName = new Attributes.Name(name);
a.put(attribName, value);
return a;
}