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:info.dolezel.fatrat.plugins.helpers.JarClassLoader.java

private static void getPackageVersion(File fo, Map<String, String> rv) throws IOException {
    if (!fo.exists())
        return;/*  w  w w  .j  a v a  2 s  .  c  o m*/

    JarFile file = new JarFile(fo);
    Manifest manifest = file.getManifest();
    Attributes attr = manifest.getMainAttributes();

    rv.put(fo.getName(), attr.getValue("Implementation-Version"));
}

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./*from  w  w  w  .  j  a v  a2  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:net.fabricmc.installer.installer.ClientInstaller.java

public static void install(File mcDir, String version, IInstallerProgress progress, File fabricJar)
        throws IOException {
    progress.updateProgress(Translator.getString("gui.installing") + ": " + version, 0);
    JarFile jarFile = new JarFile(fabricJar);
    Attributes attributes = jarFile.getManifest().getMainAttributes();

    String id = "fabric-" + attributes.getValue("FabricVersion");

    System.out.println(Translator.getString("gui.installing") + " " + id);
    File versionsFolder = new File(mcDir, "versions");
    File fabricVersionFolder = new File(versionsFolder, id);
    File mcVersionFolder = new File(versionsFolder, version);
    File fabricJsonFile = new File(fabricVersionFolder, id + ".json");

    File tempWorkDir = new File(fabricVersionFolder, "temp");
    ZipUtil.unpack(fabricJar, tempWorkDir, name -> {
        if (name.startsWith(Reference.INSTALLER_METADATA_FILENAME)) {
            return name;
        } else {/*w  ww . ja v  a 2 s  .co  m*/
            return null;
        }
    });
    InstallerMetadata metadata = new InstallerMetadata(tempWorkDir);

    File mcJarFile = new File(mcVersionFolder, version + ".jar");
    if (fabricVersionFolder.exists()) {
        progress.updateProgress(Translator.getString("install.client.removeOld"), 10);
        FileUtils.deleteDirectory(fabricVersionFolder);
    }
    fabricVersionFolder.mkdirs();

    progress.updateProgress(Translator.getString("install.client.createJson"), 20);

    String mcJson = FileUtils.readFileToString(mcJarFile, Charset.defaultCharset());

    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    JsonObject versionJson = new JsonObject();
    versionJson.addProperty("id", id);
    versionJson.addProperty("type", "release");
    versionJson.addProperty("time", Utils.ISO_8601.format(fabricJar.lastModified()));
    versionJson.addProperty("releaseTime", Utils.ISO_8601.format(fabricJar.lastModified()));
    versionJson.addProperty("mainClass", metadata.getMainClass());
    versionJson.addProperty("inheritsFrom", version);

    JsonArray gameArgs = new JsonArray();
    JsonObject arguments = new JsonObject();

    List<String> metadataTweakers = metadata.getTweakers("client", "common");
    if (metadataTweakers.size() > 1) {
        throw new RuntimeException("Not supporting > 1 tweaker yet!");
    }

    metadata.getArguments("client", "common").forEach(gameArgs::add);
    gameArgs.add("--tweakClass");
    gameArgs.add(metadataTweakers.get(0));

    arguments.add("game", gameArgs);
    versionJson.add("arguments", arguments);

    JsonArray libraries = new JsonArray();

    addDep(Reference.PACKAGE_FABRIC + ":" + Reference.NAME_FABRIC_LOADER + ":"
            + attributes.getValue("FabricVersion"), "http://maven.modmuss50.me/", libraries);

    for (InstallerMetadata.LibraryEntry entry : metadata.getLibraries("client", "common")) {
        libraries.add(entry.toVanillaEntry());
    }

    versionJson.add("libraries", libraries);

    FileUtils.write(fabricJsonFile, gson.toJson(versionJson), "UTF-8");
    jarFile.close();
    progress.updateProgress(Translator.getString("install.client.cleanDir"), 90);
    FileUtils.deleteDirectory(tempWorkDir);

    progress.updateProgress(Translator.getString("install.success"), 100);
}

From source file:net.sf.keystore_explorer.crypto.jcepolicy.JcePolicyUtil.java

/**
 * Get a JCE policy's crypto strength.//from   w  ww .  j a  va 2s .  c om
 *
 * @param jcePolicy
 *            JCE policy
 * @return Crypto strength
 * @throws CryptoException
 *             If there was a problem getting the crypto strength
 */
public static CryptoStrength getCryptoStrength(JcePolicy jcePolicy) throws CryptoException {
    try {
        File file = getJarFile(jcePolicy);

        // if there is no policy file at all, we assume that we are running under OpenJDK
        if (!file.exists()) {
            return UNLIMITED;
        }

        JarFile jar = new JarFile(file);

        Manifest jarManifest = jar.getManifest();
        String strength = jarManifest.getMainAttributes().getValue("Crypto-Strength");

        // workaround for IBM JDK: test for maximum key size
        if (strength == null) {
            return unlimitedStrengthTest();
        }

        if (strength.equals(LIMITED.manifestValue())) {
            return LIMITED;
        } else {
            return UNLIMITED;
        }
    } catch (IOException ex) {
        throw new CryptoException(
                MessageFormat.format(res.getString("NoGetCryptoStrength.exception.message"), jcePolicy), ex);
    }
}

