Example usage for java.util.jar Attributes getValue

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

Introduction

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

Prototype

public String getValue(Name name) 

Source Link

Document

Returns the value of the specified Attributes.Name, or null if the attribute was not found.

Usage

From source file:org.echocat.nodoodle.classloading.FileClassLoader.java

/**
 * This is a copy of {@link URLClassLoader#getPermissions(CodeSource)}.
 *
 * Defines a new package by name in this ClassLoader. The attributes contained in the specified Manifest will be used to obtain package version and sealing
 * information. For sealed packages, the additional URL specifies the code source URL from which the package was loaded.
 *
 * @param name the package name//ww  w . jav  a  2  s .  c  o  m
 * @param man the Manifest containing package version and sealing information
 * @param url the code source url for the package, or null if none
 * @return the newly defined Package object
 * @throws IllegalArgumentException if the package name duplicates an existing package either in this class loader or one of its ancestors
 */
protected Package definePackage(String name, Manifest man, URL url) throws IllegalArgumentException {
    final String path = name.replace('.', '/').concat("/");
    String specTitle = null;
    String specVersion = null;
    String specVendor = null;
    String implTitle = null;
    String implVersion = null;
    String implVendor = null;
    String sealed = null;
    URL sealBase = null;

    Attributes attr = man.getAttributes(path);
    if (attr != null) {
        specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
        specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
        specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
        implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
        implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
        implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
        sealed = attr.getValue(Name.SEALED);
    }
    attr = man.getMainAttributes();
    if (attr != null) {
        if (specTitle == null) {
            specTitle = attr.getValue(Name.SPECIFICATION_TITLE);
        }
        if (specVersion == null) {
            specVersion = attr.getValue(Name.SPECIFICATION_VERSION);
        }
        if (specVendor == null) {
            specVendor = attr.getValue(Name.SPECIFICATION_VENDOR);
        }
        if (implTitle == null) {
            implTitle = attr.getValue(Name.IMPLEMENTATION_TITLE);
        }
        if (implVersion == null) {
            implVersion = attr.getValue(Name.IMPLEMENTATION_VERSION);
        }
        if (implVendor == null) {
            implVendor = attr.getValue(Name.IMPLEMENTATION_VENDOR);
        }
        if (sealed == null) {
            sealed = attr.getValue(Name.SEALED);
        }
    }
    if ("true".equalsIgnoreCase(sealed)) {
        sealBase = url;
    }
    return definePackage(name, specTitle, specVersion, specVendor, implTitle, implVersion, implVendor,
            sealBase);
}

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");
            }//  w w  w.  ja  va  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: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  o  m
 * 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.sling.maven.slingstart.PreparePackageMojoTest.java

