Example usage for java.util.jar Attributes entrySet

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

Introduction

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

Prototype

public Set<Map.Entry<Object, Object>> entrySet() 

Source Link

Document

Returns a Collection view of the attribute name-value mappings contained in this Map.

Usage

From source file:Main.java

public static void main(String[] args) throws IOException {

    JarFile jf = new JarFile(args[0]);
    Enumeration e = jf.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        String name = je.getName();

        Attributes a = je.getAttributes();
        if (a != null) {
            Object[] nameValuePairs = a.entrySet().toArray();
            for (int j = 0; j < nameValuePairs.length; j++) {
                System.out.println(nameValuePairs[j]);
            }// w ww .  j  a v a  2  s. c  om
        }
    }
}

From source file:Main.java

public static void main(String[] args) throws IOException {
    JarFile jf = new JarFile("a.jar");
    Enumeration e = jf.entries();
    while (e.hasMoreElements()) {
        JarEntry je = (JarEntry) e.nextElement();
        System.out.println(je.getName());
        long uncompressedSize = je.getSize();
        long compressedSize = je.getCompressedSize();
        long crc = je.getCrc();
        int method = je.getMethod();
        String comment = je.getComment();
        System.out.println(new Date(je.getTime()));
        System.out.println("from  " + uncompressedSize + " bytes to " + compressedSize);
        if (method == ZipEntry.STORED) {
            System.out.println("ZipEntry.STORED");
        } else if (method == ZipEntry.DEFLATED) {
            System.out.println(ZipEntry.DEFLATED);
        }/* ww w.j  av  a 2s .com*/
        System.out.println("Its CRC is " + crc);
        System.out.println(comment);
        System.out.println(je.isDirectory());

        Attributes a = je.getAttributes();
        if (a != null) {
            Object[] nameValuePairs = a.entrySet().toArray();
            for (int j = 0; j < nameValuePairs.length; j++) {
                System.out.println(nameValuePairs[j]);
            }
        }
        System.out.println();
    }
}

From source file:com.qmetry.qaf.automation.core.ConfigurationManager.java

private static Map<String, String> getBuildInfo() {
    Manifest manifest = null;//from ww  w .  jav a2 s .  co m
    Map<String, String> buildInfo = new HashMap<String, String>();
    JarFile jar = null;
    try {
        URL url = ConfigurationManager.class.getProtectionDomain().getCodeSource().getLocation();
        File file = new File(url.toURI());
        jar = new JarFile(file);
        manifest = jar.getManifest();
    } catch (NullPointerException ignored) {
    } catch (URISyntaxException ignored) {
    } catch (IOException ignored) {
    } catch (IllegalArgumentException ignored) {
    } finally {
        if (null != jar)
            try {
                jar.close();
            } catch (IOException e) {
                log.warn(e.getMessage());
            }
    }

    if (manifest == null) {
        return buildInfo;
    }

    try {
        Attributes attributes = manifest.getAttributes("Build-Info");
        Set<Entry<Object, Object>> entries = attributes.entrySet();
        for (Entry<Object, Object> e : entries) {
            buildInfo.put(String.valueOf(e.getKey()), String.valueOf(e.getValue()));
        }
    } catch (NullPointerException e) {
        // Fall through
    }

    return buildInfo;
}

From source file:org.carewebframework.api.ManifestIteratorTest.java

@Test
public void testIterator() {
    ManifestIterator manifests = (ManifestIterator) appContext.getBean("manifestIterator");

    for (Manifest manifest : manifests) {
        Attributes attributes = manifest.getMainAttributes();

        for (Entry<?, ?> entry : attributes.entrySet()) {
            Name name = (Name) entry.getKey();
            log.info(name + ": " + entry.getValue().toString());
        }//from   w w w . j  av a 2s .  c o  m
    }
}

From source file:org.eu.gasp.core.internal.DefaultPluginRegistry.java

