Example usage for java.util.jar Attributes putValue

List of usage examples for java.util.jar Attributes putValue

Introduction

In this page you can find the example usage for java.util.jar Attributes putValue.

Prototype

public String putValue(String name, String value) 

Source Link

Document

Associates the specified value with the specified attribute name, specified as a String.

Usage

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);/*  ww  w .  j  a  va2  s .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.apatch.MergePatch.java

private void fillManifest(Attributes main) throws IOException {
    JarFile jarFile;//from   www.j  a v  a 2 s  .co  m
    Manifest manifest;
    StringBuffer fromBuffer = new StringBuffer();
    StringBuffer toBuffer = new StringBuffer();
    String from;
    String to;
    String name;
    // String classes;
    for (File file : patchs) {
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("META-INF/PATCH.MF");
        manifest = new Manifest(jarFile.getInputStream(dexEntry));
        Attributes attributes = manifest.getMainAttributes();

        from = attributes.getValue("From-File");
        if (fromBuffer.length() > 0) {
            fromBuffer.append(',');
        }
        fromBuffer.append(from);
        to = attributes.getValue("To-File");
        if (toBuffer.length() > 0) {
            toBuffer.append(',');
        }
        toBuffer.append(to);

        name = attributes.getValue("Patch-Name");
        // classes = attributes.getValue(name + "-Patch-Classes");
        main.putValue(name + "-Patch-Classes", attributes.getValue(name + "-Patch-Classes"));
        main.putValue(name + "-Prepare-Classes", attributes.getValue(name + "-Prepare-Classes"));
        main.putValue(name + "-Used-Methods", attributes.getValue(name + "-Used-Methods"));
        main.putValue(name + "-Modified-Classes", attributes.getValue(name + "-Modified-Classes"));
        main.putValue(name + "-Used-Classes", attributes.getValue(name + "-Used-Classes"));
        main.putValue(name + "-add-classes", attributes.getValue(name + "-add-classes"));

    }
    main.putValue("From-File", fromBuffer.toString());
    main.putValue("To-File", toBuffer.toString());
}

From source file:com.android.builder.internal.packaging.sign.SignatureExtension.java

/**
 * Reads the signature file (if any) on the zip file.
 * <p>//w  w w.j a  v  a 2  s .  c  om
 * When this method terminates, we have the following guarantees:
 * <ul>
 *      <li>An internal signature manifest exists.</li>
 *      <li>All entries in the in-memory signature file exist in the zip file.</li>
 *      <li>All entries in the zip file (with the exception of the signature-related files,
 *      as specified by https://docs.oracle.com/javase/7/docs/technotes/guides/jar/jar.html)
 *      exist in the in-memory signature file.</li>
 *      <li>All entries in the in-memory signature file have digests that match their
 *      contents in the zip.</li>
 *      <li>All entries in the in-memory signature manifest exist also in the manifest file
 *      and the digests are the same.</li>
 *      <li>The main attributes of the in-memory signature manifest are valid. The manifest's
 *      digest has not been verified and may not even exist.</li>
 *      <li>If the internal in-memory signature manifest differs in any way from the one
 *      written in the file, {@link #mDirty} will be set to {@code true}. Otherwise,
 *      {@link #mDirty} will be set to {@code false}.</li>
 * </ul>
 *
 * @throws IOException failed to read the signature file
 */
