Example usage for java.util.jar Attributes containsKey

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

Introduction

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

Prototype

public boolean containsKey(Object name) 

Source Link

Document

Returns true if this Map contains the specified attribute name (key).

Usage

From source file:com.xebialabs.deployit.cli.ext.mustachify.dar.DarManifestParser.java

private static void validate(Attributes mainAttributes) {
    checkArgument(mainAttributes.containsKey(new Name(PACKAGE_FORMAT_VERSION_ATTRIBUTE_NAME)),
            "manifest does not contain required DAR attribute '%s'", PACKAGE_FORMAT_VERSION_ATTRIBUTE_NAME);
    checkArgument(//from   ww  w . j  a  v a 2  s  .c o m
            mainAttributes.getValue(PACKAGE_FORMAT_VERSION_ATTRIBUTE_NAME)
                    .equals(SUPPORTED_PACKAGE_FORMAT_VERSION),
            "unsupported package format version '%s', only '%s' supported",
            mainAttributes.getValue(PACKAGE_FORMAT_VERSION_ATTRIBUTE_NAME), SUPPORTED_PACKAGE_FORMAT_VERSION);
    checkArgument(mainAttributes.containsKey(new Name(APPLICATION_ATTRIBUTE_NAME)),
            "manifest does not contain required DAR attribute '%s'", APPLICATION_ATTRIBUTE_NAME);
    checkArgument(mainAttributes.containsKey(new Name(VERSION_ATTRIBUTE_NAME)),
            "manifest does not contain required DAR attribute '%s'", VERSION_ATTRIBUTE_NAME);
}

From source file:com.thoughtworks.go.plugin.infra.plugininfo.GoPluginOSGiManifest.java

private void updateManifest(String symbolicName, String classPath, String bundleActivator) throws IOException {
    try (FileInputStream manifestInputStream = new FileInputStream(manifestLocation)) {
        Manifest manifest = new Manifest(manifestInputStream);
        Attributes mainAttributes = manifest.getMainAttributes();

        if (mainAttributes.containsKey(new Attributes.Name(BUNDLE_SYMBOLICNAME))) {
            descriptor.markAsInvalid(Arrays.asList(
                    "Plugin JAR is invalid. MANIFEST.MF already contains header: " + BUNDLE_SYMBOLICNAME),
                    null);//from www  . j av  a 2s  .c o m
            return;
        }
        mainAttributes.put(new Attributes.Name(BUNDLE_SYMBOLICNAME), symbolicName);
        mainAttributes.put(new Attributes.Name(BUNDLE_CLASSPATH), classPath);
        mainAttributes.put(new Attributes.Name(BUNDLE_ACTIVATOR), bundleActivator);

        descriptor.updateBundleInformation(symbolicName, classPath, bundleActivator);

        try (FileOutputStream manifestOutputStream = new FileOutputStream(manifestLocation)) {
            manifest.write(manifestOutputStream);
        }
    }
}

From source file:net.minecraftforge.fml.relauncher.libraries.LibraryManager.java

