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

The following examples show how to use java.util.jar.Attributes#entrySet() . 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: MakeOSGiTest.java    From netbeans with Apache License 2.0 6 votes vote down vote up
private void assertTranslation(String expectedOsgi, String netbeans, Set<String> importedPackages, Set<String> exportedPackages) throws Exception {
    assertTrue(netbeans.endsWith("\n")); // JRE bug
    Manifest nbmani = new Manifest(new ByteArrayInputStream(netbeans.getBytes()));
    Attributes nbattr = nbmani.getMainAttributes();
    Manifest osgimani = new Manifest();
    Attributes osgi = osgimani.getMainAttributes();
    Info info = new Info();
    info.importedPackages.addAll(importedPackages);
    info.exportedPackages.addAll(exportedPackages);
    new MakeOSGi().translate(nbattr, osgi, Collections.singletonMap(nbattr.getValue("OpenIDE-Module"), info));
    // boilerplate:
    assertEquals("1.0", osgi.remove(new Attributes.Name("Manifest-Version")));
    assertEquals("2", osgi.remove(new Attributes.Name("Bundle-ManifestVersion")));
    SortedMap<String,String> osgiMap = new TreeMap<>();
    for (Map.Entry<Object,Object> entry : osgi.entrySet()) {
        osgiMap.put(((Attributes.Name) entry.getKey()).toString(), (String) entry.getValue());
    }
    assertEquals(expectedOsgi, osgiMap.toString().replace('"', '\''));
}
 
Example 2
Source File: GridUriDeploymentJarVerifier.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Gets all signed files from the manifest.
 * <p>
 * It scans all manifest entries and their attributes. If there is an attribute
 * name which ends with "-DIGEST" we are assuming that manifest entry name is a
 * signed file name.
 *
 * @param manifest JAR file manifest.
 * @return Either empty set if none found or set of signed file names.
 */
private static Set<String> getSignedFiles(Manifest manifest) {
    Set<String> fileNames = new HashSet<>();

    Map<String, Attributes> entries = manifest.getEntries();

    if (entries != null && entries.size() > 0) {
        for (Map.Entry<String, Attributes> entry : entries.entrySet()) {
            Attributes attrs = entry.getValue();

            for (Map.Entry<Object, Object> attrEntry : attrs.entrySet()) {
                if (attrEntry.getKey().toString().toUpperCase().endsWith("-DIGEST")) {
                    fileNames.add(entry.getKey());

                    break;
                }
            }
        }
    }

    return fileNames;
}
 
Example 3
Source File: JarFileReader.java    From openpojo with Apache License 2.0 6 votes vote down vote up
public Map<String, String> getManifestEntries() {
  Map<String, String> manifestEntries = new HashMap<String, String>();
  Manifest manifest;
  try {
    manifest = jarFile.getManifest();
  } catch (IOException e) {
    throw ReflectionException.getInstance("Failed to load Manifest-File for: " + jarFile.getName(), e);
  }

  Attributes mainAttributes = manifest.getMainAttributes();

  for (Attributes.Entry entry : mainAttributes.entrySet()) {
    String key = entry.getKey() == null ? "null" : entry.getKey().toString();
    String value = entry.getValue() == null ? "null" : entry.getValue().toString();
    manifestEntries.put(key, value);
  }
  return manifestEntries;
}
 
Example 4
Source File: ManifestLoader.java    From micro-server with Apache License 2.0 6 votes vote down vote up
public Map<String, String> getManifest(final InputStream input) {

        final Map<String, String> retMap = new HashMap<String, String>();
        try {
            Manifest manifest = new Manifest();
            manifest.read(input);
            final Attributes attributes = manifest.getMainAttributes();
            for (final Map.Entry attribute : attributes.entrySet()) {
                retMap.put(attribute.getKey().toString(), attribute.getValue().toString());
            }
        } catch (final Exception ex) {
            logger.error("Failed to load manifest ", ex);
        }

        return retMap;
    }
 
Example 5
Source File: ManifestResource.java    From micro-server with Apache License 2.0 6 votes vote down vote up
public Map<String, String> getManifest(final InputStream input) {
	
	final Map<String, String> retMap = new HashMap<String, String>();
	try {
		Manifest manifest = new Manifest();
		manifest.read(input);
		final Attributes attributes = manifest.getMainAttributes();
		for (final Map.Entry attribute : attributes.entrySet()) {
			retMap.put(attribute.getKey().toString(), attribute.getValue().toString());
		}
	} catch (final Exception ex) {
		logger.error( "Failed to load manifest ", ex);
	}

	return retMap;
}
 
