Example usage for java.util.jar Manifest getEntries

List of usage examples for java.util.jar Manifest getEntries

Introduction

In this page you can find the example usage for java.util.jar Manifest getEntries.

Prototype

public Map<String, Attributes> getEntries() 

Source Link

Document

Returns a Map of the entries contained in this Manifest.

Usage

From source file:com.facebook.buck.java.JarDirectoryStepTest.java

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());
    }/*from w  w w  . ja  v  a2s  .  c om*/
    manifest.getEntries().put("example", attrs);
    return manifest;
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

@Test
public void shouldMergeManifestsIfAsked() throws IOException {
    Manifest fromJar = createManifestWithExampleSection(ImmutableMap.of("Not-Seen", "ever"));
    Manifest fromUser = createManifestWithExampleSection(ImmutableMap.of("cake", "cheese"));

    Manifest seenManifest = jarDirectoryAndReadManifest(fromJar, fromUser, true);

    Manifest expectedManifest = new Manifest(fromJar);
    Attributes attrs = new Attributes();
    attrs.putValue("Not-Seen", "ever");
    attrs.putValue("cake", "cheese");
    expectedManifest.getEntries().put("example", attrs);
    assertEquals(expectedManifest.getEntries(), seenManifest.getEntries());
}

From source file:com.facebook.buck.jvm.java.JarDirectoryStepTest.java

/**
 * From the constructor of {@link JarInputStream}:
 * <p>/*from  ww w . j  a v  a2  s  . c o  m*/
 * This implementation assumes the META-INF/MANIFEST.MF entry
 * should be either the first or the second entry (when preceded
 * by the dir META-INF/). It skips the META-INF/ and then
 * "consumes" the MANIFEST.MF to initialize the Manifest object.
 * <p>
 * A simple implementation of {@link JarDirectoryStep} would iterate over all entries to be
 * included, adding them to the output jar, while merging manifest files, writing the merged
 * manifest as the last item in the jar. That will generate jars the {@code JarInputStream} won't
 * be able to find the manifest for.
 */
