下面列出了java.util.jar.Attributes#putValue ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Test
public void testLinesSplitLikeJavaImpl() throws IOException {
// TODO(jtorkkola): Re-enable and change behavior of {@link DeterministicManifest} to match new
// behavior {@link java.util.jar.Manifest} once Java 11 migration is complete.
Assume.assumeThat(JavaVersion.getMajorVersion(), lessThanOrEqualTo(8));
String entryName = "test";
String key = "12345678";
String value =
"138-char value + 8 char key + 2 char padding = 148 chars. |"
+ "69-character second line |"
+ "last line";
manifestWriter.setEntryAttribute(entryName, key, value);
manifestWriter.write(outputStream);
Manifest jdkManifest = new Manifest();
Attributes attrs = new Attributes();
attrs.putValue(key, value);
jdkManifest.getEntries().put(entryName, attrs);
ByteArrayOutputStream expected = new ByteArrayOutputStream();
jdkManifest.write(expected);
assertArrayEquals(expected.toByteArray(), outputStream.toByteArray());
}
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();
}
/**
* Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
* <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
* the archive will not be signed.
* @param out the {@link OutputStream} where to write the Jar archive.
* @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>.
* @param certificate the {@link X509Certificate} used to sign the archive, or
* <code>null</code>.
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public SignedJarBuilder(OutputStream out, PrivateKey key, X509Certificate certificate)
throws IOException, NoSuchAlgorithmException {
mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
mOutputJar.setLevel(9);
mKey = key;
mCertificate = certificate;
if (mKey != null && mCertificate != null) {
mManifest = new Manifest();
Attributes main = mManifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
main.putValue("Created-By", "1.0 (Android)");
mBase64Encoder = new BASE64Encoder();
mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
}
}
@BeforeSuite
public void setup() throws IOException {
defaultAttributes = new Attributes();
defaultAttributes.putValue("Manifest-Version", "1.0");
defaultAttributes.putValue("Created-By", "1.8.0-internal");
mrjar1 = Paths.get("mrjar1.jar");
mrjar2 = Paths.get("mrjar2.jar");
nonMRjar = Paths.get("nonMRjar.jar");
mrjarAllCaps = Paths.get("mrjarAllCaps.jar");
Attributes mrJarAttrs = new Attributes(defaultAttributes);
mrJarAttrs.putValue(MRJAR_ATTR, "true");
build(mrjar1, mrJarAttrs);
build(mrjar2, mrJarAttrs);
build(nonMRjar, defaultAttributes);
// JEP 238 - "Multi-Release JAR Files" states that the attribute name
// and value are case insensitive. Try with all caps to ensure that
// jdeps still recognizes a multi-release jar.
Attributes allCapsAttrs = new Attributes(defaultAttributes);
allCapsAttrs.putValue(MRJAR_ATTR.toUpperCase(), "TRUE");
build(mrjarAllCaps, allCapsAttrs);
}
protected void redefineFoo() throws Exception {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
Attributes mainAttrs = manifest.getMainAttributes();
mainAttrs.putValue("Agent-Class", FooAgent.class.getName());
mainAttrs.putValue("Can-Redefine-Classes", "true");
mainAttrs.putValue("Can-Retransform-Classes", "true");
Path jar = Files.createTempFile("myagent", ".jar");
try {
JarOutputStream jarStream = new JarOutputStream(new FileOutputStream(jar.toFile()), manifest);
add(jarStream, FooAgent.class);
add(jarStream, FooTransformer.class);
jarStream.close();
loadAgent(jar);
} finally {
Files.deleteIfExists(jar);
}
}
/**
* Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
* <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
* the archive will not be signed.
* @param out the {@link OutputStream} where to write the Jar archive.
* @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>.
* @param certificate the {@link X509Certificate} used to sign the archive, or
* <code>null</code>.
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public SignedJarBuilder(@NonNull OutputStream out,
@Nullable PrivateKey key,
@Nullable X509Certificate certificate,
@Nullable String builtBy,
@Nullable String createdBy)
throws IOException, NoSuchAlgorithmException {
mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
mOutputJar.setLevel(9);
mKey = key;
mCertificate = certificate;
if (mKey != null && mCertificate != null) {
mManifest = new Manifest();
Attributes main = mManifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
if (builtBy != null) {
main.putValue("Built-By", builtBy);
}
if (createdBy != null) {
main.putValue("Created-By", createdBy);
}
mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
}
}
public void testExportPackage() throws Exception {
Attributes attr = new Attributes();
attr.putValue("Bundle-SymbolicName", "javaewah.dummy;singleton:=true");
attr.putValue("Bundle-Version", "0.5.6");
//attr.putValue("Bundle-Name", "%OpenIDE-Module-Name");
//attr.putValue("Bundle-Category", "%OpenIDE-Module-Display-Category");
//attr.putValue("Bundle-Description", "%OpenIDE-Module-Short-Description");
// As generated by JarWithModuleAttributes:
attr.putValue("Export-Package", "javaewah;version=0.5.6");
Properties localization = new Properties();
localization.setProperty("OpenIDE-Module-Name", "My Bundle");
localization.setProperty("OpenIDE-Module-Display-Category", "hello");
localization.setProperty("OpenIDE-Module-Short-Description", "Hello there!");
Element e = MakeUpdateDesc.fakeOSGiInfoXml(attr, localization, new File(getWorkDir(), "something/some.jar"));
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLUtil.write(e, baos);
assertEquals("<module codenamebase='javaewah.dummy' "
+ "distribution='' downloadsize='0' targetcluster='something'>"
+ " <manifest AutoUpdate-Show-In-Client='false' OpenIDE-Module='javaewah.dummy'"
+ " OpenIDE-Module-Name='javaewah.dummy'"
+ " OpenIDE-Module-Provides='javaewah'"
+ " OpenIDE-Module-Specification-Version='0.5.6'/>"
+ " </module> ", baos.toString().replace('"', '\'').replaceAll("\\s+", " "));
}
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(CAN_REDEFINE_CLASSES, "true");
global.putValue(CAN_SET_NATIVE_METHOD, "true");
try (JarOutputStream jos = new JarOutputStream(fos, m)) {
addClass(HotSwapAgent.class, jos);
addClass(CodeCoverageStore.class, jos);
addClass(InvokeReceiver.class, jos);
}
}
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();
}
/**
* java.util.jar.Attributes#equals(java.lang.Object)
*/
public void test_equalsLjava_lang_Object() {
Attributes.Name n1 = new Attributes.Name("name"), n2 = new Attributes.Name("Name");
assertEquals(n1, n2);
Attributes a1 = new Attributes();
a1.putValue("one", "1");
a1.putValue("two", "2");
Attributes a2 = new Attributes();
a2.putValue("One", "1");
a2.putValue("TWO", "2");
assertEquals(a1, a2);
assertEquals(a1, a1);
a2 = null;
assertFalse(a1.equals(a2));
}
private Iterable<Entry> jarManifestSource(MavenProject project) throws IOException {
Manifest manifest = new Manifest();
Attributes main = manifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
main.putValue("Archiver-Version", "Provisio Archiver");
main.putValue("Created-By", "Takari Inc.");
main.putValue("Built-By", System.getProperty("user.name"));
main.putValue("Build-Jdk", System.getProperty("java.version"));
main.putValue("Specification-Title", project.getArtifactId());
main.putValue("Specification-Version", project.getVersion());
main.putValue("Implementation-Title", project.getArtifactId());
main.putValue("Implementation-Version", project.getVersion());
main.putValue("Implementation-Vendor-Id", project.getGroupId());
if (archive != null && archive.getManifestEntries() != null) {
for (Map.Entry<String, String> extra : archive.getManifestEntries().entrySet()) {
if (extra.getValue() != null) {
main.putValue(extra.getKey(), extra.getValue());
}
}
}
File manifestFile = new File(project.getBuild().getDirectory(), "MANIFEST.MF");
if (!manifestFile.getParentFile().exists()) {
manifestFile.getParentFile().mkdirs();
}
ByteArrayOutputStream buf = new ByteArrayOutputStream();
manifest.write(buf);
return singleton((Entry) new BytesEntry(MANIFEST_PATH, buf.toByteArray()));
}
@Override
protected void setUp() {
a = new Attributes();
a.putValue("1", "one");
a.putValue("2", "two");
a.putValue("3", "three");
a.putValue("4", "four");
}
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;
}
private void handleDisplayAttribute(Properties props, Attributes netbeans, Attributes osgi, String netbeansHeader, String osgiHeader) throws IOException {
String val = netbeans.getValue(netbeansHeader);
if (val != null) {
osgi.putValue(osgiHeader, val);
} else if (props.containsKey(netbeansHeader)) {
osgi.putValue(osgiHeader, "%" + netbeansHeader);
}
}
private void processFragment(File fragment) throws Exception {
String cnb = findFragmentHost(fragment);
File bundleFile = new File(destdir, fragment.getName());
if (bundleFile.lastModified() > fragment.lastModified()) {
log("Skipping " + fragment + " since " + bundleFile + " is newer", Project.MSG_VERBOSE);
return;
}
log("Processing " + fragment + " into " + bundleFile);
Manifest mf = new Manifest();
Attributes attr = mf.getMainAttributes();
attr.putValue("Manifest-Version", "1.0"); // workaround for JDK bug
attr.putValue("Bundle-ManifestVersion", "2");
attr.putValue("Bundle-SymbolicName", cnb + "-branding");
attr.putValue("Fragment-Host", cnb);
try (JarFile jar = new JarFile(fragment);
OutputStream bundle = new FileOutputStream(bundleFile);
ZipOutputStream zos = new JarOutputStream(bundle, mf)) {
Set<String> parents = new HashSet<>();
Enumeration<? extends ZipEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = entries.nextElement();
String path = entry.getName();
if (path.endsWith("/") || path.equals("META-INF/MANIFEST.MF")) {
continue;
} try (InputStream is = jar.getInputStream(entry)) {
writeEntry(zos, path, is, parents);
}
}
zos.finish();
}
}
private Manifest updateManifest(Manifest manifest) {
Attributes mainAttributes = manifest.getMainAttributes();
String reqs = mainAttributes.getValue(REQUIRE_CAPABILITY);
reqs = getAndroidRequirement(reqs);
mainAttributes.putValue(REQUIRE_CAPABILITY, reqs);
Manifest res = new Manifest();
res.getMainAttributes().putAll(mainAttributes);
return res;
}
private Attributes getDigestAttributes(
ZipEntry ze, ZipFile zf, MessageDigest[] digests)
throws IOException {
String[] base64Digests = getDigests(ze, zf, digests);
Attributes attrs = new Attributes();
for (int i = 0; i < digests.length; i++) {
attrs.putValue(digests[i].getAlgorithm() + "-Digest",
base64Digests[i]);
}
return attrs;
}
/**
* Creates a {@link SignedJarBuilder} with a given output stream, and signing information.
* <p/>If either <code>key</code> or <code>certificate</code> is <code>null</code> then
* the archive will not be signed.
*
* @param out the {@link OutputStream} where to write the Jar archive.
* @param key the {@link PrivateKey} used to sign the archive, or <code>null</code>.
* @param certificate the {@link X509Certificate} used to sign the archive, or
* <code>null</code>.
* @throws IOException
* @throws NoSuchAlgorithmException
*/
public LocalSignedJarBuilder(@NonNull OutputStream out,
@Nullable PrivateKey key,
@Nullable X509Certificate certificate,
@Nullable String builtBy,
@Nullable String createdBy,
@Nullable String signFile) throws IOException, NoSuchAlgorithmException {
mOutputJar = new JarOutputStream(new BufferedOutputStream(out));
mOutputJar.setLevel(9);
mKey = key;
mCertificate = certificate;
mSignFile = signFile;
if (mKey != null && mCertificate != null) {
mManifest = new Manifest();
Attributes main = mManifest.getMainAttributes();
main.putValue("Manifest-Version", "1.0");
if (builtBy != null) {
main.putValue("Built-By", builtBy);
}
if (createdBy != null) {
main.putValue("Created-By", createdBy);
}
mMessageDigest = MessageDigest.getInstance(DIGEST_ALGORITHM);
}
}
private void updateManifest(int manifestIndex, String inName, String outName, MessageDigest[] digests)
{
// Create fresh section for entry, and enter "Name" header
Manifest nm = newManifest[manifestIndex];
Manifest om = oldManifest[manifestIndex];
Attributes oldAtts = om.getAttributes(inName);
Attributes newAtts = new Attributes();
//newAtts.putValue(MANIFEST_NAME_TAG, outName);
// copy over non-name and none digest entries
if (oldAtts != null){
for(Iterator it = oldAtts.entrySet().iterator(); it.hasNext();){
Map.Entry entry = (Map.Entry) it.next();
Object key = entry.getKey();
String name = key.toString();
if (!name.equalsIgnoreCase(MANIFEST_NAME_TAG) &&
name.indexOf("Digest") == -1){
newAtts.remove(name);
newAtts.putValue(name, (String)entry.getValue());
}
}
}
// Create fresh digest entries in the new section
if (digests != null && digests.length > 0)
{
// Digest-Algorithms header
StringBuffer sb = new StringBuffer();
for (int i = 0; i < digests.length; i++)
{
sb.append(digests[i].getAlgorithm());
if (i < digests.length -1){
sb.append(", ");
}
}
newAtts.remove(MANIFEST_DIGESTALG_TAG);
newAtts.putValue(MANIFEST_DIGESTALG_TAG, sb.toString());
// *-Digest headers
for (int i = 0; i < digests.length; i++)
{
newAtts.remove(digests[i].getAlgorithm() + "-Digest");
newAtts.putValue(digests[i].getAlgorithm() + "-Digest", Tools.toBase64(digests[i].digest()));
}
}
if (!newAtts.isEmpty()) {
// Append the new section to the new manifest
nm.getEntries().put(outName, newAtts);
}
}
private static void merge(Attributes attributes, Attributes others) {
for (final Map.Entry<?, ?> entry : others.entrySet()) {
attributes.putValue(entry.getKey().toString(), entry.getValue().toString());
}
}