private void readSignatureFile() throws IOException {
    boolean needsNewSignature = false;

    StoredEntry signatureEntry = mManifestExtension.zFile().get(SIGNATURE_FILE);
    if (signatureEntry != null) {
        byte[] signatureData = signatureEntry.read();
        mSignatureFile.read(new ByteArrayInputStream(signatureData));

        Attributes mainAttrs = mSignatureFile.getMainAttributes();
        String versionName = mainAttrs.getValue(SIGNATURE_VERSION_NAME);
        String createdBy = mainAttrs.getValue(SIGNATURE_CREATED_BY_NAME);
        String apkSigned = mainAttrs.getValue(SIGNATURE_ANDROID_APK_SIGNED_NAME);

        if (!SIGNATURE_VERSION_VALUE.equals(versionName) || !SIGNATURE_CREATED_BY_VALUE.equals(createdBy)
                || mainAttrs.get(mDigestAlgorithm.manifestAttributeName) != null
                || !Objects.equal(mApkSignedHeaderValue, apkSigned)) {
            needsNewSignature = true;
        }
    } else {
        needsNewSignature = true;
    }

    if (needsNewSignature) {
        Attributes mainAttrs = mSignatureFile.getMainAttributes();

        mainAttrs.putValue(SIGNATURE_CREATED_BY_NAME, SIGNATURE_CREATED_BY_VALUE);
        mainAttrs.putValue(SIGNATURE_VERSION_NAME, SIGNATURE_VERSION_VALUE);
        if (mApkSignedHeaderValue != null) {
            mainAttrs.putValue(SIGNATURE_ANDROID_APK_SIGNED_NAME, mApkSignedHeaderValue);
        } else {
            mainAttrs.remove(SIGNATURE_ANDROID_APK_SIGNED_NAME);
        }

        mDirty = true;
    }

    /*
     * At this point we have a valid in-memory signature file with a valid header. mDirty
     * states whether this is the same as the file-based signature file.
     *
     * Now, check we have the same files in the zip as in the signature file and that all
     * digests match. While we do this, make sure the manifest is also up-do-date.
     *
     * We ignore all signature-related files that exist in the zip that are signature-related.
     * This are defined in the jar format specification.
     */
    Set<StoredEntry> allEntries = mManifestExtension.zFile().entries().stream()
            .filter(se -> !isIgnoredFile(se.getCentralDirectoryHeader().getName())).collect(Collectors.toSet());

    Set<String> sigEntriesToRemove = Sets.newHashSet(mSignatureFile.getEntries().keySet());
    Set<String> manEntriesToRemove = Sets.newHashSet(mManifestExtension.allEntries().keySet());
    for (StoredEntry se : allEntries) {
        /*
         * Update the entry's digest, if needed.
         */
        setDigestForEntry(se);

        /*
         * This entry exists in the file, so remove it from the list of entries to remove
         * from the manifest and signature file.
         */
        sigEntriesToRemove.remove(se.getCentralDirectoryHeader().getName());
        manEntriesToRemove.remove(se.getCentralDirectoryHeader().getName());
    }

    for (String toRemoveInSignature : sigEntriesToRemove) {
        mSignatureFile.getEntries().remove(toRemoveInSignature);
        mDirty = true;
    }

    for (String toRemoveInManifest : manEntriesToRemove) {
        mManifestExtension.removeEntry(toRemoveInManifest);
    }
}

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

public void addDigestAttribute(Attributes attrs, ArtifactData file) throws IOException {
    attrs.putValue(m_digestAlg.concat("-Digest"), calculateDigest(file));
}

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 ww  w.ja va 2  s .co  m
        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.felix.deploymentadmin.itest.util.DPSigner.java

private Attributes getDigestAttributes(byte[] rawData) throws IOException {
    Attributes attrs = new Attributes();
    attrs.putValue(m_digestAlg + "-Digest", calculateDigest(rawData));
    return attrs;
}

From source file:org.apache.sling.maven.slingstart.PreparePackageMojo.java

private Manifest getRunModesManifest(Feature feature) throws MojoExecutionException {
    Map<String, StringBuilder> runModes = new HashMap<>();

    for (RunMode rm : feature.getRunModes()) {
        for (ArtifactGroup ag : rm.getArtifactGroups()) {
            int startOrder = ag.getStartLevel(); // For subsystems the start level on the artifact group is used as start order.

            for (org.apache.sling.provisioning.model.Artifact a : ag) {
                Artifact artifact = ModelUtils.getArtifact(this.project, this.mavenSession,
                        this.artifactHandlerManager, this.resolver, a.getGroupId(), a.getArtifactId(),
                        a.getVersion(), a.getType(), a.getClassifier());
                File artifactFile = artifact.getFile();
                String entryName = getEntryName(artifactFile, startOrder);

                String[] runModeNames = rm.getNames();
                if (runModeNames == null)
                    runModeNames = new String[] { ALL_RUNMODES_KEY };

                for (String runModeName : runModeNames) {
                    StringBuilder sb = runModes.get(runModeName);
                    if (sb == null) {
                        sb = new StringBuilder();
                        runModes.put(runModeName, sb);
                    } else {
                        sb.append('|');
                    }//w w  w  .  j  a va2s.  c o m

                    sb.append(entryName);
                }
            }
        }
    }

    Manifest mf = new Manifest();
    Attributes attrs = mf.getMainAttributes();
    attrs.putValue("Manifest-Version", "1.0"); // Manifest does not work without this value
    attrs.putValue("About-This-Manifest",
            "This is not a real manifest, it is used as information when this archive is transformed into a real subsystem .esa file");
    for (Map.Entry<String, StringBuilder> entry : runModes.entrySet()) {
        attrs.putValue(entry.getKey().replace(':', '_'), entry.getValue().toString());
    }
    return mf;
}

