Java Code Examples for java.util.jar.Attributes#putValue()

The following examples show how to use java.util.jar.Attributes#putValue() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: DeterministicManifestTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example 2
Source File: ViewservletRepoGen.java    From birt with Eclipse Public License 1.0 6 votes vote down vote up
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();
}
 
Example 3
Source File: JarCreatingJarFinder.java    From pitest with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example 4
Source File: MakeUpdateDescTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
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+", " "));
}
 
Example 5
Source File: SignedJarBuilder.java    From javaide with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 6
Source File: RedefineClassTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
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);
    }
}
 
Example 7
Source File: MRJarWarning.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 6 votes vote down vote up
@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);
}
 
Example 8
Source File: SignedJarBuilder.java    From java-n-IDE-for-Android with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 9
Source File: AndroidResourceOutputs.java    From bazel with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example 10
Source File: AttributesTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * 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));
}
 
Example 11
Source File: Jar.java    From takari-lifecycle with Eclipse Public License 1.0 5 votes vote down vote up
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()));
}
 
Example 12
Source File: OldAttributesTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
@Override
protected void setUp() {
    a = new Attributes();
    a.putValue("1", "one");
    a.putValue("2", "two");
    a.putValue("3", "three");
    a.putValue("4", "four");
}
 
Example 13
Source File: MRJARCachingFileManagerTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 14
Source File: MakeOSGi.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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);
    }
}
 
Example 15
Source File: MakeOSGi.java    From netbeans with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example 16
Source File: Dexifier.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
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;
}
 
Example 17
Source File: JarSigner.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
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;
}
 
Example 18
Source File: LocalSignedJarBuilder.java    From atlas with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 19
Source File: JkManifest.java    From jeka with Apache License 2.0 4 votes vote down vote up
private static void merge(Attributes attributes, Attributes others) {
    for (final Map.Entry<?, ?> entry : others.entrySet()) {
        attributes.putValue(entry.getKey().toString(), entry.getValue().toString());
    }
}
 
Example 20
Source File: GuardDB.java    From yGuard with MIT License 4 votes vote down vote up
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);
  }
}