private void registerPlugin(File file) throws Exception {
    if (isFileRegistered(file)) {
        return;//  ww  w .  j  a v a 2 s .co m
    }

    final JarFile jarFile = new JarFile(file);
    final Manifest manifest = jarFile.getManifest();

    String pluginId = null;
    String pluginClassName = null;
    Version version = null;
    final List<DefaultPluginDependency> pluginDependencies = new ArrayList<DefaultPluginDependency>();
    final List<String> services = new ArrayList<String>();

    final Attributes attrs = manifest.getMainAttributes();
    for (final Map.Entry entry : attrs.entrySet()) {
        final String key = entry.getKey().toString();
        final String value = StringUtils.trimToNull(entry.getValue().toString());

        if (value == null) {
            continue;
        }

        if (JAR_PLUGIN.equals(key)) {
            pluginId = value;
        } else if (JAR_PLUGIN_CLASS.equals(key)) {
            pluginClassName = value;
        } else if (JAR_PLUGIN_VERSION.equals(key)) {
            version = new Version(value);
        } else if (JAR_PLUGIN_PROVIDES.equals(key)) {
            for (final String service : value.split(",")) {
                services.add(service);
            }
        } else if (JAR_PLUGIN_REQUIRES.equals(key)) {
            for (final String versionnedRequiredPluginId : value.split(",")) {
                pluginDependencies.add(new DefaultPluginDependency(versionnedRequiredPluginId, null));
            }
        }
    }

    if (StringUtils.isBlank(pluginId)) {
        throw new IllegalStateException("Missing " + JAR_PLUGIN + " attribute in manifest");
    }
    if (version == null) {
        throw new IllegalStateException("Missing " + JAR_PLUGIN_VERSION + " attribute in manifest");
    }

    final PluginDescriptor pluginDescriptor = new DefaultPluginDescriptor(pluginId, version, pluginClassName,
            pluginDependencies, services);
    if (!plugins.containsKey(pluginDescriptor)) {
        log.info("Registering plugin: " + pluginDescriptor);
        plugins.put(pluginDescriptor, new PluginData(file));
    }
}

From source file:org.jasig.ssp.service.impl.ServerServiceImpl.java

private void cacheVersionProfile() throws IOException {

    InputStream mfStream = null;//from   w ww  . j av  a2s  . co  m
    try {
        mfStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");
        Manifest mf = new Manifest(mfStream);
        final Attributes mainAttributes = mf.getMainAttributes();
        final Map<String, Object> tmpVersionProfile = new HashMap<String, Object>();
        tmpVersionProfile.put(NAME_API_FIELD_NAME, SSP_VERSION_PROFILE_NAME);

        // For SSP itself the entry format is:
        //  SSP-<EntryName>
        // e.g.:
        //  SSP-Artifact-Version
        //
        // For "extensions" the entry format is:
        //  SSP-Ext-<ExtensionName>-<EntryName>
        // e.g.:
        //  SSP-Ext-UPOverlay-Artifact-Version
        //
        // We do not want to accidentally expose any sensitive config
        // placed into the manifest. So we only output values from recognized
        // <EntryName> values.
        Map<String, Object> extensions = null;
        for (Map.Entry<Object, Object> entry : mainAttributes.entrySet()) {
            String rawEntryName = entry.getKey().toString();
            if (rawEntryName.startsWith(SSP_EXTENSION_ENTRY_PREFIX)) {
                String[] parsedEntryName = rawEntryName.split(SSP_EXTENSION_ENTRY_DELIM);
                if (parsedEntryName.length < 4) {
                    continue;
                }
                String unqualifiedEntryName = StringUtils.join(parsedEntryName, SSP_EXTENSION_ENTRY_DELIM, 3,
                        parsedEntryName.length);
                if (!(isWellKnownEntryName(unqualifiedEntryName))) {
                    continue;
                }
                String extName = parsedEntryName[2];
                if (extensions == null) {
                    extensions = new HashMap<String, Object>();
                }
                Map<String, Object> thisExtension = (Map<String, Object>) extensions.get(extName);
                if (thisExtension == null) {
                    thisExtension = new HashMap<String, Object>();
                    thisExtension.put(NAME_API_FIELD_NAME, extName);
                    extensions.put(extName, thisExtension);
                }
                mapWellKnownEntryName(unqualifiedEntryName, (String) entry.getValue(), thisExtension);
            } else if (rawEntryName.startsWith(SSP_ENTRY_PREFIX)) {
                String unqualifiedEntryName = rawEntryName.substring(SSP_ENTRY_PREFIX.length());
                if (isWellKnownEntryName(unqualifiedEntryName)) {
                    mapWellKnownEntryName(unqualifiedEntryName, (String) entry.getValue(), tmpVersionProfile);
                }
            }
        }

        if (extensions == null) {
            tmpVersionProfile.put(EXTENSIONS_API_FIELD_NAME, Collections.EMPTY_MAP);
        } else {
            tmpVersionProfile.put(EXTENSIONS_API_FIELD_NAME, Lists.newArrayList(extensions.values()));
        }

        this.versionProfile = tmpVersionProfile; // lets not cache it until we're sure we loaded everything

    } finally {
        if (mfStream != null) {
            try {
                mfStream.close();
            } catch (Exception e) {
            }
        }
    }
}