From source file:org.apache.sling.maven.slingstart.PreparePackageMojo.java

private int createSubsystemManifest(Feature feature, Map<String, Integer> startOrderMap, ZipOutputStream os)
        throws IOException {
    int subsystemStartLevel = -1;
    ZipEntry ze = new ZipEntry("SUBSYSTEM-MANIFEST-BASE.MF");
    try {/*  w  w  w .ja  v a 2s.c o  m*/
        os.putNextEntry(ze);

        Manifest mf = new Manifest();
        Attributes attributes = mf.getMainAttributes();
        attributes.putValue("Manifest-Version", "1.0"); // Manifest does not work without this value
        attributes.putValue("Subsystem-SymbolicName", feature.getName());
        attributes.putValue("Subsystem-Version", "1"); // Version must be an integer (cannot be a long), TODO better idea?
        attributes.putValue("Subsystem-Type", feature.getType());
        for (Section section : feature.getAdditionalSections("subsystem-manifest")) {
            String sl = section.getAttributes().get("startLevel");
            try {
                subsystemStartLevel = Integer.parseInt(sl);
            } catch (NumberFormatException nfe) {
                // Not a valid start level
            }

            BufferedReader br = new BufferedReader(new StringReader(section.getContents()));
            String line = null;
            while ((line = br.readLine()) != null) {
                int idx = line.indexOf(':');
                if (idx > 0) {
                    String key = line.substring(0, idx);
                    String value;
                    idx++;
                    if (line.length() > idx)
                        value = line.substring(idx);
                    else
                        value = "";
                    attributes.putValue(key.trim(), value.trim());
                }
            }
        }
        mf.write(os);
    } finally {
        os.closeEntry();
    }

    return subsystemStartLevel;
}

From source file:org.apache.sysml.utils.lite.BuildLite.java

/**
 * Build a lite jar based on the consolidated class names.
 * /*  ww  w . j  a  va2 s.  co  m*/
 * @param consolidateClassPathNames
 *            the consolidated class names
 * @throws IOException
 *             if an IOException occurs
 */
private static void createJarFromConsolidatedClassPathNames(Set<String> consolidateClassPathNames)
        throws IOException {
    System.out.println("\nCreating " + liteJarLocation + " file");
    ClassLoader cl = BuildLite.class.getClassLoader();

    Manifest mf = new Manifest();
    Attributes attr = mf.getMainAttributes();
    attr.putValue("" + Attributes.Name.MANIFEST_VERSION, "1.0");

    File file = new File(liteJarLocation);
    try (FileOutputStream fos = new FileOutputStream(file);
            JarOutputStream jos = new JarOutputStream(fos, mf)) {
        int numFilesWritten = 0;
        for (String classPathName : consolidateClassPathNames) {
            writeMessage(classPathName, ++numFilesWritten);
            InputStream is = cl.getResourceAsStream(classPathName);
            byte[] bytes = IOUtils.toByteArray(is);

            JarEntry je = new JarEntry(classPathName);
            jos.putNextEntry(je);
            jos.write(bytes);
        }

        writeIdentifierFileToLiteJar(jos, ++numFilesWritten);
        writeAdditionalResourcesToJar(jos, numFilesWritten);
    }

}

From source file:org.eclipse.birt.build.mavenrepogen.RepoGen.java

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);//from   w w w.ja  v a 2s .c o m
        final FileInputStream fis = new FileInputStream(file);
        pipeStream(fis, jos);
        fis.close();
    }
    jos.close();
}