Example usage for java.util.jar JarFile close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Closes the ZIP file.

Usage

From source file:org.netbeans.nbbuild.MakeJnlp2.java

private void generateFiles() throws IOException, BuildException {

    final Set<String> declaredLocales = new HashSet<String>();

    final boolean useAllLocales;

    if ("*".equals(includelocales)) {
        useAllLocales = true;/*w  w  w .j a  v a  2s . c o  m*/
    } else if ("".equals(includelocales)) {
        useAllLocales = false;
    } else {
        useAllLocales = false;
        StringTokenizer tokenizer = new StringTokenizer(includelocales, ",");
        while (tokenizer.hasMoreElements()) {
            declaredLocales.add(tokenizer.nextToken());
        }
    }

    final Set<String> indirectFilePaths = new HashSet<String>();
    for (FileSet fs : new FileSet[] { indirectJars, indirectFiles }) {
        if (fs != null) {
            DirectoryScanner scan = fs.getDirectoryScanner(getProject());
            for (String f : scan.getIncludedFiles()) {
                indirectFilePaths.add(f.replace(File.pathSeparatorChar, '/'));
            }
        }
    }

    final ExecutorService executorService = Executors.newFixedThreadPool(nbThreads);

    final List<BuildException> exceptions = new ArrayList<BuildException>();

    for (final Iterator fileIt = files.iterator(); fileIt.hasNext();) {
        if (!exceptions.isEmpty()) {
            break;
        }

        final FileResource fr = (FileResource) fileIt.next();
        final File jar = fr.getFile();

        if (!jar.canRead()) {
            throw new BuildException("Cannot read file: " + jar);
        }

        //
        if (optimize && checkDuplicate(jar).isPresent()) {
            continue;
        }
        //

        executorService.execute(new Runnable() {
            @Override
            public void run() {
                JarFile theJar = null;
                try {
                    theJar = new JarFile(jar);

                    String codenamebase = JarWithModuleAttributes
                            .extractCodeName(theJar.getManifest().getMainAttributes());
                    if (codenamebase == null) {
                        throw new BuildException("Not a NetBeans Module: " + jar);
                    }
                    {
                        int slash = codenamebase.indexOf('/');
                        if (slash >= 0) {
                            codenamebase = codenamebase.substring(0, slash);
                        }
                    }
                    String dashcnb = codenamebase.replace('.', '-');

                    String title;
                    String oneline;
                    String shrt;
                    String osDep = null;

                    {
                        String bundle = theJar.getManifest().getMainAttributes()
                                .getValue("OpenIDE-Module-Localizing-Bundle");
                        Properties prop = new Properties();
                        if (bundle != null) {
                            ZipEntry en = theJar.getEntry(bundle);
                            if (en == null) {
                                throw new BuildException("Cannot find entry: " + bundle + " in file: " + jar);
                            }
                            InputStream is = theJar.getInputStream(en);
                            prop.load(is);
                            is.close();
                        }
                        title = prop.getProperty("OpenIDE-Module-Name", codenamebase);
                        oneline = prop.getProperty("OpenIDE-Module-Short-Description", title);
                        shrt = prop.getProperty("OpenIDE-Module-Long-Description", oneline);
                    }

                    {
                        String osMan = theJar.getManifest().getMainAttributes()
                                .getValue("OpenIDE-Module-Requires");
                        if (osMan != null) {
                            if (osMan.indexOf("org.openide.modules.os.MacOSX") >= 0) { // NOI18N
                                osDep = "Mac OS X"; // NOI18N
                            } else if (osMan.indexOf("org.openide.modules.os.Linux") >= 0) { // NOI18N
                                osDep = "Linux"; // NOI18N
                            } else if (osMan.indexOf("org.openide.modules.os.Solaris") >= 0) { // NOI18N
                                osDep = "Solaris"; // NOI18N
                            } else if (osMan.indexOf("org.openide.modules.os.Windows") >= 0) { // NOI18N
                                osDep = "Windows"; // NOI18N
                            }
                        }
                    }

                    Map<String, List<File>> localizedFiles = verifyExtensions(jar, theJar.getManifest(),
                            dashcnb, codenamebase, verify, indirectFilePaths);

                    executedLocales = localizedFiles.keySet();

                    new File(targetFile, dashcnb).mkdir();

                    File signed = new File(new File(targetFile, dashcnb), jar.getName());

                    // +p
                    final JarConfigResolved jarConfig = signOrCopy(jar, signed);

                    File jnlp = new File(targetFile, dashcnb + ".jnlp");
                    StringWriter writeJNLP = new StringWriter();
                    writeJNLP.write("<?xml version='1.0' encoding='UTF-8'?>\n");
                    writeJNLP.write(
                            "<!DOCTYPE jnlp PUBLIC \"-//Sun Microsystems, Inc//DTD JNLP Descriptor 6.0//EN\" \"http://java.sun.com/dtd/JNLP-6.0.dtd\">\n");
                    writeJNLP.write("<jnlp spec='1.0+' codebase='" + codebase + "'>\n");
                    writeJNLP.write("  <information>\n");
                    writeJNLP.write("   <title>" + XMLUtil.toElementContent(title) + "</title>\n");
                    writeJNLP.write("   <vendor>NetBeans</vendor>\n");
                    writeJNLP.write("   <description kind='one-line'>" + XMLUtil.toElementContent(oneline)
                            + "</description>\n");
                    writeJNLP.write("   <description kind='short'>" + XMLUtil.toElementContent(shrt)
                            + "</description>\n");
                    writeJNLP.write("  </information>\n");

                    String realPermissions = permissions;
                    if ((jarConfig != null) && (jarConfig.getExtraManifestAttributes() != null)) {
                        String jarPermissions = jarConfig.getExtraManifestAttributes().getValue("Permissions");

                        if (jarPermissions != null) {
                            if ("all-permissions".equals(jarPermissions)) {
                                realPermissions = "<security><all-permissions/></security>\n";
                            } else {
                                realPermissions = "";
                            }
                        }
                    }

                    writeJNLP.write(realPermissions);

                    if (osDep == null) {
                        writeJNLP.write("  <resources>\n");
                    } else {
                        writeJNLP.write("  <resources os='" + osDep + "'>\n");
                    }
                    writeJNLP.write("<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf(pack200)
                            + "\"/>\n");
                    writeJNLP.write(constructJarHref(jar, dashcnb));

                    processExtensions(jar, theJar.getManifest(), writeJNLP, dashcnb, codebase, realPermissions);
                    processIndirectJars(writeJNLP, dashcnb);
                    processIndirectFiles(writeJNLP, dashcnb);

                    writeJNLP.write("  </resources>\n");

                    if (useAllLocales || !declaredLocales.isEmpty()) {

                        // write down locales
                        for (Map.Entry<String, List<File>> e : localizedFiles.entrySet()) {
                            final String locale = e.getKey();

                            if (!declaredLocales.isEmpty() && !declaredLocales.contains(locale)) {
                                continue;
                            }

                            final List<File> allFiles = e.getValue();

                            writeJNLP.write("  <resources locale='" + locale + "'>\n");

                            for (File n : allFiles) {
                                log("generating locale " + locale + " for " + n, Project.MSG_VERBOSE);
                                String name = n.getName();
                                String clusterRootPrefix = jar.getParent() + File.separatorChar;
                                String absname = n.getAbsolutePath();
                                if (absname.startsWith(clusterRootPrefix)) {
                                    name = absname.substring(clusterRootPrefix.length())
                                            .replace(File.separatorChar, '-');
                                }
                                File t = new File(new File(targetFile, dashcnb), name);
                                signOrCopy(n, t);
                                writeJNLP.write(constructJarHref(n, dashcnb, name));
                            }

                            writeJNLP.write("  </resources>\n");

                        }
                    }

                    writeJNLP.write("  <component-desc/>\n");
                    writeJNLP.write("</jnlp>\n");
                    writeJNLP.close();

                    // +p
                    Files.write(writeJNLP.toString(), jnlp, Charset.forName("UTF-8"));
                } catch (Exception e) {
                    exceptions.add(new BuildException(e));
                } finally {
                    if (theJar != null) {
                        try {
                            theJar.close();
                        } catch (IOException e) {
                        }
                    }
                }
            }
        });
    }

    executorService.shutdown();

    try {
        executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
    } catch (Exception e) {
        throw new BuildException(e);
    }

    if (!exceptions.isEmpty()) {
        throw exceptions.get(0);
    }
}

