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:org.deventropy.shared.utils.DirectoryArchiverUtilTest.java

private void checkJarArchive(final File archiveFile, final File sourceDirectory, final String pathPrefix)
        throws IOException {

    JarFile jarFile = null;
    try {/*from   www . ja v a 2  s .  co  m*/
        jarFile = new JarFile(archiveFile);

        final Manifest manifest = jarFile.getManifest();
        assertNotNull("Manifest should be present", manifest);
        assertEquals("Manifest version should be 1.0", "1.0",
                manifest.getMainAttributes().getValue(Attributes.Name.MANIFEST_VERSION));

        final ArchiveEntries archiveEntries = createArchiveEntries(sourceDirectory, pathPrefix);

        final Enumeration<JarEntry> entries = jarFile.entries();

        while (entries.hasMoreElements()) {
            final JarEntry jarEntry = entries.nextElement();
            if (MANIFEST_FILE_ENTRY_NAME.equalsIgnoreCase(jarEntry.getName())) {
                // It is the manifest file, not added by use
                continue;
            }
            if (jarEntry.isDirectory()) {
                assertTrue("Directory in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.dirs.contains(jarEntry.getName()));
                archiveEntries.dirs.remove(jarEntry.getName());
            } else {
                assertTrue("File in jar should be from us [" + jarEntry.getName() + "]",
                        archiveEntries.files.containsKey(jarEntry.getName()));
                final byte[] inflatedMd5 = getMd5Digest(jarFile.getInputStream(jarEntry), false);
                assertArrayEquals("MD5 hash of files should equal [" + jarEntry.getName() + "]",
                        archiveEntries.files.get(jarEntry.getName()), inflatedMd5);
                archiveEntries.files.remove(jarEntry.getName());
            }
        }

        // Check that all files and directories have been accounted for
        assertTrue("All directories should be in the jar", archiveEntries.dirs.isEmpty());
        assertTrue("All files should be in the jar", archiveEntries.files.isEmpty());
    } finally {
        if (null != jarFile) {
            jarFile.close();
        }
    }
}

From source file:net.minecraftforge.fml.common.asm.FMLSanityChecker.java

@Override
public Void call() throws Exception {
    CodeSource codeSource = getClass().getProtectionDomain().getCodeSource();
    boolean goodFML = false;
    boolean fmlIsJar = false;
    if (codeSource.getLocation().getProtocol().equals("jar")) {
        fmlIsJar = true;/*from  w  w  w  . j  a  va2 s  .c  o  m*/
        Certificate[] certificates = codeSource.getCertificates();
        if (certificates != null) {

            for (Certificate cert : certificates) {
                String fingerprint = CertificateHelper.getFingerprint(cert);
                if (fingerprint.equals(FMLFINGERPRINT)) {
                    FMLRelaunchLog.info("Found valid fingerprint for FML. Certificate fingerprint %s",
                            fingerprint);
                    goodFML = true;
                } else if (fingerprint.equals(FORGEFINGERPRINT)) {
                    FMLRelaunchLog.info(
                            "Found valid fingerprint for Minecraft Forge. Certificate fingerprint %s",
                            fingerprint);
                    goodFML = true;
                } else {
                    FMLRelaunchLog.severe("Found invalid fingerprint for FML: %s", fingerprint);
                }
            }
        }
    } else {
        goodFML = true;
    }
    // Server is not signed, so assume it's good - a deobf env is dev time so it's good too
    boolean goodMC = FMLLaunchHandler.side() == Side.SERVER || !liveEnv;
    int certCount = 0;
    try {
        Class<?> cbr = Class.forName("net.minecraft.client.ClientBrandRetriever", false, cl);
        codeSource = cbr.getProtectionDomain().getCodeSource();
    } catch (Exception e) {
        // Probably a development environment, or the server (the server is not signed)
        goodMC = true;
    }
    JarFile mcJarFile = null;
    if (fmlIsJar && !goodMC && codeSource.getLocation().getProtocol().equals("jar")) {
        try {
            String mcPath = codeSource.getLocation().getPath().substring(5);
            mcPath = mcPath.substring(0, mcPath.lastIndexOf('!'));
            mcPath = URLDecoder.decode(mcPath, Charsets.UTF_8.name());
            mcJarFile = new JarFile(mcPath, true);
            mcJarFile.getManifest();
            JarEntry cbrEntry = mcJarFile.getJarEntry("net/minecraft/client/ClientBrandRetriever.class");
            InputStream mcJarFileInputStream = mcJarFile.getInputStream(cbrEntry);
            try {
                ByteStreams.toByteArray(mcJarFileInputStream);
            } finally {
                IOUtils.closeQuietly(mcJarFileInputStream);
            }
            Certificate[] certificates = cbrEntry.getCertificates();
            certCount = certificates != null ? certificates.length : 0;
            if (certificates != null) {

                for (Certificate cert : certificates) {
                    String fingerprint = CertificateHelper.getFingerprint(cert);
                    if (fingerprint.equals(MCFINGERPRINT)) {
                        FMLRelaunchLog.info("Found valid fingerprint for Minecraft. Certificate fingerprint %s",
                                fingerprint);
                        goodMC = true;
                    }
                }
            }
        } catch (Throwable e) {
            FMLRelaunchLog.log(Level.ERROR, e,
                    "A critical error occurred trying to read the minecraft jar file");
        } finally {
            Java6Utils.closeZipQuietly(mcJarFile);
        }
    } else {
        goodMC = true;
    }
    if (!goodMC) {
        FMLRelaunchLog.severe(
                "The minecraft jar %s appears to be corrupt! There has been CRITICAL TAMPERING WITH MINECRAFT, it is highly unlikely minecraft will work! STOP NOW, get a clean copy and try again!",
                codeSource.getLocation().getFile());
        if (!Boolean.parseBoolean(System.getProperty("fml.ignoreInvalidMinecraftCertificates", "false"))) {
            FMLRelaunchLog.severe(
                    "For your safety, FML will not launch minecraft. You will need to fetch a clean version of the minecraft jar file");
            FMLRelaunchLog.severe(
                    "Technical information: The class net.minecraft.client.ClientBrandRetriever should have been associated with the minecraft jar file, "
                            + "and should have returned us a valid, intact minecraft jar location. This did not work. Either you have modified the minecraft jar file (if so "
                            + "run the forge installer again), or you are using a base editing jar that is changing this class (and likely others too). If you REALLY "
                            + "want to run minecraft in this configuration, add the flag -Dfml.ignoreInvalidMinecraftCertificates=true to the 'JVM settings' in your launcher profile.");
            FMLCommonHandler.instance().exitJava(1, false);
        } else {
            FMLRelaunchLog.severe(
                    "FML has been ordered to ignore the invalid or missing minecraft certificate. This is very likely to cause a problem!");
            FMLRelaunchLog.severe(
                    "Technical information: ClientBrandRetriever was at %s, there were %d certificates for it",
                    codeSource.getLocation(), certCount);
        }
    }
    if (!goodFML) {
        FMLRelaunchLog.severe("FML appears to be missing any signature data. This is not a good thing");
    }
    return null;
}

From source file:org.italiangrid.voms.container.Container.java

private void forceTaglibsLoading() {

    if (System.getProperty("voms.disableTaglibsLoading") != null) {
        log.warn("Taglibs loading disabled, as requested by voms.disableTaglibsLoading");
        return;//from  w w w.  ja  v a2  s  .c  o  m
    }

    try {

        String classpath = java.lang.System.getProperty("java.class.path");
        String entries[] = classpath.split(System.getProperty("path.separator"));

        if (entries.length >= 1) {

            JarFile f = new JarFile(entries[0]);
            Attributes attrs = f.getManifest().getMainAttributes();
            Name n = new Name("Class-Path");
            String jarClasspath = attrs.getValue(n);
            String jarEntries[] = jarClasspath.split(" ");

            boolean taglibsFound = false;

            for (String e : jarEntries) {
                if (e.contains(TAGLIBS_JAR_NAME)) {
                    taglibsFound = true;
                    ClassLoader currentClassLoader = Thread.currentThread().getContextClassLoader();

                    File taglibsJar = new File(e);
                    URLClassLoader newClassLoader = new URLClassLoader(new URL[] { taglibsJar.toURI().toURL() },
                            currentClassLoader);

                    Thread.currentThread().setContextClassLoader(newClassLoader);
                }
            }

            f.close();

            if (!taglibsFound) {
                throw new RuntimeException("Error configuring taglibs classloading!");
            }

        }
    } catch (IOException e) {
        log.error(e.getMessage(), e);
        System.exit(1);
    }
}

From source file:org.eclipse.ecr.testlib.NXRuntimeTestCase.java

protected void initUrls() throws Exception {
    ClassLoader classLoader = NXRuntimeTestCase.class.getClassLoader();
    if (classLoader instanceof URLClassLoader) {
        urls = ((URLClassLoader) classLoader).getURLs();
    } else if (classLoader.getClass().getName().equals("org.apache.tools.ant.AntClassLoader")) {
        Method method = classLoader.getClass().getMethod("getClasspath");
        String cp = (String) method.invoke(classLoader);
        String[] paths = cp.split(File.pathSeparator);
        urls = new URL[paths.length];
        for (int i = 0; i < paths.length; i++) {
            urls[i] = new URL("file:" + paths[i]);
        }/*  w  ww .java 2  s.com*/
    } else {
        log.warn("Unknow classloader type: " + classLoader.getClass().getName()
                + "\nWon't be able to load OSGI bundles");
        return;
    }
    // special case for maven surefire with useManifestOnlyJar
    if (urls.length == 1) {
        try {
            URI uri = urls[0].toURI();
            if (uri.getScheme().equals("file") && uri.getPath().contains("surefirebooter")) {
                JarFile jar = new JarFile(new File(uri));
                try {
                    String cp = jar.getManifest().getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
                    if (cp != null) {
                        String[] cpe = cp.split(" ");
                        URL[] newUrls = new URL[cpe.length];
                        for (int i = 0; i < cpe.length; i++) {
                            // Don't need to add 'file:' with maven surefire
                            // >= 2.4.2
                            String newUrl = cpe[i].startsWith("file:") ? cpe[i] : "file:" + cpe[i];
                            newUrls[i] = new URL(newUrl);
                        }
                        urls = newUrls;
                    }
                } finally {
                    jar.close();
                }
            }
        } catch (Exception e) {
            // skip
        }
    }
    StringBuilder sb = new StringBuilder();
    sb.append("URLs on the classpath: ");
    for (URL url : urls) {
        sb.append(url.toString());
        sb.append('\n');
    }
    log.debug(sb.toString());
    readUris = new HashSet<URI>();
    bundles = new HashMap<String, BundleFile>();
}

From source file:org.apache.pig.tools.pigstats.ScriptState.java

public String getPigVersion() {
    if (pigVersion == null) {
        String findContainingJar = JarManager.findContainingJar(ScriptState.class);
        if (findContainingJar != null) {
            try {
                JarFile jar = new JarFile(findContainingJar);
                final Manifest manifest = jar.getManifest();
                final Map<String, Attributes> attrs = manifest.getEntries();
                Attributes attr = attrs.get("org/apache/pig");
                pigVersion = attr.getValue("Implementation-Version");
            } catch (Exception e) {
                LOG.warn("unable to read pigs manifest file");
            }// w  ww  .ja va2 s.c o  m
        } else {
            LOG.warn("unable to read pigs manifest file. Not running from the Pig jar");
        }
    }
    return (pigVersion == null) ? "" : pigVersion;
}

From source file:com.basistech.bbhmp.RosapiBundleCollectorMojo.java

private boolean isJarFragment(File outputFile) throws MojoExecutionException, MojoFailureException {
    JarFile jar;
    try {//ww w  . j av  a 2s.c  om
        jar = new JarFile(outputFile);
    } catch (IOException e) {
        throw new MojoExecutionException(
                "Failed to open dependency we just copied " + outputFile.getAbsolutePath(), e);
    }
    final Manifest manifest;
    try {
        manifest = jar.getManifest();
    } catch (IOException e) {
        throw new MojoFailureException(
                "Failed to read manifest from dependency we just copied " + outputFile.getAbsolutePath(), e);
    }
    final Attributes mattr = manifest.getMainAttributes();
    // getValue is case-insensitive.
    String mfVersion = mattr.getValue("Bundle-ManifestVersion");
    /*
     * '2' is the only legitimate bundle manifest version. Version 1 is long obsolete, and not supported
     * in current containers. There's no plan on the horizon for a version 3. No version at all indicates
     * that the jar file is not an OSGi bundle at all.
     */
    if (!"2".equals(mfVersion)) {
        throw new MojoFailureException("Bundle-ManifestVersion is not '2' from dependency we just copied "
                + outputFile.getAbsolutePath());
    }
    String host = mattr.getValue("Fragment-Host");
    return host != null;
}

From source file:com.dtolabs.rundeck.ExpandRunServer.java

private void copyToolLibs(final File toolslibdir, final File coreJar) throws IOException {
    if (!toolslibdir.isDirectory()) {
        if (!toolslibdir.mkdirs()) {
            ERR("Couldn't create bin dir: " + toolslibdir.getAbsolutePath());
            return;
        }/*from   www.  j  ava  2  s  .c  o m*/
    }
    //get dependencies info
    final JarFile zf = new JarFile(coreJar);
    final String depslist = zf.getManifest().getMainAttributes().getValue("Rundeck-Tools-Dependencies");
    if (null == depslist) {
        throw new RuntimeException(
                "Rundeck Core jar file manifest attribute \"Rundeck-Tools-Dependencies\" was not found: "
                        + coreJar.getAbsolutePath());
    }
    final String[] jars = depslist.split(" ");

    //copy jars from list to toolslibdir

    final String jarpath = jettyLibPath;
    for (final String jarName : jars) {
        ZipUtil.extractZip(thisJar.getAbsolutePath(), toolslibdir, jarpath + "/" + jarName, jarpath + "/");
        if (!new File(toolslibdir, jarName).exists()) {
            ERR("Failed to extract dependent jar for tools into " + toolslibdir.getAbsolutePath() + ": "
                    + jarName);
        }
    }

    //finally, copy corejar to toolslibdir
    final File destfile = new File(toolslibdir, coreJarName);
    if (!destfile.exists()) {
        if (!destfile.createNewFile()) {
            ERR("Unable to create file: " + destfile.createNewFile());
        }
    }
    ZipUtil.copyStream(new FileInputStream(coreJar), new FileOutputStream(destfile));
}

From source file:com.slamd.admin.JobPack.java

/**
 * Extracts the contents of the job pack and registers the included jobs with
 * the SLAMD server.// w  w w  .  j  a  va2s  .c om
 *
 * @throws  SLAMDServerException  If a problem occurs while processing the job
 *                                pack JAR file.
 */
public void processJobPack() throws SLAMDServerException {
    byte[] fileData = null;
    File tempFile = null;
    String fileName = null;
    String separator = System.getProperty("file.separator");

    if (filePath == null) {
        // First, get the request and ensure it is multipart content.
        HttpServletRequest request = requestInfo.request;
        if (!FileUpload.isMultipartContent(request)) {
            throw new SLAMDServerException("Request does not contain multipart " + "content");
        }

        // Iterate through the request fields to get to the file data.
        Iterator iterator = fieldList.iterator();
        while (iterator.hasNext()) {
            FileItem fileItem = (FileItem) iterator.next();
            String fieldName = fileItem.getFieldName();

            if (fieldName.equals(Constants.SERVLET_PARAM_JOB_PACK_FILE)) {
                fileData = fileItem.get();
                fileName = fileItem.getName();
            }
        }

        // Make sure that a file was actually uploaded.
        if (fileData == null) {
            throw new SLAMDServerException("No file data was found in the " + "request.");
        }

        // Write the JAR file data to a temp file, since that's the only way we
        // can parse it.
        if (separator == null) {
            separator = "/";
        }

        tempFile = new File(jobClassDirectory + separator + fileName);
        try {
            FileOutputStream outputStream = new FileOutputStream(tempFile);
            outputStream.write(fileData);
            outputStream.flush();
            outputStream.close();
        } catch (IOException ioe) {
            try {
                tempFile.delete();
            } catch (Exception e) {
            }

            ioe.printStackTrace();
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
            throw new SLAMDServerException("I/O error writing temporary JAR " + "file:  " + ioe, ioe);
        }
    } else {
        tempFile = new File(filePath);
        if ((!tempFile.exists()) || (!tempFile.isFile())) {
            throw new SLAMDServerException("Specified job pack file \"" + filePath + "\" does not exist");
        }

        try {
            fileName = tempFile.getName();
            int fileLength = (int) tempFile.length();
            fileData = new byte[fileLength];

            FileInputStream inputStream = new FileInputStream(tempFile);
            int bytesRead = 0;
            while (bytesRead < fileLength) {
                bytesRead += inputStream.read(fileData, bytesRead, fileLength - bytesRead);
            }
            inputStream.close();
        } catch (Exception e) {
            slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
            throw new SLAMDServerException("Error reading job pack file \"" + filePath + "\" -- " + e, e);
        }
    }

    StringBuilder htmlBody = requestInfo.htmlBody;

    // Parse the jar file
    JarFile jarFile = null;
    Manifest manifest = null;
    Enumeration jarEntries = null;
    try {
        jarFile = new JarFile(tempFile, true);
        manifest = jarFile.getManifest();
        jarEntries = jarFile.entries();
    } catch (IOException ioe) {
        try {
            if (filePath == null) {
                tempFile.delete();
            }
        } catch (Exception e) {
        }

        ioe.printStackTrace();
        slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
        throw new SLAMDServerException("Unable to parse the JAR file:  " + ioe, ioe);
    }

    ArrayList<String> dirList = new ArrayList<String>();
    ArrayList<String> fileNameList = new ArrayList<String>();
    ArrayList<byte[]> fileDataList = new ArrayList<byte[]>();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = (JarEntry) jarEntries.nextElement();
        String entryName = jarEntry.getName();
        if (jarEntry.isDirectory()) {
            dirList.add(entryName);
        } else {
            try {
                int entrySize = (int) jarEntry.getSize();
                byte[] entryData = new byte[entrySize];
                InputStream inputStream = jarFile.getInputStream(jarEntry);
                extractFileData(inputStream, entryData);
                fileNameList.add(entryName);
                fileDataList.add(entryData);
            } catch (IOException ioe) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("I/O error parsing JAR entry " + entryName + " -- " + ioe, ioe);
            } catch (SLAMDServerException sse) {
                try {
                    jarFile.close();
                    if (filePath == null) {
                        tempFile.delete();
                    }
                } catch (Exception e) {
                }

                sse.printStackTrace();
                throw sse;
            }
        }
    }

    // If we have gotten here, then we have read all the data from the JAR file.
    // Delete the temporary file to prevent possible (although unlikely)
    // conflicts with data contained in the JAR.
    try {
        jarFile.close();
        if (filePath == null) {
            tempFile.delete();
        }
    } catch (Exception e) {
    }

    // Create the directory structure specified in the JAR file.
    if (!dirList.isEmpty()) {
        htmlBody.append("<B>Created the following directories</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < dirList.size(); i++) {
            File dirFile = new File(jobClassDirectory + separator + dirList.get(i));
            try {
                dirFile.mkdirs();
                htmlBody.append("  <LI>" + dirFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (Exception e) {
                htmlBody.append("</UL>" + Constants.EOL);
                e.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(e));
                throw new SLAMDServerException(
                        "Unable to create directory \"" + dirFile.getAbsolutePath() + " -- " + e, e);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Write all the files to disk.  If we have gotten this far, then there
    // should not be any failures, but if there are, then we will have to
    // leave things in a "dirty" state.
    if (!fileNameList.isEmpty()) {
        htmlBody.append("<B>Created the following files</B>" + Constants.EOL);
        htmlBody.append("<BR>" + Constants.EOL);
        htmlBody.append("<UL>" + Constants.EOL);

        for (int i = 0; i < fileNameList.size(); i++) {
            File dataFile = new File(jobClassDirectory + separator + fileNameList.get(i));

            try {
                // Make sure the parent directory exists.
                dataFile.getParentFile().mkdirs();
            } catch (Exception e) {
            }

            try {
                FileOutputStream outputStream = new FileOutputStream(dataFile);
                outputStream.write(fileDataList.get(i));
                outputStream.flush();
                outputStream.close();
                htmlBody.append("  <LI>" + dataFile.getAbsolutePath() + "</LI>" + Constants.EOL);
            } catch (IOException ioe) {
                htmlBody.append("</UL>" + Constants.EOL);
                ioe.printStackTrace();
                slamdServer.logMessage(Constants.LOG_LEVEL_EXCEPTION_DEBUG, JobClass.stackTraceToString(ioe));
                throw new SLAMDServerException("Unable to write file " + dataFile.getAbsolutePath() + ioe, ioe);
            }
        }

        htmlBody.append("</UL>" + Constants.EOL);
        htmlBody.append("<BR><BR>" + Constants.EOL);
    }

    // Finally, parse the manifest to get the names of the classes that should
    // be registered with the SLAMD server.
    Attributes manifestAttributes = manifest.getMainAttributes();
    Attributes.Name key = new Attributes.Name(Constants.JOB_PACK_MANIFEST_REGISTER_JOBS_ATTR);
    String registerClassesStr = (String) manifestAttributes.get(key);
    if ((registerClassesStr == null) || (registerClassesStr.length() == 0)) {
        htmlBody.append("<B>No job classes registered</B>" + Constants.EOL);
    } else {
        ArrayList<String> successList = new ArrayList<String>();
        ArrayList<String> failureList = new ArrayList<String>();

        StringTokenizer tokenizer = new StringTokenizer(registerClassesStr, ", \t\r\n");
        while (tokenizer.hasMoreTokens()) {
            String className = tokenizer.nextToken();

            try {
                JobClass jobClass = slamdServer.loadJobClass(className);
                slamdServer.addJobClass(jobClass);
                successList.add(className);
            } catch (Exception e) {
                failureList.add(className + ":  " + e);
            }
        }

        if (!successList.isEmpty()) {
            htmlBody.append("<B>Registered Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < successList.size(); i++) {
                htmlBody.append("  <LI>" + successList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }

        if (!failureList.isEmpty()) {
            htmlBody.append("<B>Unable to Register Job Classes</B>" + Constants.EOL);
            htmlBody.append("<UL>" + Constants.EOL);
            for (int i = 0; i < failureList.size(); i++) {
                htmlBody.append("  <LI>" + failureList.get(i) + "</LI>" + Constants.EOL);
            }
            htmlBody.append("</UL>" + Constants.EOL);
            htmlBody.append("<BR><BR>" + Constants.EOL);
        }
    }
}

From source file:org.jenkinsci.maven.plugins.hpi.RunMojo.java

private VersionNumber versionOfPlugin(File p) throws IOException {
    if (!p.isFile()) {
        return new VersionNumber("0.0");
    }/* w w w .  ja  v  a 2  s .com*/
    JarFile j = new JarFile(p);
    try {
        String v = j.getManifest().getMainAttributes().getValue("Plugin-Version");
        if (v == null) {
            throw new IOException("no Plugin-Version in " + p);
        }
        try {
            return new VersionNumber(v);
        } catch (IllegalArgumentException x) {
            throw new IOException("malformed Plugin-Version in " + p + ": " + x, x);
        }
    } finally {
        j.close();
    }
}

From source file:net.rim.ejde.internal.packaging.PackagingManager.java

/**
 * Checks if a jar file is a MidletJar created by rapc.
 *
 * @param f/*  w  ww .ja va2  s.  c  o m*/
 * @return
 */
static public int getJarFileType(File f) {
    int type = 0x0;
    if (!f.exists()) {
        return type;
    }
    java.util.jar.JarFile jar = null;
    try {
        jar = new java.util.jar.JarFile(f, false);
        java.util.jar.Manifest manifest = jar.getManifest();
        if (manifest != null) {
            java.util.jar.Attributes attributes = manifest.getMainAttributes();
            String profile = attributes.getValue("MicroEdition-Profile");
            if (profile != null) {
                if ("MIDP-1.0".equals(profile) || "MIDP-2.0".equals(profile)) {
                    type = type | MIDLET_JAR;
                }
            }
        }
        Enumeration<JarEntry> entries = jar.entries();
        JarEntry entry;
        String entryName;
        InputStream is = null;
        IClassFileReader classFileReader = null;
        // check the attribute of the class files in the jar file
        for (; entries.hasMoreElements();) {
            entry = entries.nextElement();
            entryName = entry.getName();
            if (entryName.endsWith(IConstants.CLASS_FILE_EXTENSION_WITH_DOT)) {
                is = jar.getInputStream(entry);
                classFileReader = ToolFactory.createDefaultClassFileReader(is, IClassFileReader.ALL);
                if (isEvisceratedClass(classFileReader)) {
                    type = type | EVISCERATED_JAR;
                    break;
                }
            }
        }
    } catch (IOException e) {
        _log.error(e.getMessage());
    } finally {
        try {
            if (jar != null) {
                jar.close();
            }
        } catch (IOException e) {
            _log.error(e.getMessage());
        }
    }
    return type;
}