private static Pair<Artifact, byte[]> extractPacked(JarFile jar, ModList modlist, File... modDirs)
        throws IOException {
    Attributes attrs;
    if (jar.getManifest() == null)
        return null;

    JarEntry manifest_entry = jar.getJarEntry(JarFile.MANIFEST_NAME);
    if (manifest_entry == null)
        manifest_entry = jar.stream()/*from w ww .  j  av  a  2 s.c o  m*/
                .filter(e -> JarFile.MANIFEST_NAME.equals(e.getName().toUpperCase(Locale.ENGLISH))).findFirst()
                .get(); //We know that getManifest returned non-null so we know there is *some* entry that matches the manifest file. So we dont need to empty check.

    attrs = jar.getManifest().getMainAttributes();

    String modSide = attrs.getValue(LibraryManager.MODSIDE);
    if (modSide != null && !"BOTH".equals(modSide) && !FMLLaunchHandler.side().name().equals(modSide))
        return null;

    if (attrs.containsKey(MODCONTAINSDEPS)) {
        for (String dep : attrs.getValue(MODCONTAINSDEPS).split(" ")) {
            if (!dep.endsWith(".jar")) {
                FMLLog.log.error("Contained Dep is not a jar file: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Must be jar: " + dep);
            }

            if (jar.getJarEntry(dep) == null && jar.getJarEntry("META-INF/libraries/" + dep) != null)
                dep = "META-INF/libraries/" + dep;

            JarEntry depEntry = jar.getJarEntry(dep);
            if (depEntry == null) {
                FMLLog.log.error("Contained Dep is not in the jar: {}", dep);
                throw new IllegalStateException("Invalid contained dep, Missing from jar: " + dep);
            }

            String depEndName = new File(dep).getName(); // extract last part of name
            if (skipContainedDeps.contains(dep) || skipContainedDeps.contains(depEndName)) {
                FMLLog.log.error("Skipping dep at request: {}", dep);
                continue;
            }

            Attributes meta = null;
            byte[] data = null;
            byte[] manifest_data = null;

            JarEntry metaEntry = jar.getJarEntry(dep + ".meta");
            if (metaEntry != null) {
                manifest_data = readAll(jar.getInputStream(metaEntry));
                meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
            } else {
                data = readAll(jar.getInputStream(depEntry));
                try (ZipInputStream zi = new ZipInputStream(new ByteArrayInputStream(data))) //We use zip input stream directly, as the current Oracle implementation of JarInputStream only works when the manifest is the First/Second entry in the jar...
                {
                    ZipEntry ze = null;
                    while ((ze = zi.getNextEntry()) != null) {
                        if (ze.getName().equalsIgnoreCase(JarFile.MANIFEST_NAME)) {
                            manifest_data = readAll(zi);
                            meta = new Manifest(new ByteArrayInputStream(manifest_data)).getMainAttributes();
                            break;
                        }
                    }
                }
            }

            if (meta == null || !meta.containsKey(MAVEN_ARTIFACT)) //Ugh I really don't want to do backwards compatibility here, I want to force modders to provide information... TODO: Remove in 1.13?
            {
                boolean found = false;
                for (File dir : modDirs) {
                    File target = new File(dir, depEndName);
                    if (target.exists()) {
                        FMLLog.log.debug("Found existing ContainDep extracted to {}, skipping extraction",
                                target.getCanonicalPath());
                        found = true;
                    }
                }
                if (!found) {
                    File target = new File(modDirs[0], depEndName);
                    FMLLog.log.debug("Extracting ContainedDep {} from {} to {}", dep, jar.getName(),
                            target.getCanonicalPath());
                    try {
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {} from {} to {}", dep, jar.getName(),
                                target.getCanonicalPath());
                        extractPacked(target, modlist, modDirs);
                    } catch (IOException e) {
                        FMLLog.log.error("An error occurred extracting dependency", e);
                    }
                }
            } else {
                try {
                    Artifact artifact = readArtifact(modlist.getRepository(), meta);
                    File target = artifact.getFile();
                    if (target.exists()) {
                        FMLLog.log.debug(
                                "Found existing ContainedDep {}({}) from {} extracted to {}, skipping extraction",
                                dep, artifact.toString(), target.getCanonicalPath(), jar.getName());
                        if (!ENABLE_AUTO_MOD_MOVEMENT) {
                            Pair<?, ?> child = extractPacked(target, modlist, modDirs); //If we're not building a real list we have to re-build the dep list every run. So search down.
                            if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                            {
                                modlist.add(artifact);
                            }
                        }
                    } else {
                        FMLLog.log.debug("Extracting ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());
                        Files.createParentDirs(target);
                        try (FileOutputStream out = new FileOutputStream(target);
                                InputStream in = data == null ? jar.getInputStream(depEntry)
                                        : new ByteArrayInputStream(data)) {
                            ByteStreams.copy(in, out);
                        }
                        FMLLog.log.debug("Extracted ContainedDep {}({}) from {} to {}", dep,
                                artifact.toString(), jar.getName(), target.getCanonicalPath());

                        if (artifact.isSnapshot()) {
                            SnapshotJson json = SnapshotJson.create(artifact.getSnapshotMeta());
                            json.add(new SnapshotJson.Entry(artifact.getTimestamp(), meta.getValue(MD5)));
                            json.write(artifact.getSnapshotMeta());
                        }

                        if (!DISABLE_EXTERNAL_MANIFEST) {
                            File meta_target = new File(target.getAbsolutePath() + ".meta");
                            Files.write(manifest_data, meta_target);
                        }
                        Pair<?, ?> child = extractPacked(target, modlist, modDirs);
                        if (child == null && metaEntry != null) //External meta with no internal name... If there is a internal name, we trust that that name is the correct one.
                        {
                            modlist.add(artifact);
                        }
                    }
                } catch (NumberFormatException nfe) {
                    FMLLog.log.error(FMLLog.log.getMessageFactory().newMessage(
                            "An error occurred extracting dependency. Invalid Timestamp: {}",
                            meta.getValue(TIMESTAMP)), nfe);
                } catch (IOException e) {
                    FMLLog.log.error("An error occurred extracting dependency", e);
                }
            }
        }
    }

    if (attrs.containsKey(MAVEN_ARTIFACT)) {
        Artifact artifact = readArtifact(modlist.getRepository(), attrs);
        modlist.add(artifact);
        return Pair.of(artifact, readAll(jar.getInputStream(manifest_entry)));
    }
    return null;
}