From source file:com.arcusys.liferay.vaadinplugin.util.WidgetsetUtil.java

private static void includeVaadinAddonJar(File file, List<VaadinAddonInfo> addons) {
    try {//from  w  ww . ja  v  a  2 s .  c  o m
        URL url = new URL("file:" + file.getCanonicalPath());
        url = new URL("jar:" + url.toExternalForm() + "!/");
        JarURLConnection conn = (JarURLConnection) url.openConnection();
        JarFile jarFile = conn.getJarFile();
        if (jarFile != null) {
            Manifest manifest = jarFile.getManifest();
            if (manifest == null) {
                // No manifest so this is not a Vaadin Add-on
                return;
            }

            Attributes attrs = manifest.getMainAttributes();
            String value = attrs.getValue("Vaadin-Widgetsets");
            if (value != null) {
                String name = attrs.getValue("Implementation-Title");
                String version = attrs.getValue("Implementation-Version");
                if (name == null || version == null) {
                    // A jar file with Vaadin-Widgetsets but name or version
                    // missing. Most probably vaadin.jar itself, skipping it
                    // here
                    return;
                }

                List<String> widgetsets = new ArrayList<String>();
                String[] widgetsetNames = value.split(",");
                for (String wName : widgetsetNames) {
                    String widgetsetname = wName.trim().intern();
                    if (!widgetsetname.equals("")) {
                        widgetsets.add(widgetsetname);
                    }
                }

                if (!widgetsets.isEmpty()) {
                    addons.add(new VaadinAddonInfo(name, version, file, widgetsets));
                }
            }
        }
    } catch (Exception e) {
        log.warn("Exception trying to include Vaadin Add-ons.", e);
    }

}

From source file:Zip.java

/**
 * Reads a Jar file, displaying the attributes in its manifest and dumping
 * the contents of each file contained to the console.
 *//*w w  w  . ja v  a2  s. com*/
public static void readJarFile(String fileName) {
    JarFile jarFile = null;
    try {
        // JarFile extends ZipFile and adds manifest information
        jarFile = new JarFile(fileName);
        if (jarFile.getManifest() != null) {
            System.out.println("Manifest Main Attributes:");
            Iterator iter = jarFile.getManifest().getMainAttributes().keySet().iterator();
            while (iter.hasNext()) {
                Attributes.Name attribute = (Attributes.Name) iter.next();
                System.out.println(
                        attribute + " : " + jarFile.getManifest().getMainAttributes().getValue(attribute));
            }
            System.out.println();
        }
        // use the Enumeration to dump the contents of each file to the console
        System.out.println("Jar file entries:");
        for (Enumeration e = jarFile.entries(); e.hasMoreElements();) {
            JarEntry jarEntry = (JarEntry) e.nextElement();
            if (!jarEntry.isDirectory()) {
                System.out.println(jarEntry.getName() + " contains:");
                BufferedReader jarReader = new BufferedReader(
                        new InputStreamReader(jarFile.getInputStream(jarEntry)));
                while (jarReader.ready()) {
                    System.out.println(jarReader.readLine());
                }
                jarReader.close();
            }
        }
    } catch (IOException ioe) {
        System.out.println("An IOException occurred: " + ioe.getMessage());
    } finally {
        if (jarFile != null) {
            try {
                jarFile.close();
            } catch (IOException ioe) {
            }
        }
    }
}

From source file:org.broadleafcommerce.common.extensibility.InstrumentationRuntimeFactory.java

private static boolean validateAgentJarManifest(File agentJarFile, String agentClassName) {
    try {//ww  w.  j  a  v a 2  s  .c o m
        JarFile jar = new JarFile(agentJarFile);
        Manifest manifest = jar.getManifest();
        if (manifest == null) {
            return false;
        }
        Attributes attributes = manifest.getMainAttributes();
        String ac = attributes.getValue("Agent-Class");
        if (ac != null && ac.equals(agentClassName)) {
            return true;
        }
    } catch (Exception e) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Unexpected exception occured.", e);
        }
    }
    return false;
}

From source file:org.ebayopensource.turmeric.tools.codegen.util.ClassPathUtil.java

private static List<File> getJarClassPathRefs(File file) {
    List<File> refs = new ArrayList<File>();

    JarFile jar = null;
    try {//from  w w w .  j a v  a2 s  .  c o  m
        jar = new JarFile(file);
        Manifest manifest = jar.getManifest();
        if (manifest == null) {
            // No manifest, no classpath.
            return refs;
        }

        Attributes attrs = manifest.getMainAttributes();
        if (attrs == null) {
            /*
             * No main attributes. (not sure how that's possible, but we can skip this jar)
             */
            return refs;
        }
        String classPath = attrs.getValue(Attributes.Name.CLASS_PATH);
        if (CodeGenUtil.isEmptyString(classPath)) {
            return refs;
        }

        String parentDir = FilenameUtils.getFullPath(file.getAbsolutePath());
        File possible;
        for (String path : StringUtils.splitStr(classPath, ' ')) {
            possible = new File(path);

            if (!possible.isAbsolute()) {
                // relative path?
                possible = new File(FilenameUtils.normalize(parentDir + path));
            }

            if (!refs.contains(possible)) {
                refs.add(possible);
            }
        }
    } catch (IOException e) {
        LOG.log(Level.WARNING, "Unable to load/read/parse Jar File: " + file.getAbsolutePath(), e);
    } finally {
        CodeGenUtil.closeQuietly(jar);
    }

    return refs;
}