Example 6
Source File: ManifestReader.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
private static Map<String, String> toMap(Manifest manifest) {
    Map<String, String> rawMap = new HashMap<>();
    if(manifest == null) return rawMap;
    Attributes mainAttributes = manifest.getMainAttributes();
    if(mainAttributes==null) return rawMap;
    for (Map.Entry<Object, Object> entry : mainAttributes.entrySet()) {
        rawMap.put(entry.getKey().toString(), (String) entry.getValue());
    }
    return rawMap;
}
 
Example 7
Source File: ManifestWriter.java    From Xpatch with Apache License 2.0 5 votes vote down vote up
static SortedMap<String, String> getAttributesSortedByName(Attributes attributes) {
    Set<Map.Entry<Object, Object>> attributesEntries = attributes.entrySet();
    SortedMap<String, String> namedAttributes = new TreeMap<String, String>();
    for (Map.Entry<Object, Object> attribute : attributesEntries) {
        String attrName = attribute.getKey().toString();
        String attrValue = attribute.getValue().toString();
        namedAttributes.put(attrName, attrValue);
    }
    return namedAttributes;
}
 
Example 8
Source File: JarFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Adds the source attributes to the destination map.
 */
private void addAll(final Attributes src, final Map<String, Object> dest) {
    for (final Entry<Object, Object> entry : src.entrySet()) {
        // final String name = entry.getKey().toString().toLowerCase();
        final String name = entry.getKey().toString();
        dest.put(name, entry.getValue());
    }
}
 
Example 9
Source File: BrooklynVersion.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
private static Optional<BrooklynFeature> newFeature(Attributes attrs) {
    // unfortunately Attributes is a Map<Object,Object>
    Dictionary<String,String> headers = new Hashtable<>();
    for (Map.Entry<Object, Object> entry : attrs.entrySet()) {
        headers.put(entry.getKey().toString(), entry.getValue().toString());
    }
    return newFeature(headers);
}
 
Example 10
Source File: Version.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
public static Properties getVersionProperties() {
    if (propertiesCache == null) {
        Properties newProps = new Properties();
        try {
            String jarUrl = Version.class.getProtectionDomain().getCodeSource().getLocation().getFile();
            try (JarFile jar = new JarFile(new File(jarUrl))) {
                Manifest manifest = jar.getManifest();
                Attributes attributes = manifest.getMainAttributes();
                for (Entry<Object, Object> entry : attributes.entrySet()) {
                    newProps.setProperty(entry.getKey().toString(), entry.getValue().toString());
                }
            }
        } catch (Exception e) {
            newProps.put(PROP_BUILD_SHA, "unknown");
            newProps.put(PROP_BUILD_DATE, "unknown");
            Package pkg = Version.class.getPackage();
            if (pkg != null) {
                newProps.put(PROP_IMPL_TITLE, pkg.getImplementationTitle());
                newProps.put(PROP_IMPL_VERSION, pkg.getImplementationVersion());
            } else {
                newProps.put(PROP_IMPL_TITLE, "unknown");
                newProps.put(PROP_IMPL_VERSION, "unknown");
            }
        }
        propertiesCache = newProps;
    }

    Properties retProps = new Properties();
    retProps.putAll(propertiesCache);
    return retProps;
}
 
Example 11
Source File: HeaderDictionary.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Create a dictionary from manifest attributes.
 */
public HeaderDictionary(Attributes in) {
  headers = new Hashtable<Attributes.Name, String>();
  for (final Entry<Object, Object> e : in.entrySet()) {
    headers.put((Attributes.Name)e.getKey(), (String)e.getValue());
  }
}
 
Example 12
Source File: ComponentValidator.java    From vespa with Apache License 2.0 5 votes vote down vote up
public void validateOSGIHeaders(DeployLogger deployLogger) throws IOException {
    Manifest mf = jarFile.getManifest();
    if (mf == null) {
        throw new IllegalArgumentException("Non-existing or invalid manifest in " + jarFile.getName());
    }

    // Check for required OSGI headers
    Attributes attributes = mf.getMainAttributes();
    HashSet<String> mfAttributes = new HashSet<>();
    for (Object attributeSet : attributes.entrySet()) {
        Map.Entry<Object, Object> e = (Map.Entry<Object, Object>) attributeSet;
        mfAttributes.add(e.getKey().toString());
    }
    List<String> requiredOSGIHeaders = Arrays.asList(
            "Bundle-ManifestVersion", "Bundle-Name", "Bundle-SymbolicName", "Bundle-Version");
    for (String header : requiredOSGIHeaders) {
        if (!mfAttributes.contains(header)) {
            throw new IllegalArgumentException("Required OSGI header '" + header +
                    "' was not found in manifest in '" + jarFile.getName() + "'");
        }
    }

    if (attributes.getValue("Bundle-Version").endsWith(".SNAPSHOT")) {
        deployLogger.log(Level.WARNING, "Deploying snapshot bundle " + jarFile.getName() +
                ".\nTo use this bundle, you must include the qualifier 'SNAPSHOT' in  the version specification in services.xml.");
    }
}
 