From source file:com.github.sampov2.OneJarMojo.java

/**
  * Adds option to manifest entries, if applicable.
  * @param optionToCheck to perform null check, if null then nothing added
  * @param mainAttributes to add to//from   w  w  w.  j  a  va 2  s  .  co m
  * @param keyPairToSet both the key and value to add if applicable
  * @param entryNamesForValue keys to look for to prevent duplicating or overwriting keys
  */
private void setOptional(Object optionToCheck, Attributes mainAttributes, AttributeEntry keyPairToSet,
        String... entryNamesForValue) {
    if (optionToCheck != null) {
        for (String keyToCheck : entryNamesForValue) {
            if (mainAttributes.containsKey(keyToCheck)) {
                // key is already set, don't override
                return;
            }
        }
        // if key not found, add it
        mainAttributes.putValue(keyPairToSet.getKey(), keyPairToSet.getValue());
    }
}

From source file:net.minecraftforge.fml.relauncher.CoreModManager.java

private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader) {
    ModListHelper.parseModList(mcDir);// w w  w .  jav  a  2s  .  c om
    FMLRelaunchLog.fine("Discovering coremods");
    File coreMods = setupCoreModDir(mcDir);
    FilenameFilter ff = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    };
    FilenameFilter derpfilter = new FilenameFilter() {
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar.zip");
        }
    };
    File[] derplist = coreMods.listFiles(derpfilter);
    if (derplist != null && derplist.length > 0) {
        FMLRelaunchLog.severe(
                "FML has detected several badly downloaded jar files,  which have been named as zip files. You probably need to download them again, or they may not work properly");
        for (File f : derplist) {
            FMLRelaunchLog.severe("Problem file : %s", f.getName());
        }
    }
    FileFilter derpdirfilter = new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() && new File(pathname, "META-INF").isDirectory();
        }

    };
    File[] derpdirlist = coreMods.listFiles(derpdirfilter);
    if (derpdirlist != null && derpdirlist.length > 0) {
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "There appear to be jars extracted into the mods directory. This is VERY BAD and will almost NEVER WORK WELL");
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "You should place original jars only in the mods directory. NEVER extract them to the mods directory.");
        FMLRelaunchLog.log.getLogger().log(Level.FATAL,
                "The directories below appear to be extracted jar files. Fix this before you continue.");

        for (File f : derpdirlist) {
            FMLRelaunchLog.log.getLogger().log(Level.FATAL, "Directory {} contains {}", f.getName(),
                    Arrays.asList(new File(f, "META-INF").list()));
        }

        RuntimeException re = new RuntimeException("Extracted mod jars found, loading will NOT continue");
        // We're generating a crash report for the launcher to show to the user here
        try {
            Class<?> crashreportclass = classLoader.loadClass("b");
            Object crashreport = crashreportclass.getMethod("a", Throwable.class, String.class).invoke(null, re,
                    "FML has discovered extracted jar files in the mods directory.\nThis breaks mod loading functionality completely.\nRemove the directories and replace with the jar files originally provided.");
            File crashreportfile = new File(new File(coreMods.getParentFile(), "crash-reports"),
                    String.format("fml-crash-%1$tY-%1$tm-%1$td_%1$tT.txt", Calendar.getInstance()));
            crashreportclass.getMethod("a", File.class).invoke(crashreport, crashreportfile);
            System.out.println("#@!@# FML has crashed the game deliberately. Crash report saved to: #@!@# "
                    + crashreportfile.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
            // NOOP - hopefully
        }
        throw re;
    }
    File[] coreModList = coreMods.listFiles(ff);
    File versionedModDir = new File(coreMods, FMLInjectionData.mccversion);
    if (versionedModDir.isDirectory()) {
        File[] versionedCoreMods = versionedModDir.listFiles(ff);
        coreModList = ObjectArrays.concat(coreModList, versionedCoreMods, File.class);
    }

    coreModList = ObjectArrays.concat(coreModList, ModListHelper.additionalMods.values().toArray(new File[0]),
            File.class);

    coreModList = FileListHelper.sortFileList(coreModList);

    for (File coreMod : coreModList) {
        FMLRelaunchLog.fine("Examining for coremod candidacy %s", coreMod.getName());
        JarFile jar = null;
        Attributes mfAttributes;
        String fmlCorePlugin;
        try {
            jar = new JarFile(coreMod);
            if (jar.getManifest() == null) {
                // Not a coremod and no access transformer list
                continue;
            }
            ModAccessTransformer.addJar(jar);
            mfAttributes = jar.getManifest().getMainAttributes();
            String cascadedTweaker = mfAttributes.getValue("TweakClass");
            if (cascadedTweaker != null) {
                FMLRelaunchLog.info("Loading tweaker %s from %s", cascadedTweaker, coreMod.getName());
                Integer sortOrder = Ints.tryParse(Strings.nullToEmpty(mfAttributes.getValue("TweakOrder")));
                sortOrder = (sortOrder == null ? Integer.valueOf(0) : sortOrder);
                handleCascadingTweak(coreMod, jar, cascadedTweaker, classLoader, sortOrder);
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            List<String> modTypes = mfAttributes.containsKey(MODTYPE)
                    ? Arrays.asList(mfAttributes.getValue(MODTYPE).split(","))
                    : ImmutableList.of("FML");

            if (!modTypes.contains("FML")) {
                FMLRelaunchLog.fine(
                        "Adding %s to the list of things to skip. It is not an FML mod,  it has types %s",
                        coreMod.getName(), modTypes);
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            String modSide = mfAttributes.containsKey(MODSIDE) ? mfAttributes.getValue(MODSIDE) : "BOTH";
            if (!("BOTH".equals(modSide) || FMLLaunchHandler.side.name().equals(modSide))) {
                FMLRelaunchLog.fine("Mod %s has ModSide meta-inf value %s, and we're %s. It will be ignored",
                        coreMod.getName(), modSide, FMLLaunchHandler.side.name());
                ignoredModFiles.add(coreMod.getName());
                continue;
            }
            ModListHelper.additionalMods.putAll(extractContainedDepJars(jar, coreMods, versionedModDir));
            fmlCorePlugin = mfAttributes.getValue("FMLCorePlugin");
            if (fmlCorePlugin == null) {
                // Not a coremod
                FMLRelaunchLog.fine("Not found coremod data in %s", coreMod.getName());
                continue;
            }
        } catch (IOException ioe) {
            FMLRelaunchLog.log(Level.ERROR, ioe, "Unable to read the jar file %s - ignoring",
                    coreMod.getName());
            continue;
        } finally {
            if (jar != null) {
                try {
                    jar.close();
                } catch (IOException e) {
                    // Noise
                }
            }
        }
        // Support things that are mod jars, but not FML mod jars
        try {
            classLoader.addURL(coreMod.toURI().toURL());
            if (!mfAttributes.containsKey(COREMODCONTAINSFMLMOD)) {
                FMLRelaunchLog.finer("Adding %s to the list of known coremods, it will not be examined again",
                        coreMod.getName());
                ignoredModFiles.add(coreMod.getName());
            } else {
                FMLRelaunchLog.finer(
                        "Found FMLCorePluginContainsFMLMod marker in %s, it will be examined later for regular @Mod instances",
                        coreMod.getName());
                candidateModFiles.add(coreMod.getName());
            }
        } catch (MalformedURLException e) {
            FMLRelaunchLog.log(Level.ERROR, e, "Unable to convert file into a URL. weird");
            continue;
        }
        loadCoreMod(classLoader, fmlCorePlugin, coreMod);
    }
}

From source file:ca.weblite.jdeploy.JDeploy.java

private File[] findJarCandidates() throws IOException {
    File[] jars = findCandidates(directory.toPath().getFileSystem().getPathMatcher("glob:**/*.jar"));
    List<File> out = new ArrayList<File>();
    // We only want executable jars
    for (File f : jars) {
        Manifest m = new JarFile(f).getManifest();
        //System.out.println(m.getEntries());
        if (m != null) {
            Attributes atts = m.getMainAttributes();
            if (atts.containsKey(Attributes.Name.MAIN_CLASS)) {
                //executable jar
                out.add(f);//from www. j ava 2s .c om
            }
        }
    }
    return out.toArray(new File[out.size()]);
}

From source file:org.apache.hadoop.util.TestClasspath.java

/**
 * Asserts that the specified file is a jar file with a manifest containing a
 * non-empty classpath attribute.//ww w .  j av a  2 s .  c  om
 *
 * @param file File to check
 * @throws IOException if there is an I/O error
 */
private static void assertJar(File file) throws IOException {
    JarFile jarFile = null;
    try {
        jarFile = new JarFile(file);
        Manifest manifest = jarFile.getManifest();
        assertNotNull(manifest);
        Attributes mainAttributes = manifest.getMainAttributes();
        assertNotNull(mainAttributes);
        assertTrue(mainAttributes.containsKey(Attributes.Name.CLASS_PATH));
        String classPathAttr = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
        assertNotNull(classPathAttr);
        assertFalse(classPathAttr.isEmpty());
    } finally {
        // It's too bad JarFile doesn't implement Closeable.
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException e) {
                LOG.warn("exception closing jarFile: " + jarFile, e);
            }
        }
    }
}