From source file:org.overlord.commons.osgi.vfs.VfsBundle.java

/**
 * Throws a "not found" error while also logging information found in the manifest.  This
 * latter part will help diagnose which JAR was *supposed* to have been detected.
 * @param url/*  w  w w .  j  a  v  a  2 s.  com*/
 */
private void throwNotFoundError(URL url) {
    InputStream manifestStream = null;
    StringBuilder builder = new StringBuilder();
    try {
        String manifestPath = "META-INF/MANIFEST.MF"; //$NON-NLS-1$
        URL manifestURL = new URL(url.toExternalForm() + manifestPath);
        manifestStream = manifestURL.openStream();
        Manifest manifest = new Manifest(manifestStream);
        Attributes attributes = manifest.getMainAttributes();
        for (Entry<Object, Object> entry : attributes.entrySet()) {
            String key = String.valueOf(entry.getKey());
            String value = String.valueOf(entry.getValue());
            builder.append(key).append(": ").append(value).append("\n"); //$NON-NLS-1$ //$NON-NLS-2$
        }
    } catch (Exception e) {
    } finally {
        IOUtils.closeQuietly(manifestStream);
    }
    // Include the full manifest in the exception - this is helpful to diagnose which
    // JAR gave us fits.  Hopefully this will not happen!
    throw new RuntimeException("Failed to create a Vfs.Dir for URL: " + url //$NON-NLS-1$
            + "\n--Manifest--\n====================" + builder.toString()); //$NON-NLS-1$
}

From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java

/**
 * <p>//from w w w.  jav  a  2  s . co m
 * Reads the manifest from the JAR file and collects the entries. Some
 * vendorKey entries are:</p>
 * <ul><li>Implementation Title</li>
 * <li>Implementation Version</li> <li>Implementation Vendor</li>
 * <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle
 * Version</li> <li>Bundle Vendor</li> <li>Bundle Description</li> <li>Main
 * Class</li> </ul>
 * However, all but a handful of specific entries are read in.
 *
 * @param dependency A reference to the dependency
 * @param classInformation a collection of class information
 * @return whether evidence was identified parsing the manifest
 * @throws IOException if there is an issue reading the JAR file
 */
protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation)
        throws IOException {
    boolean foundSomething = false;
    JarFile jar = null;
    try {
        jar = new JarFile(dependency.getActualFilePath());
        final Manifest manifest = jar.getManifest();
        if (manifest == null) {
            if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar")
                    && !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar")
                    && !dependency.getFileName().toLowerCase().endsWith("-src.jar")
                    && !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) {
                LOGGER.debug("Jar file '{}' does not contain a manifest.", dependency.getFileName());
            }
            return false;
        }
        final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
        final EvidenceCollection productEvidence = dependency.getProductEvidence();
        final EvidenceCollection versionEvidence = dependency.getVersionEvidence();

        String source = "Manifest";
        String specificationVersion = null;
        boolean hasImplementationVersion = false;
        Attributes atts = manifest.getMainAttributes();
        for (Entry<Object, Object> entry : atts.entrySet()) {
            String key = entry.getKey().toString();
            String value = atts.getValue(key);
            if (HTML_DETECTION_PATTERN.matcher(value).find()) {
                value = Jsoup.parse(value).text();
            }
            if (IGNORE_VALUES.contains(value)) {
                continue;
            } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) {
                foundSomething = true;
                productEvidence.addEvidence(source, key, value, Confidence.HIGH);
                addMatchingValues(classInformation, value, productEvidence);
            } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) {
                hasImplementationVersion = true;
                foundSomething = true;
                versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
            } else if ("specification-version".equalsIgnoreCase(key)) {
                specificationVersion = key;
            } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) {
                foundSomething = true;
                vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
                addMatchingValues(classInformation, value, vendorEvidence);
            } else if (key.equalsIgnoreCase(IMPLEMENTATION_VENDOR_ID)) {
                foundSomething = true;
                vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                addMatchingValues(classInformation, value, vendorEvidence);
            } else if (key.equalsIgnoreCase(BUNDLE_DESCRIPTION)) {
                foundSomething = true;
                addDescription(dependency, value, "manifest", key);
                addMatchingValues(classInformation, value, productEvidence);
            } else if (key.equalsIgnoreCase(BUNDLE_NAME)) {
                foundSomething = true;
                productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                addMatchingValues(classInformation, value, productEvidence);
                //                //the following caused false positives.
                //                } else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) {
                //                    foundSomething = true;
                //                    vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
                //                    addMatchingValues(classInformation, value, vendorEvidence);
            } else if (key.equalsIgnoreCase(BUNDLE_VERSION)) {
                foundSomething = true;
                versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
            } else if (key.equalsIgnoreCase(Attributes.Name.MAIN_CLASS.toString())) {
                continue;
                //skipping main class as if this has important information to add
                // it will be added during class name analysis...  if other fields
                // have the information from the class name then they will get added...
            } else {
                key = key.toLowerCase();
                if (!IGNORE_KEYS.contains(key) && !key.endsWith("jdk") && !key.contains("lastmodified")
                        && !key.endsWith("package") && !key.endsWith("classpath") && !key.endsWith("class-path")
                        && !key.endsWith("-scm") //todo change this to a regex?
                        && !key.startsWith("scm-") && !value.trim().startsWith("scm:")
                        && !isImportPackage(key, value) && !isPackage(key, value)) {
                    foundSomething = true;
                    if (key.contains("version")) {
                        if (!key.contains("specification")) {
                            versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                        }
                    } else if ("build-id".equals(key)) {
                        int pos = value.indexOf('(');
                        if (pos >= 0) {
                            value = value.substring(0, pos - 1);
                        }
                        pos = value.indexOf('[');
                        if (pos >= 0) {
                            value = value.substring(0, pos - 1);
                        }
                        versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                    } else if (key.contains("title")) {
                        productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                        addMatchingValues(classInformation, value, productEvidence);
                    } else if (key.contains("vendor")) {
                        if (key.contains("specification")) {
                            vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
                        } else {
                            vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                            addMatchingValues(classInformation, value, vendorEvidence);
                        }
                    } else if (key.contains("name")) {
                        productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                        vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                        addMatchingValues(classInformation, value, vendorEvidence);
                        addMatchingValues(classInformation, value, productEvidence);
                    } else if (key.contains("license")) {
                        addLicense(dependency, value);
                    } else if (key.contains("description")) {
                        addDescription(dependency, value, "manifest", key);
                    } else {
                        productEvidence.addEvidence(source, key, value, Confidence.LOW);
                        vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
                        addMatchingValues(classInformation, value, vendorEvidence);
                        addMatchingValues(classInformation, value, productEvidence);
                        if (value.matches(".*\\d.*")) {
                            final StringTokenizer tokenizer = new StringTokenizer(value, " ");
                            while (tokenizer.hasMoreElements()) {
                                final String s = tokenizer.nextToken();
                                if (s.matches("^[0-9.]+$")) {
                                    versionEvidence.addEvidence(source, key, s, Confidence.LOW);
                                }
                            }
                        }
                    }
                }
            }
        }

        for (Map.Entry<String, Attributes> item : manifest.getEntries().entrySet()) {
            final String name = item.getKey();
            source = "manifest: " + name;
            atts = item.getValue();
            for (Entry<Object, Object> entry : atts.entrySet()) {
                final String key = entry.getKey().toString();
                final String value = atts.getValue(key);
                if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) {
                    foundSomething = true;
                    productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                    addMatchingValues(classInformation, value, productEvidence);
                } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) {
                    foundSomething = true;
                    versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) {
                    foundSomething = true;
                    vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                    addMatchingValues(classInformation, value, vendorEvidence);
                } else if (key.equalsIgnoreCase(Attributes.Name.SPECIFICATION_TITLE.toString())) {
                    foundSomething = true;
                    productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                    addMatchingValues(classInformation, value, productEvidence);
                }
            }
        }
        if (specificationVersion != null && !hasImplementationVersion) {
            foundSomething = true;
            versionEvidence.addEvidence(source, "specification-version", specificationVersion, Confidence.HIGH);
        }
    } finally {
        if (jar != null) {
            jar.close();
        }
    }
    return foundSomething;
}

From source file:org.sourcepit.common.manifest.util.ManifestUtils.java

public static Manifest toManifest(java.util.jar.Manifest manifest) {
    GenericManifestBuilder builder = new GenericManifestBuilder();

    // map main section
    builder.visitSection(true, null);/* w  w w . j  a v a 2  s .  com*/
    for (Map.Entry<Object, Object> header : manifest.getMainAttributes().entrySet()) {
        builder.visitHeader(header.getKey().toString(), header.getValue().toString());
    }

    // map other section
    for (Map.Entry<String, Attributes> entry : manifest.getEntries().entrySet()) {
        builder.visitSection(false, entry.getKey());
        Attributes attributes = entry.getValue();
        for (Map.Entry<Object, Object> header : attributes.entrySet()) {
            builder.visitHeader(header.getKey().toString(), header.getValue().toString());
        }
    }
    return builder.getManifest();
}