@Test
public void manifestShouldBeSecondEntryInJar() throws IOException {
    Path manifestPath = Paths.get(JarFile.MANIFEST_NAME);

    // Create a directory with a manifest in it and more than two files.
    Path dir = folder.newFolder();
    Manifest dirManifest = new Manifest();
    Attributes attrs = new Attributes();
    attrs.putValue("From-Dir", "cheese");
    dirManifest.getEntries().put("Section", attrs);

    Files.createDirectories(dir.resolve(manifestPath).getParent());
    try (OutputStream out = Files.newOutputStream(dir.resolve(manifestPath))) {
        dirManifest.write(out);
    }
    Files.write(dir.resolve("A.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("B.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("aa.txt"), "hello world".getBytes(UTF_8));
    Files.write(dir.resolve("bb.txt"), "hello world".getBytes(UTF_8));

    // Create a jar with a manifest and more than two other files.
    Path inputJar = folder.newFile("example.jar");
    try (ZipOutputStream zos = new ZipOutputStream(Files.newOutputStream(inputJar))) {
        byte[] data = "hello world".getBytes(UTF_8);
        ZipEntry entry = new ZipEntry("C.txt");
        zos.putNextEntry(entry);
        zos.write(data, 0, data.length);
        zos.closeEntry();

        entry = new ZipEntry("cc.txt");
        zos.putNextEntry(entry);
        zos.write(data, 0, data.length);
        zos.closeEntry();

        entry = new ZipEntry("META-INF/");
        zos.putNextEntry(entry);
        zos.closeEntry();

        // Note: at end of the stream. Technically invalid.
        entry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(entry);
        Manifest zipManifest = new Manifest();
        attrs = new Attributes();
        attrs.putValue("From-Zip", "peas");
        zipManifest.getEntries().put("Section", attrs);
        zipManifest.write(zos);
        zos.closeEntry();
    }

    // Merge and check that the manifest includes everything
    Path output = folder.newFile("output.jar");
    JarDirectoryStep step = new JarDirectoryStep(new FakeProjectFilesystem(folder.getRoot()), output,
            ImmutableSortedSet.of(dir, inputJar), null, null);
    int exitCode = step.execute(TestExecutionContext.newInstance()).getExitCode();

    assertEquals(0, exitCode);

    Manifest manifest;
    try (InputStream is = Files.newInputStream(output); JarInputStream jis = new JarInputStream(is)) {
        manifest = jis.getManifest();
    }

    assertNotNull(manifest);
    Attributes readAttributes = manifest.getAttributes("Section");
    assertEquals(2, readAttributes.size());
    assertEquals("cheese", readAttributes.getValue("From-Dir"));
    assertEquals("peas", readAttributes.getValue("From-Zip"));
}

From source file:com.jrummyapps.busybox.signing.ZipSigner.java

/** Add the SHA1 of every file to the manifest, creating it if necessary. */
private static Manifest addDigestsToManifest(final JarFile jar) throws IOException, GeneralSecurityException {
    final Manifest input = jar.getManifest();
    final Manifest output = new Manifest();

    final Attributes main = output.getMainAttributes();
    main.putValue("Manifest-Version", MANIFEST_VERSION);
    main.putValue("Created-By", CREATED_BY);

    // We sort the input entries by name, and add them to the output manifest in sorted order.
    // We expect that the output map will be deterministic.
    final TreeMap<String, JarEntry> byName = new TreeMap<>();
    for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements();) {
        JarEntry entry = e.nextElement();
        byName.put(entry.getName(), entry);
    }/*from www .j  a  va  2s .c  o  m*/

    final MessageDigest md = MessageDigest.getInstance("SHA1");
    final byte[] buffer = new byte[4096];
    int num;

    for (JarEntry entry : byName.values()) {
        final String name = entry.getName();
        if (!entry.isDirectory() && !name.equals(JarFile.MANIFEST_NAME) && !name.equals(CERT_SF_NAME)
                && !name.equals(CERT_RSA_NAME)) {
            InputStream data = jar.getInputStream(entry);
            while ((num = data.read(buffer)) > 0) {
                md.update(buffer, 0, num);
            }

            Attributes attr = null;
            if (input != null) {
                attr = input.getAttributes(name);
            }
            attr = attr != null ? new Attributes(attr) : new Attributes();
            attr.putValue("SHA1-Digest", base64encode(md.digest()));
            output.getEntries().put(name, attr);
        }
    }

    return output;
}

From source file:com.facebook.buck.jvm.java.DefaultJavaLibraryIntegrationTest.java

@Test
public void shouldIncludeUserSuppliedManifestIfProvided() throws IOException {
    setUpProjectWorkspaceForScenario("manifest");

    Manifest m = new Manifest();
    Attributes attrs = new Attributes();
    attrs.putValue("Data", "cheese");
    m.getEntries().put("Example", attrs);
    m.write(System.out);//from   ww w  . j  a v  a 2s  .  c o m

    Path path = workspace.buildAndReturnOutput("//:library");

    try (InputStream is = Files.newInputStream(path); JarInputStream jis = new JarInputStream(is)) {
        Manifest manifest = jis.getManifest();
        String value = manifest.getEntries().get("Example").getValue("Data");
        assertEquals("cheese", value);
    }
}

From source file:com.taobao.android.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Writes a .SF file with a digest to the manifest.
 *//*from  w w w  . ja v  a2 s  .co  m*/