From source file:org.jahia.services.modulemanager.util.ModuleUtils.java

/**
 * Checks if the artifact manifest requires adjustments in the capability headers w.r.t. module dependencies.
 *
 * @param atts the manifest attributes to be checked
 *
 * @return <code>true</code> if the artifact manifest requires adjustments in the capability headers w.r.t. module dependencies;
 *         <code>false</code> if it already contains that info
 *//*from  ww  w . j  a  va 2s.  c  o m*/
public static boolean requiresTransformation(Attributes atts) {
    return !StringUtils.contains(atts.getValue(ATTR_NAME_PROVIDE_CAPABILITY),
            OSGI_CAPABILITY_MODULE_DEPENDENCIES) && !atts.containsKey(ATTR_NAME_FRAGMENT_HOST);
}

From source file:org.kepler.kar.KARFile.java

/**
 * @param lsid/*w w w  .j  ava  2  s . c  o m*/
 * @throws IOException
 */
public void setLSID(KeplerLSID lsid) throws IOException {
    Attributes atts = getManifest().getMainAttributes();
    if (atts.containsKey(LSID)) {
        atts.remove(LSID);
    }
    atts.put(LSID, lsid.toString());
}

From source file:org.kepler.kar.KARFile.java

/**
 * Set the version of the KARFile./*w ww.  ja  va 2  s. c  om*/
 * 
 * @param version
 * @throws IOException
 *             if the given version is not supported
 */
public void setVersion(String version) throws IOException {
    if (_supportedVersions.contains(version)) {
        Attributes atts = getManifest().getMainAttributes();
        if (atts.containsKey(KAR_VERSION)) {
            atts.remove(KAR_VERSION);
        }
        atts.put(KAR_VERSION, version);
    } else {
        throw new IOException(version + " is not a supported KAR version.\n" + getSupportedVersionString());
    }
}