@Test
public void testSubsystemBaseGeneration() throws Exception {
    // Provide the system with some artifacts that are known to be in the local .m2 repo
    // These are explicitly included in the test section of the pom.xml
    PreparePackageMojo ppm = getMojoUnderTest("org.apache.sling/org.apache.sling.commons.classloader/1.3.2",
            "org.apache.sling/org.apache.sling.commons.classloader/1.3.2/app",
            "org.apache.sling/org.apache.sling.commons.contentdetection/1.0.2",
            "org.apache.sling/org.apache.sling.commons.json/2.0.12",
            "org.apache.sling/org.apache.sling.commons.mime/2.1.8",
            "org.apache.sling/org.apache.sling.commons.osgi/2.3.0",
            "org.apache.sling/org.apache.sling.commons.threads/3.2.0");

    try {//from w w w .  java 2s .  c  om
        // The launchpad feature is a prerequisite for the model
        String modelTxt = "[feature name=:launchpad]\n" + "[artifacts]\n"
                + "  org.apache.sling/org.apache.sling.commons.classloader/1.3.2\n" + ""
                + "[feature name=test1 type=osgi.subsystem.composite]\n" + ""
                + "[:subsystem-manifest startLevel=123]\n"
                + "  Subsystem-Description: Extra subsystem headers can go here including very long ones that would span multiple lines in a manifest\n"
                + "  Subsystem-Copyright: (c) 2015 yeah!\n" + "" + "[artifacts]\n"
                + "  org.apache.sling/org.apache.sling.commons.osgi/2.3.0\n" + ""
                + "[artifacts startLevel=10]\n" + "  org.apache.sling/org.apache.sling.commons.json/2.0.12\n"
                + "  org.apache.sling/org.apache.sling.commons.mime/2.1.8\n" + ""
                + "[artifacts startLevel=20 runModes=foo,bar,:blah]\n"
                + "  org.apache.sling/org.apache.sling.commons.threads/3.2.0\n" + ""
                + "[artifacts startLevel=100 runModes=bar]\n"
                + "  org.apache.sling/org.apache.sling.commons.contentdetection/1.0.2\n";
        Model model = ModelReader.read(new StringReader(modelTxt), null);
        ppm.execute(model);

        File generatedFile = new File(ppm.getTmpDir() + "/test1.subsystem-base");
        try (JarFile jf = new JarFile(generatedFile)) {
            // Test META-INF/MANIFEST.MF
            Manifest mf = jf.getManifest();
            Attributes attrs = mf.getMainAttributes();
            String expected = "Potential_Bundles/0/org.apache.sling.commons.osgi-2.3.0.jar|"
                    + "Potential_Bundles/10/org.apache.sling.commons.json-2.0.12.jar|"
                    + "Potential_Bundles/10/org.apache.sling.commons.mime-2.1.8.jar";
            assertEquals(expected, attrs.getValue("_all_"));
            assertEquals("Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar",
                    attrs.getValue("foo"));
            assertEquals(
                    "Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar|"
                            + "Potential_Bundles/100/org.apache.sling.commons.contentdetection-1.0.2.jar",
                    attrs.getValue("bar"));

            // Test SUBSYSTEM-MANIFEST-BASE.MF
            ZipEntry smbZE = jf.getEntry("SUBSYSTEM-MANIFEST-BASE.MF");
            try (InputStream smbIS = jf.getInputStream(smbZE)) {
                Manifest smbMF = new Manifest(smbIS);
                Attributes smbAttrs = smbMF.getMainAttributes();
                assertEquals("test1", smbAttrs.getValue("Subsystem-SymbolicName"));
                assertEquals("osgi.subsystem.composite", smbAttrs.getValue("Subsystem-Type"));
                assertEquals("(c) 2015 yeah!", smbAttrs.getValue("Subsystem-Copyright"));
                assertEquals(
                        "Extra subsystem headers can go here including very long ones "
                                + "that would span multiple lines in a manifest",
                        smbAttrs.getValue("Subsystem-Description"));
            }

            // Test embedded bundles
            File mrr = getMavenRepoRoot();
            File soj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.osgi", "2.3.0");
            ZipEntry sojZE = jf.getEntry("Potential_Bundles/0/org.apache.sling.commons.osgi-2.3.0.jar");
            try (InputStream is = jf.getInputStream(sojZE)) {
                assertArtifactsEqual(soj, is);
            }

            File sjj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.json", "2.0.12");
            ZipEntry sjZE = jf.getEntry("Potential_Bundles/10/org.apache.sling.commons.json-2.0.12.jar");
            try (InputStream is = jf.getInputStream(sjZE)) {
                assertArtifactsEqual(sjj, is);
            }

            File smj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.mime", "2.1.8");
            ZipEntry smjZE = jf.getEntry("Potential_Bundles/10/org.apache.sling.commons.mime-2.1.8.jar");
            try (InputStream is = jf.getInputStream(smjZE)) {
                assertArtifactsEqual(smj, is);
            }

            File stj = getMavenArtifactFile(mrr, "org.apache.sling", "org.apache.sling.commons.threads",
                    "3.2.0");
            ZipEntry stjZE = jf.getEntry("Potential_Bundles/20/org.apache.sling.commons.threads-3.2.0.jar");
            try (InputStream is = jf.getInputStream(stjZE)) {
                assertArtifactsEqual(stj, is);
            }

            File ctj = getMavenArtifactFile(mrr, "org.apache.sling",
                    "org.apache.sling.commons.contentdetection", "1.0.2");
            ZipEntry ctjZE = jf
                    .getEntry("Potential_Bundles/100/org.apache.sling.commons.contentdetection-1.0.2.jar");
            try (InputStream is = jf.getInputStream(ctjZE)) {
                assertArtifactsEqual(ctj, is);
            }
        }
    } finally {
        FileUtils.deleteDirectory(new File(ppm.project.getBuild().getDirectory()));
    }
}

