Example usage for java.util.jar JarFile getManifest

List of usage examples for java.util.jar JarFile getManifest

Introduction

In this page you can find the example usage for java.util.jar JarFile getManifest.

Prototype

public Manifest getManifest() throws IOException 

Source Link

Document

Returns the jar file manifest, or null if none.

Usage

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

private static void discoverCoreMods(File mcDir, LaunchClassLoader classLoader) {
    ModListHelper.parseModList(mcDir);//from   w w w.  ja  v  a  2  s  . c o  m
    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:ml.shifu.shifu.ShifuCLI.java

/**
 * print version info for shifu//from w  ww .  j  a  va 2 s  . c o  m
 */
private static void printLogoAndVersion() {
    String findContainingJar = JarManager.findContainingJar(ShifuCLI.class);
    JarFile jar = null;
    try {
        jar = new JarFile(findContainingJar);
        final Manifest manifest = jar.getManifest();

        String vendor = manifest.getMainAttributes().getValue("vendor");
        String title = manifest.getMainAttributes().getValue("title");
        String version = manifest.getMainAttributes().getValue("version");
        String timestamp = manifest.getMainAttributes().getValue("timestamp");
        System.out.println(" ____  _   _ ___ _____ _   _ ");
        System.out.println("/ ___|| | | |_ _|  ___| | | |");
        System.out.println("\\___ \\| |_| || || |_  | | | |");
        System.out.println(" ___) |  _  || ||  _| | |_| |");
        System.out.println("|____/|_| |_|___|_|    \\___/ ");
        System.out.println("                             ");
        System.out.println(vendor + " " + title + " version " + version + " \ncompiled " + timestamp);
    } catch (Exception e) {
        throw new RuntimeException("unable to read pigs manifest file", e);
    } finally {
        if (jar != null) {
            try {
                jar.close();
            } catch (IOException e) {
                throw new RuntimeException("jar closed failed", e);
            }
        }
    }
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static String getManifestEntriesAttrs(JarFile jar) throws IOException {

    StringBuilder sbManifest = new StringBuilder();

    // Get current manifest
    Manifest manifest = jar.getManifest();

    // Write out entry attributes to manifest
    if (manifest != null) {
        // Get entry attributes
        Map<String, Attributes> entries = manifest.getEntries();

        boolean firstEntry = true;

        // For each entry...
        for (String entryName : entries.keySet()) {
            // Get entry's attributes
            Attributes entryAttrs = entries.get(entryName);

            // Completely ignore entries that contain only a xxx-Digest
            // attribute
            if ((entryAttrs.size() == 1) && (entryAttrs.keySet().toArray()[0].toString().endsWith("-Digest"))) {
                continue;
            }//from w ww .java 2s . com

            if (!firstEntry) {
                // Entries subequent to the first are split by a newline
                sbManifest.append(CRLF);
            }

            // Get entry attributes as a string to preserve their order
            String manifestEntryAttributes = getManifestEntryAttrs(jar, entryName);

            // Write them out
            sbManifest.append(manifestEntryAttributes);

            // The next entry will not be the first entry
            firstEntry = false;
        }
    }

    return sbManifest.toString();
}

From source file:net.sf.keystore_explorer.crypto.signing.JarSigner.java

private static String getManifestMainAttrs(JarFile jar, String signer) throws IOException {

    StringBuilder sbManifest = new StringBuilder();

    // Get current manifest
    Manifest manifest = jar.getManifest();

    // Write out main attributes to manifest

    if (manifest == null) {
        // No current manifest - write out main attributes
        // ("Manifest Version" and "Created By")
        sbManifest.append(createAttributeText(MANIFEST_VERSION_ATTR, MANIFEST_VERSION));
        sbManifest.append(CRLF);//w  ww  . j a va 2s.c  o  m

        sbManifest.append(createAttributeText(CREATED_BY_ATTR, signer));
        sbManifest.append(CRLF);

        sbManifest.append(CRLF);
    } else {
        // Get main attributes as a string to preserve their order
        String manifestMainAttrs = getManifestMainAttrs(jar);

        // Write them out
        sbManifest.append(manifestMainAttrs);
        sbManifest.append(CRLF);
    }

    return sbManifest.toString();
}

From source file:com.smash.revolance.ui.model.application.ApplicationFactory.java

private void loadApplication(String appDir, String appId, String impl, String version) throws IOException {
    if (!appDir.isEmpty() && new File(appDir).isDirectory()) {
        Collection<File> files = FileUtils.listFiles(new File(appDir), new String[] { "jar" }, false);

        for (File file : files) {
            JarFile jar = new JarFile(file);
            Manifest manifest = jar.getManifest();
            Attributes attributes = manifest.getMainAttributes();

            String implAttr = attributes.getValue("revolance-ui-explorer-applicationImpl");
            String versionAttr = attributes.getValue("revolance-ui-explorer-applicationVersion");

            if (implAttr.contentEquals(impl) && (versionAttr.contentEquals(version) || version == null)) {
                applicationLoaders.put(getKey(appId, impl, version), new JarClassLoader(file.toURI().toURL()));
            }/*from  ww  w .j a  v  a  2  s  . co  m*/
        }

    }
}

From source file:org.mc4j.ems.connection.support.metadata.AbstractConnectionTypeDescriptor.java

public String getServerVersion(File recognitionFile) {
    try {/*from ww  w . j  a  va2 s .c  o  m*/
        String version;
        JarFile recJarFile = new JarFile(recognitionFile);

        version = recJarFile.getManifest().getMainAttributes().getValue("Implementation-Version");

        if (version == null) {
            Map attrMap = recJarFile.getManifest().getEntries();
            for (Iterator iterator = attrMap.entrySet().iterator(); iterator.hasNext();) {
                Map.Entry entry = (Map.Entry) iterator.next();
                String name = (String) entry.getKey();
                Attributes attr = (Attributes) entry.getValue();
                version = attr.getValue("Implementation-Version");
            }
        }
        return version;
    } catch (MalformedURLException e) {
        log.warn("Could not determine server version from matched file " + recognitionFile.getAbsolutePath(),
                e);
    } catch (IOException e) {
        log.warn("Could not determine server version from matched file " + recognitionFile.getAbsolutePath(),
                e);
    }
    return null;
}

From source file:com.github.dirkraft.jash.ShExecutableJarBundler.java

@Override
public List<String> validateAndInit() throws Exception {
    List<String> errors = super.validateAndInit();

    if (!jarFile.isFile()) {
        errors.add(jarFile + " is not a file.");
        return errors;
    }/*from www  .  j a  v a 2  s  .  c  o m*/

    JarFile jar = new JarFile(jarFile);
    Manifest manifest = jar.getManifest();
    String mainClass = manifest.getMainAttributes().getValue(Attributes.Name.MAIN_CLASS);
    ClassLoader jarClassLoader = URLClassLoader.newInstance(new URL[] { jarFile.toURI().toURL() });
    try {
        ClassUtils.getClass(jarClassLoader, mainClass, false);
    } catch (ClassNotFoundException e) {
        errors.add("Could not find Main-Class: " + mainClass + " in jar " + jarFile.getAbsolutePath());
        return errors;
    }

    _targetBinary = outputDir.toPath().resolve(commandName).toFile();
    if (_targetBinary.exists()) {
        errors.add("Target binary path " + _targetBinary.getAbsolutePath()
                + " is occupied. Will not overwrite, so aborting.");
    }

    return errors;
}

From source file:org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.TestContainerLaunch.java

private static List<String> getJarManifestClasspath(String path) throws Exception {
    List<String> classpath = new ArrayList<String>();
    JarFile jarFile = new JarFile(path);
    Manifest manifest = jarFile.getManifest();
    String cps = manifest.getMainAttributes().getValue("Class-Path");
    StringTokenizer cptok = new StringTokenizer(cps);
    while (cptok.hasMoreTokens()) {
        String cpentry = cptok.nextToken();
        classpath.add(cpentry);// w  ww.  j ava 2s.  co m
    }
    return classpath;
}

From source file:org.pentaho.webpackage.deployer.archive.impl.WebPackageURLConnectionTest.java

@Test
public void testZipFileWithMacOsMetadata() throws Exception {
    JarFile jarFile = getDeployedJar(getResourceUrl("/macos.zip"));

    Manifest manifest = jarFile.getManifest();

    verifyManifest(manifest, "my-module", "1.4.2");
}

From source file:com.npower.dm.msm.JADCreator.java

public SoftwareInformation getSoftwareInformation(File file) throws IOException {
    JarFile jar = new JarFile(file);
    Manifest manifest = jar.getManifest();
    SoftwareInformation info = new SoftwareInformation();
    info.setVendor(manifest.getMainAttributes().getValue("MIDlet-Vendor"));
    info.setName(manifest.getMainAttributes().getValue("MIDlet-Name"));
    info.setVersion(manifest.getMainAttributes().getValue("MIDlet-Version"));
    String midpVersion = manifest.getMainAttributes().getValue("MicroEdition-Profile");
    if (StringUtils.isNotEmpty(midpVersion) && midpVersion.trim().equalsIgnoreCase("MIDP-2.0")) {
        info.setMidp2(true);//from w  w w.j av  a  2s.  co  m
    }
    return info;
}