private void writeSignatureFile(OutputStream out) throws IOException, GeneralSecurityException {
    Manifest sf = new Manifest();
    Attributes main = sf.getMainAttributes();
    main.putValue("Signature-Version", "1.0");
    main.putValue("Created-By", "1.0 (Android)");

    MessageDigest md = MessageDigest.getInstance(DIGEST_ALGORITHM);
    PrintStream print = new PrintStream(new DigestOutputStream(new ByteArrayOutputStream(), md), true,
            SdkConstants.UTF_8);

    // Digest of the entire manifest
    mManifest.write(print);
    print.flush();
    main.putValue(DIGEST_MANIFEST_ATTR, new String(Base64.encode(md.digest()), "ASCII"));

    Map<String, Attributes> entries = mManifest.getEntries();
    for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
        // Digest of the manifest stanza for this entry.
        print.print("Name: " + entry.getKey() + "\r\n");
        for (Map.Entry<Object, Object> att : entry.getValue().entrySet()) {
            print.print(att.getKey() + ": " + att.getValue() + "\r\n");
        }
        print.print("\r\n");
        print.flush();

        Attributes sfAttr = new Attributes();
        sfAttr.putValue(DIGEST_ATTR, new String(Base64.encode(md.digest()), "ASCII"));
        sf.getEntries().put(entry.getKey(), sfAttr);
    }
    CountOutputStream cout = new CountOutputStream(out);
    sf.write(cout);

    // A bug in the java.util.jar implementation of Android platforms
    // up to version 1.6 will cause a spurious IOException to be thrown
    // if the length of the signature file is a multiple of 1024 bytes.
    // As a workaround, add an extra CRLF in this case.
    if ((cout.size() % 1024) == 0) {
        cout.write('\r');
        cout.write('\n');
    }
}

From source file:org.apache.felix.deploymentadmin.itest.util.DPSigner.java

private Manifest createSignatureFile(Manifest manifest) throws IOException {
    byte[] mfRawBytes;
    try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
        manifest.write(baos);/*from   w  ww  .j  av a 2 s  .c  om*/
        mfRawBytes = baos.toByteArray();
    }

    Manifest sf = new Manifest();
    Attributes sfMain = sf.getMainAttributes();
    Map<String, Attributes> sfEntries = sf.getEntries();

    sfMain.put(Attributes.Name.SIGNATURE_VERSION, "1.0");
    sfMain.putValue("Created-By", "Apache Felix DeploymentPackageBuilder");
    sfMain.putValue(m_digestAlg + "-Digest-Manifest", calculateDigest(mfRawBytes));
    sfMain.putValue(m_digestAlg + "-Digest-Manifest-Main-Attribute",
            calculateDigest(getRawBytesMainAttributes(manifest)));

    for (Entry<String, Attributes> entry : manifest.getEntries().entrySet()) {
        String name = entry.getKey();
        byte[] entryData = getRawBytesAttributes(entry.getValue());

        sfEntries.put(name, getDigestAttributes(entryData));
    }
    return sf;
}

From source file:org.apache.pig.tools.pigstats.ScriptState.java

public String getPigVersion() {
    if (pigVersion == null) {
        String findContainingJar = JarManager.findContainingJar(ScriptState.class);
        if (findContainingJar != null) {
            try {
                JarFile jar = new JarFile(findContainingJar);
                final Manifest manifest = jar.getManifest();
                final Map<String, Attributes> attrs = manifest.getEntries();
                Attributes attr = attrs.get("org/apache/pig");
                pigVersion = attr.getValue("Implementation-Version");
            } catch (Exception e) {
                LOG.warn("unable to read pigs manifest file");
            }//from  w ww .j a  v a  2s  .  co m
        } else {
            LOG.warn("unable to read pigs manifest file. Not running from the Pig jar");
        }
    }
    return (pigVersion == null) ? "" : pigVersion;
}

From source file:org.argouml.moduleloader.ModuleLoader2.java

/**
 * Check a jar file for an ArgoUML extension/module.
 * <p>//  www.ja v a2  s  .  com
 *
 * If there isn't a manifest or it isn't readable, we fall back to using the
 * raw JAR entries.
 *
 * @param classloader
 *            The classloader to use.
 * @param file
 *            The file to process.
 * @throws ClassNotFoundException
 *             if the manifest file contains a class that doesn't exist.
 */