From source file:org.owasp.dependencycheck.analyzer.JarAnalyzer.java

/**
 * <p>//from www  .  ja v  a 2  s .  c  om
 * Reads the manifest from the JAR file and collects the entries. Some
 * vendorKey entries are:</p>
 * <ul><li>Implementation Title</li>
 * <li>Implementation Version</li> <li>Implementation Vendor</li>
 * <li>Implementation VendorId</li> <li>Bundle Name</li> <li>Bundle
 * Version</li> <li>Bundle Vendor</li> <li>Bundle Description</li> <li>Main
 * Class</li> </ul>
 * However, all but a handful of specific entries are read in.
 *
 * @param dependency A reference to the dependency
 * @param classInformation a collection of class information
 * @return whether evidence was identified parsing the manifest
 * @throws IOException if there is an issue reading the JAR file
 */
protected boolean parseManifest(Dependency dependency, List<ClassNameInformation> classInformation)
        throws IOException {
    boolean foundSomething = false;
    JarFile jar = null;
    try {
        jar = new JarFile(dependency.getActualFilePath());
        final Manifest manifest = jar.getManifest();
        if (manifest == null) {
            if (!dependency.getFileName().toLowerCase().endsWith("-sources.jar")
                    && !dependency.getFileName().toLowerCase().endsWith("-javadoc.jar")
                    && !dependency.getFileName().toLowerCase().endsWith("-src.jar")
                    && !dependency.getFileName().toLowerCase().endsWith("-doc.jar")) {
                LOGGER.debug("Jar file '{}' does not contain a manifest.", dependency.getFileName());
            }
            return false;
        }
        final EvidenceCollection vendorEvidence = dependency.getVendorEvidence();
        final EvidenceCollection productEvidence = dependency.getProductEvidence();
        final EvidenceCollection versionEvidence = dependency.getVersionEvidence();

        String source = "Manifest";
        String specificationVersion = null;
        boolean hasImplementationVersion = false;
        Attributes atts = manifest.getMainAttributes();
        for (Entry<Object, Object> entry : atts.entrySet()) {
            String key = entry.getKey().toString();
            String value = atts.getValue(key);
            if (HTML_DETECTION_PATTERN.matcher(value).find()) {
                value = Jsoup.parse(value).text();
            }
            if (IGNORE_VALUES.contains(value)) {
                continue;
            } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) {
                foundSomething = true;
                productEvidence.addEvidence(source, key, value, Confidence.HIGH);
                addMatchingValues(classInformation, value, productEvidence);
            } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) {
                hasImplementationVersion = true;
                foundSomething = true;
                versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
            } else if ("specification-version".equalsIgnoreCase(key)) {
                specificationVersion = key;
            } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) {
                foundSomething = true;
                vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
                addMatchingValues(classInformation, value, vendorEvidence);
            } else if (key.equalsIgnoreCase(IMPLEMENTATION_VENDOR_ID)) {
                foundSomething = true;
                vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                addMatchingValues(classInformation, value, vendorEvidence);
            } else if (key.equalsIgnoreCase(BUNDLE_DESCRIPTION)) {
                foundSomething = true;
                addDescription(dependency, value, "manifest", key);
                addMatchingValues(classInformation, value, productEvidence);
            } else if (key.equalsIgnoreCase(BUNDLE_NAME)) {
                foundSomething = true;
                productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                addMatchingValues(classInformation, value, productEvidence);
                //                //the following caused false positives.
                //                } else if (key.equalsIgnoreCase(BUNDLE_VENDOR)) {
                //                    foundSomething = true;
                //                    vendorEvidence.addEvidence(source, key, value, Confidence.HIGH);
                //                    addMatchingValues(classInformation, value, vendorEvidence);
            } else if (key.equalsIgnoreCase(BUNDLE_VERSION)) {
                foundSomething = true;
                versionEvidence.addEvidence(source, key, value, Confidence.HIGH);
            } else if (key.equalsIgnoreCase(Attributes.Name.MAIN_CLASS.toString())) {
                continue;
                //skipping main class as if this has important information to add
                // it will be added during class name analysis...  if other fields
                // have the information from the class name then they will get added...
            } else {
                key = key.toLowerCase();
                if (!IGNORE_KEYS.contains(key) && !key.endsWith("jdk") && !key.contains("lastmodified")
                        && !key.endsWith("package") && !key.endsWith("classpath") && !key.endsWith("class-path")
                        && !key.endsWith("-scm") //todo change this to a regex?
                        && !key.startsWith("scm-") && !value.trim().startsWith("scm:")
                        && !isImportPackage(key, value) && !isPackage(key, value)) {
                    foundSomething = true;
                    if (key.contains("version")) {
                        if (!key.contains("specification")) {
                            versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                        }
                    } else if ("build-id".equals(key)) {
                        int pos = value.indexOf('(');
                        if (pos >= 0) {
                            value = value.substring(0, pos - 1);
                        }
                        pos = value.indexOf('[');
                        if (pos >= 0) {
                            value = value.substring(0, pos - 1);
                        }
                        versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                    } else if (key.contains("title")) {
                        productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                        addMatchingValues(classInformation, value, productEvidence);
                    } else if (key.contains("vendor")) {
                        if (key.contains("specification")) {
                            vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
                        } else {
                            vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                            addMatchingValues(classInformation, value, vendorEvidence);
                        }
                    } else if (key.contains("name")) {
                        productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                        vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                        addMatchingValues(classInformation, value, vendorEvidence);
                        addMatchingValues(classInformation, value, productEvidence);
                    } else if (key.contains("license")) {
                        addLicense(dependency, value);
                    } else if (key.contains("description")) {
                        addDescription(dependency, value, "manifest", key);
                    } else {
                        productEvidence.addEvidence(source, key, value, Confidence.LOW);
                        vendorEvidence.addEvidence(source, key, value, Confidence.LOW);
                        addMatchingValues(classInformation, value, vendorEvidence);
                        addMatchingValues(classInformation, value, productEvidence);
                        if (value.matches(".*\\d.*")) {
                            final StringTokenizer tokenizer = new StringTokenizer(value, " ");
                            while (tokenizer.hasMoreElements()) {
                                final String s = tokenizer.nextToken();
                                if (s.matches("^[0-9.]+$")) {
                                    versionEvidence.addEvidence(source, key, s, Confidence.LOW);
                                }
                            }
                        }
                    }
                }
            }
        }

        for (Map.Entry<String, Attributes> item : manifest.getEntries().entrySet()) {
            final String name = item.getKey();
            source = "manifest: " + name;
            atts = item.getValue();
            for (Entry<Object, Object> entry : atts.entrySet()) {
                final String key = entry.getKey().toString();
                final String value = atts.getValue(key);
                if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_TITLE.toString())) {
                    foundSomething = true;
                    productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                    addMatchingValues(classInformation, value, productEvidence);
                } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VERSION.toString())) {
                    foundSomething = true;
                    versionEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                } else if (key.equalsIgnoreCase(Attributes.Name.IMPLEMENTATION_VENDOR.toString())) {
                    foundSomething = true;
                    vendorEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                    addMatchingValues(classInformation, value, vendorEvidence);
                } else if (key.equalsIgnoreCase(Attributes.Name.SPECIFICATION_TITLE.toString())) {
                    foundSomething = true;
                    productEvidence.addEvidence(source, key, value, Confidence.MEDIUM);
                    addMatchingValues(classInformation, value, productEvidence);
                }
            }
        }
        if (specificationVersion != null && !hasImplementationVersion) {
            foundSomething = true;
            versionEvidence.addEvidence(source, "specification-version", specificationVersion, Confidence.HIGH);
        }
    } finally {
        if (jar != null) {
            jar.close();
        }
    }
    return foundSomething;
}