From source file:org.wso2.carbon.integration.framework.utils.CodeCoverageUtils.java

private synchronized static void addEmmaDynamicImportPackage(String jarFilePath) throws IOException {
    if (!jarFilePath.endsWith(".jar")) {
        throw new IllegalArgumentException(
                "Jar file should have the extension .jar. " + jarFilePath + " is invalid");
    }/*from w  w w.  j  a  va 2 s  .  c  o  m*/
    JarFile jarFile = new JarFile(jarFilePath);
    Manifest manifest = jarFile.getManifest();
    if (manifest == null) {
        throw new IllegalArgumentException(jarFilePath + " does not contain a MANIFEST.MF file");
    }
    String fileSeparator = (File.separatorChar == '\\') ? "\\" : File.separator;
    String jarFileName = jarFilePath;
    if (jarFilePath.lastIndexOf(fileSeparator) != -1) {
        jarFileName = jarFilePath.substring(jarFilePath.lastIndexOf(fileSeparator) + 1);
    }
    ArchiveManipulator archiveManipulator;
    String tempExtractedDir;
    try {
        archiveManipulator = new ArchiveManipulator();
        tempExtractedDir = System.getProperty("basedir") + File.separator + "target" + File.separator
                + jarFileName.substring(0, jarFileName.lastIndexOf('.'));
        new ArchiveManipulatorUtil().extractFile(jarFilePath, tempExtractedDir);
    } finally {
        jarFile.close();
    }

    String dynamicImports = manifest.getMainAttributes().getValue("DynamicImport-Package");
    if (dynamicImports != null) {
        manifest.getMainAttributes().putValue("DynamicImport-Package", dynamicImports + ",com.vladium.*");
    } else {
        manifest.getMainAttributes().putValue("DynamicImport-Package", "com.vladium.*");
    }
    File newManifest = new File(
            tempExtractedDir + File.separator + "META-INF" + File.separator + "MANIFEST.MF");
    FileOutputStream manifestOut = null;
    try {
        manifestOut = new FileOutputStream(newManifest);
        manifest.write(manifestOut);
    } catch (IOException e) {
        log.error("Could not write content to new MANIFEST.MF file", e);
    } finally {
        if (manifestOut != null) {
            manifestOut.close();
        }
    }
    archiveManipulator.archiveDir(jarFilePath, tempExtractedDir);
    FileManipulator.deleteDir(tempExtractedDir);
}

From source file:com.sinosoft.one.mvc.scanning.ResourceRef.java

public static ResourceRef toResourceRef(Resource folder) throws IOException {
    ResourceRef rr = new ResourceRef(folder, null, null);
    String[] modifiers = null;/*from  ww  w. j a  v  a  2s  .co  m*/
    Resource mvcPropertiesResource = rr.getInnerResource("META-INF/mvc.properties");
    if (mvcPropertiesResource.exists()) {
        if (logger.isDebugEnabled()) {
            logger.debug("found mvc.properties: " + mvcPropertiesResource.getURI());
        }
        InputStream in = mvcPropertiesResource.getInputStream();
        rr.properties.load(in);
        in.close();
        String attrValue = rr.properties.getProperty("mvc");
        if (attrValue == null) {
            attrValue = rr.properties.getProperty("Mvc");
        }
        if (attrValue != null) {
            modifiers = StringUtils.split(attrValue, ", ;\n\r\t");
            if (logger.isDebugEnabled()) {
                logger.debug("modifiers[by properties][" + rr.getResource().getURI() + "]="
                        + Arrays.toString(modifiers));
            }
        }
    }
    //
    if (modifiers == null) {
        if (!"jar".equals(rr.getProtocol())) {
            modifiers = new String[] { "**" };
            if (logger.isDebugEnabled()) {
                logger.debug("modifiers[by default][" + rr.getResource().getURI() + "]="
                        + Arrays.toString(modifiers));
            }
        } else {
            JarFile jarFile = new JarFile(rr.getResource().getFile());
            Manifest manifest = jarFile.getManifest();
            if (manifest != null) {
                Attributes attributes = manifest.getMainAttributes();
                String attrValue = attributes.getValue("mvc");
                if (attrValue == null) {
                    attrValue = attributes.getValue("Mvc");
                }
                if (attrValue != null) {
                    modifiers = StringUtils.split(attrValue, ", ;\n\r\t");
                    if (logger.isDebugEnabled()) {
                        logger.debug("modifiers[by manifest.mf][" + rr.getResource().getURI() + "]="
                                + Arrays.toString(modifiers));
                    }
                }
            }
        }
    }
    rr.setModifiers(modifiers);
    return rr;
}