From source file:org.italiangrid.voms.container.Container.java

private void forceTaglibsLoading() {

    if (System.getProperty("voms.disableTaglibsLoading") != null) {
        log.warn("Taglibs loading disabled, as requested by voms.disableTaglibsLoading");
        return;//from  w ww .jav  a  2s  .c  o  m
    }

    try {

        String classpath = java.lang.System.getProperty("java.class.path");
        String entries[] = classpath.split(System.getProperty("path.separator"));

        if (entries.length >= 1) {

            JarFile f = new JarFile(entries[0]);
            Attributes attrs = f.getManifest().getMainAttributes();
            Name n = new Name("Class-Path");
            String jarClasspath = attrs.getValue(n);
            String jarEntries[] = jarClasspath.split(" ");

            boolean taglibsFound = false;

            for (String e : jarEntries) {
                if (e.contains(TAGLIBS_JAR_NAME)) {
                    taglibsFound = true;
                    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();

                    File taglibsJar = new File(e);
                    URLClassLoader newClassLoader = new URLClassLoader(new URL[] { taglibsJar.toURI().toURL() },
                            currentClassLoader);

                    Thread.currentThread().setContextClassLoader(newClassLoader);
                }
            }

            f.close();

            if (!taglibsFound) {
                throw new RuntimeException("Error configuring taglibs classloading!");
            }

        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        System.exit(1);
    }
}

From source file:org.sablo.specification.WebComponentPackage.java

public void appendGlobalTypesJSON(JSONObject allGlobalTypesFromAllPackages) throws IOException {
    Manifest mf = reader.getManifest();

    if (mf != null) {
        Attributes mainAttrs = mf.getMainAttributes();
        if (mainAttrs != null) {
            String globalTypesSpecPath = mainAttrs.getValue(GLOBAL_TYPES_MANIFEST_ATTR);
            if (globalTypesSpecPath != null) {
                try {
                    String specfileContent = reader.readTextFile(globalTypesSpecPath, Charset.forName("UTF8")); // TODO: check encoding
                    if (specfileContent != null) {
                        JSONObject json = new JSONObject(specfileContent);
                        Object types = json.get(WebComponentSpecification.TYPES_KEY);
                        if (types instanceof JSONObject) {
                            Iterator<String> typesIt = ((JSONObject) types).keys();
                            while (typesIt.hasNext()) {
                                String key = typesIt.next();
                                allGlobalTypesFromAllPackages.put(key, ((JSONObject) types).get(key));
                            }//from ww  w  .j a  va  2 s . c om
                        }
                    }
                } catch (Exception e) {
                    reader.reportError(globalTypesSpecPath, e);
                }
            }
        }
    }
}

From source file:interactivespaces.launcher.bootstrap.InteractiveSpacesFrameworkBootstrap.java

/**
 * Get the Interactive Spaces version from the JAR manifest.
 *
 * @return The interactive spaces version
 *//* ww  w.j av  a  2 s  .  c  om*/
private String getInteractiveSpacesVersion() {
    String classContainer = getClass().getProtectionDomain().getCodeSource().getLocation().toString();

    InputStream in = null;
    try {
        URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF");
        in = manifestUrl.openStream();
        Manifest manifest = new Manifest(in);
        Attributes attributes = manifest.getMainAttributes();

        return attributes.getValue(MANIFEST_PROPERTY_INTERACTIVESPACES_VERSION);
    } catch (IOException ex) {
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // Don't care
            }
        }
    }

}

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