Example 13
Source File: SimpleManifest.java    From pipeline-utility-steps-plugin with MIT License 5 votes vote down vote up
protected static Map<String, String> extractMainAttributes(Manifest mf) {
    Map<String, String> map = new HashMap<>();
    Attributes attributes = mf.getMainAttributes();
    for (Map.Entry<Object, Object> entry : attributes.entrySet()) {
        map.put(entry.getKey().toString(), entry.getValue().toString());
    }
    return map;
}
 
Example 14
Source File: ManifestWriter.java    From walle with Apache License 2.0 5 votes vote down vote up
static SortedMap<String, String> getAttributesSortedByName(Attributes attributes) {
    Set<Map.Entry<Object, Object>> attributesEntries = attributes.entrySet();
    SortedMap<String, String> namedAttributes = new TreeMap<String, String>();
    for (Map.Entry<Object, Object> attribute : attributesEntries) {
        String attrName = attribute.getKey().toString();
        String attrValue = attribute.getValue().toString();
        namedAttributes.put(attrName, attrValue);
    }
    return namedAttributes;
}
 
Example 15
Source File: DummyModuleInfo.java    From netbeans with Apache License 2.0 5 votes vote down vote up
/** Create a new fake module based on manifest.
     * Only main attributes need be presented, so
     * only pass these.
     */
    public DummyModuleInfo(Attributes attr) throws IllegalArgumentException {
        this.attr = attr;
        if (attr == null) {
            throw new IllegalArgumentException ("The parameter attr cannot be null.");
        }
        if (getCodeName() == null) {
            throw new IllegalArgumentException ("No code name in module descriptor " + attr.entrySet ());
        }
        String cnb = getCodeNameBase();
        try {
            getSpecificationVersion();
        } catch (NumberFormatException nfe) {
            throw new IllegalArgumentException(nfe.toString() + " from " + cnb); // NOI18N
        }
        deps = parseDeps (attr, cnb);
//        getAutoDepsHandler().refineDependencies(cnb, deps); // #29577
        String providesS = attr.getValue("OpenIDE-Module-Provides"); // NOI18N
        if (cnb.equals ("org.openide.modules")) { // NOI18N
            providesS = providesS == null ? TOKEN_MODULE_FORMAT1 : providesS + ", " + TOKEN_MODULE_FORMAT1; // NOI18N
            providesS = providesS == null ? TOKEN_MODULE_FORMAT2 : providesS + ", " + TOKEN_MODULE_FORMAT2; // NOI18N
        }
        if (providesS == null) {
            provides = new String[0];
        } else {
            StringTokenizer tok = new StringTokenizer(providesS, ", "); // NOI18N
            provides = new String[tok.countTokens()];
            for (int i = 0; i < provides.length; i++) {
                provides[i] = tok.nextToken();
            }
        }
        // XXX could do more error checking but this is probably plenty
    }
 
Example 16
Source File: SignatureFileVerifier.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * given the .SF digest header, and the data from the
 * section in the manifest, see if the hashes match.
 * if not, throw a SecurityException.
 *
 * @return true if all the -Digest headers verified
 * @exception SecurityException if the hash was not equal
 */