private void processJarFile(ClassLoader classloader, File file) throws ClassNotFoundException {

    LOG.log(Level.INFO, "Opening jar file {0}", file);
    JarFile jarfile = null;
    try {
        jarfile = new JarFile(file);
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to open " + file, e);
        return;
    } finally {
        IOUtils.closeQuietly(jarfile);
    }

    Manifest manifest;
    try {
        manifest = jarfile.getManifest();
        if (manifest == null) {
            // We expect all extensions to have a manifest even though we
            // can operate without one if necessary.
            LOG.log(Level.WARNING, file + " does not have a manifest");
        }
    } catch (IOException e) {
        LOG.log(Level.SEVERE, "Unable to read manifest of " + file, e);
        return;
    }

    // TODO: It is a performance drain to load all classes at startup time.
    // They should be lazy loaded when needed. Instead of scanning all
    // classes for ones which implement our loadable module interface, we
    // should use a manifest entry or a special name/name pattern that we
    // look for to find the single main module class to load here. - tfm

    boolean loadedClass = false;
    if (manifest == null) {
        Enumeration<JarEntry> jarEntries = jarfile.entries();
        while (jarEntries.hasMoreElements()) {
            JarEntry entry = jarEntries.nextElement();
            loadedClass = loadedClass | processEntry(classloader, entry.getName());
        }
    } else {
        Map<String, Attributes> entries = manifest.getEntries();
        for (String key : entries.keySet()) {
            // Look for our specification
            loadedClass = loadedClass | processEntry(classloader, key);
        }
    }

    // Add this to search list for I18N properties
    // (Done for both modules & localized property file sets)
    Translator.addClassLoader(classloader);

    // If it didn't have a loadable module class and it doesn't look like
    // a localized property set, warn the user that something funny is in
    // their extension directory
    if (!loadedClass && !file.getName().contains("argouml-i18n-")) {
        LOG.log(Level.SEVERE, "Failed to find any loadable ArgoUML modules in jar " + file);
    }
}

From source file:org.docx4j.jaxb.Context.java

public static void searchManifestsForJAXBImplementationInfo(ClassLoader loader) {
    Enumeration resEnum;//from  w w  w.j a  va  2  s. c  o  m
    try {
        resEnum = loader.getResources(JarFile.MANIFEST_NAME);
        while (resEnum.hasMoreElements()) {
            InputStream is = null;
            try {
                URL url = (URL) resEnum.nextElement();
                //                   System.out.println("\n\n" + url);
                is = url.openStream();
                if (is != null) {
                    Manifest manifest = new Manifest(is);

                    Attributes mainAttribs = manifest.getMainAttributes();
                    String impTitle = mainAttribs.getValue("Implementation-Title");
                    if (impTitle != null && impTitle.contains("JAXB Reference Implementation")
                            || impTitle.contains("org.eclipse.persistence")) {

                        log.info("\n" + url);
                        for (Object key2 : mainAttribs.keySet()) {

                            log.info(key2 + " : " + mainAttribs.getValue((java.util.jar.Attributes.Name) key2));
                        }
                    }

                    // In 2.1.3, it is in here
                    for (String key : manifest.getEntries().keySet()) {
                        //System.out.println(key);                       
                        if (key.equals("com.sun.xml.bind.v2.runtime")) {
                            log.info("Found JAXB reference implementation in " + url);
                            mainAttribs = manifest.getAttributes((String) key);

                            for (Object key2 : mainAttribs.keySet()) {
                                log.info(key2 + " : "
                                        + mainAttribs.getValue((java.util.jar.Attributes.Name) key2));
                            }
                        }
                    }

                }
            } catch (Exception e) {
                // Silently ignore 
                //                  log.error(e.getMessage(), e);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    } catch (IOException e1) {
        // Silently ignore 
        //           log.error(e1);
    }

}