private FileInfo getFileInfo(final File file) throws IOException {
    if (file.isDirectory())
        return null;
    if (!file.getAbsolutePath().toLowerCase().endsWith(".jar"))
        return null;
    System.out.println(file);/*from   ww w . j  a  v  a2  s  .  c o  m*/
    final Manifest manifest = getManifest(file);
    String artifactId;
    String version;
    if (manifest == null) {
        artifactId = file.getName();
        final int indexOfDot = artifactId.lastIndexOf(".");
        if (indexOfDot >= 0)
            artifactId = artifactId.substring(0, indexOfDot);
        version = "1";
    } else {
        final Attributes mainAttributes = manifest.getMainAttributes();
        artifactId = mainAttributes.getValue("Bundle-SymbolicName");
        if (artifactId != null) {
            final int indexofsemicolon = artifactId.indexOf(";");
            if (indexofsemicolon >= 0)
                artifactId = artifactId.substring(0, indexofsemicolon);
            version = trimVersion(mainAttributes.getValue("Bundle-Version"));
        } else {
            artifactId = mainAttributes.getValue("Specification-Title");
            if (artifactId != null) {
                version = mainAttributes.getValue("Specification-Version");
            } else {
                artifactId = file.getName();
                final int indexOfDot = artifactId.lastIndexOf(".");
                if (indexOfDot >= 0)
                    artifactId = artifactId.substring(0, indexOfDot);
                version = "1";
            }
        }
    }
    return new FileInfo(file, groupId, artifactId, version);
}

From source file:net.rim.ejde.internal.packaging.PackagingManager.java

/**
 * Checks if a jar file is a MidletJar created by rapc.
 *
 * @param f/*  w w  w  .j  a  va 2  s  .c o  m*/
 * @return
 */
static public int getJarFileType(File f) {
    int type = 0x0;
    if (!f.exists()) {
        return type;
    }
    java.util.jar.JarFile jar = null;
    try {
        jar = new java.util.jar.JarFile(f, false);
        java.util.jar.Manifest manifest = jar.getManifest();
        if (manifest != null) {
            java.util.jar.Attributes attributes = manifest.getMainAttributes();
            String profile = attributes.getValue("MicroEdition-Profile");
            if (profile != null) {
                if ("MIDP-1.0".equals(profile) || "MIDP-2.0".equals(profile)) {
                    type = type | MIDLET_JAR;
                }
            }
        }
        Enumeration<JarEntry> entries = jar.entries();
        JarEntry entry;
        String entryName;
        InputStream is = null;
        IClassFileReader classFileReader = null;
        // check the attribute of the class files in the jar file
        for (; entries.hasMoreElements();) {
            entry = entries.nextElement();
            entryName = entry.getName();
            if (entryName.endsWith(IConstants.CLASS_FILE_EXTENSION_WITH_DOT)) {
                is = jar.getInputStream(entry);
                classFileReader = ToolFactory.createDefaultClassFileReader(is, IClassFileReader.ALL);
                if (isEvisceratedClass(classFileReader)) {
                    type = type | EVISCERATED_JAR;
                    break;
                }
            }
        }
    } catch (IOException e) {
        _log.error(e.getMessage());
    } finally {
        try {
            if (jar != null) {
                jar.close();
            }
        } catch (IOException e) {
            _log.error(e.getMessage());
        }
    }
    return type;
}

From source file:org.araqne.pkg.PackageManagerService.java

private Version getBundleVersion(File file) {
    JarFile jar = null;//w ww  .  j  a  v  a  2 s .c om
    try {
        jar = new JarFile(file);
        Attributes attrs = jar.getManifest().getMainAttributes();
        return new Version(attrs.getValue("Bundle-Version"));
    } catch (IOException e) {
        logger.error("package manager: bundle version not found", e);
        return null;
    } finally {
        if (jar != null)
            try {
                jar.close();
            } catch (IOException e) {
            }
    }
}