private boolean verifySection(Attributes sfAttr,
                              String name,
                              ManifestDigester md)
     throws IOException, SignatureException
{
    boolean oneDigestVerified = false;
    ManifestDigester.Entry mde = md.get(name,block.isOldStyle());

    if (mde == null) {
        throw new SecurityException(
              "no manifest section for signature file entry "+name);
    }

    if (sfAttr != null) {

        //sun.misc.HexDumpEncoder hex = new sun.misc.HexDumpEncoder();
        //hex.encodeBuffer(data, System.out);

        // go through all the attributes and process *-Digest entries
        for (Map.Entry<Object,Object> se : sfAttr.entrySet()) {
            String key = se.getKey().toString();

            if (key.toUpperCase(Locale.ENGLISH).endsWith("-DIGEST")) {
                // 7 is length of "-Digest"
                String algorithm = key.substring(0, key.length()-7);

                MessageDigest digest = getDigest(algorithm);

                if (digest != null) {
                    boolean ok = false;

                    byte[] expected =
                        Base64.getMimeDecoder().decode((String)se.getValue());
                    byte[] computed;
                    if (workaround) {
                        computed = mde.digestWorkaround(digest);
                    } else {
                        computed = mde.digest(digest);
                    }

                    if (debug != null) {
                      debug.println("Signature Block File: " +
                               name + " digest=" + digest.getAlgorithm());
                      debug.println("  expected " + toHex(expected));
                      debug.println("  computed " + toHex(computed));
                      debug.println();
                    }

                    if (MessageDigest.isEqual(computed, expected)) {
                        oneDigestVerified = true;
                        ok = true;
                    } else {
                        // attempt to fallback to the workaround
                        if (!workaround) {
                           computed = mde.digestWorkaround(digest);
                           if (MessageDigest.isEqual(computed, expected)) {
                               if (debug != null) {
                                   debug.println("  re-computed " + toHex(computed));
                                   debug.println();
                               }
                               workaround = true;
                               oneDigestVerified = true;
                               ok = true;
                           }
                        }
                    }
                    if (!ok){
                        throw new SecurityException("invalid " +
                                   digest.getAlgorithm() +
                                   " signature file digest for " + name);
                    }
                }
            }
        }
    }
    return oneDigestVerified;
}
 
Example 17
Source File: SignatureFileVerifier.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private boolean verifyManifestMainAttrs(Manifest sf,
                                    ManifestDigester md)
     throws IOException, SignatureException
{
    Attributes mattr = sf.getMainAttributes();
    boolean attrsVerified = true;

    // go through all the attributes and process
    // digest entries for the manifest main attributes
    for (Map.Entry<Object,Object> se : mattr.entrySet()) {
        String key = se.getKey().toString();

        if (key.toUpperCase(Locale.ENGLISH).endsWith(ATTR_DIGEST)) {
            String algorithm =
                    key.substring(0, key.length() - ATTR_DIGEST.length());

            MessageDigest digest = getDigest(algorithm);
            if (digest != null) {
                ManifestDigester.Entry mde =
                    md.get(ManifestDigester.MF_MAIN_ATTRS, false);
                byte[] computedHash = mde.digest(digest);
                byte[] expectedHash =
                    Base64.getMimeDecoder().decode((String)se.getValue());

                if (debug != null) {
                 debug.println("Signature File: " +
                                    "Manifest Main Attributes digest " +
                                    digest.getAlgorithm());
                 debug.println( "  sigfile  " + toHex(expectedHash));
                 debug.println( "  computed " + toHex(computedHash));
                 debug.println();
                }

                if (MessageDigest.isEqual(computedHash,
                                          expectedHash)) {
                    // good
                } else {
                    // we will *not* continue and verify each section
                    attrsVerified = false;
                    if (debug != null) {
                        debug.println("Verification of " +
                                    "Manifest main attributes failed");
                        debug.println();
                    }
                    break;
                }
            }
        }
    }

    // this method returns 'true' if either:
    //      . manifest main attributes were not signed, or
    //      . manifest main attributes were signed and verified
    return attrsVerified;
}
 
Example 18
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 19
Source File: SignatureFileVerifier.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * See if the whole manifest was signed.
 */
private boolean verifyManifestHash(Manifest sf,
                                   ManifestDigester md,
                                   List<Object> manifestDigests)
     throws IOException, SignatureException
{
    Attributes mattr = sf.getMainAttributes();
    boolean manifestSigned = false;

    // go through all the attributes and process *-Digest-Manifest entries
    for (Map.Entry<Object,Object> se : mattr.entrySet()) {

        String key = se.getKey().toString();

        if (key.toUpperCase(Locale.ENGLISH).endsWith("-DIGEST-MANIFEST")) {
            // 16 is length of "-Digest-Manifest"
            String algorithm = key.substring(0, key.length()-16);

            manifestDigests.add(key);
            manifestDigests.add(se.getValue());
            MessageDigest digest = getDigest(algorithm);
            if (digest != null) {
                byte[] computedHash = md.manifestDigest(digest);
                byte[] expectedHash =
                    Base64.getMimeDecoder().decode((String)se.getValue());

                if (debug != null) {
                 debug.println("Signature File: Manifest digest " +
                                      digest.getAlgorithm());
                 debug.println( "  sigfile  " + toHex(expectedHash));
                 debug.println( "  computed " + toHex(computedHash));
                 debug.println();
                }

                if (MessageDigest.isEqual(computedHash,
                                          expectedHash)) {
                    manifestSigned = true;
                } else {
                    //XXX: we will continue and verify each section
                }
            }
        }
    }
    return manifestSigned;
}