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:com.speed.ob.api.ClassStore.java

public void dump(File in, File out, Config config) throws IOException {
    if (in.isDirectory()) {
        for (ClassNode node : nodes()) {
            String[] parts = node.name.split("\\.");
            String dirName = node.name.substring(0, node.name.lastIndexOf("."));
            dirName = dirName.replace(".", "/");
            File dir = new File(out, dirName);
            if (!dir.exists()) {
                if (!dir.mkdirs())
                    throw new IOException("Could not make output dir: " + dir.getAbsolutePath());
            }/*  w  w w.  ja  v a 2  s .  c o  m*/
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            FileOutputStream fOut = new FileOutputStream(
                    new File(dir, node.name.substring(node.name.lastIndexOf(".") + 1)));
            fOut.write(data);
            fOut.flush();
            fOut.close();
        }
    } else if (in.getName().endsWith(".jar")) {
        File output = new File(out, in.getName());
        JarFile jf = new JarFile(in);
        HashMap<JarEntry, Object> existingData = new HashMap<>();
        if (output.exists()) {
            try {
                JarInputStream jarIn = new JarInputStream(new FileInputStream(output));
                JarEntry entry;
                while ((entry = jarIn.getNextJarEntry()) != null) {
                    if (!entry.isDirectory()) {
                        byte[] data = IOUtils.toByteArray(jarIn);
                        existingData.put(entry, data);
                        jarIn.closeEntry();
                    }
                }
                jarIn.close();
            } catch (IOException e) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE,
                        "Could not read existing output file, overwriting", e);
            }
        }
        FileOutputStream fout = new FileOutputStream(output);
        Manifest manifest = null;
        if (jf.getManifest() != null) {
            manifest = jf.getManifest();
            if (!config.getBoolean("ClassNameTransform.keep_packages")
                    && config.getBoolean("ClassNameTransform.exclude_mains")) {
                manifest = new Manifest(manifest);
                if (manifest.getMainAttributes().getValue("Main-Class") != null) {
                    String manifestName = manifest.getMainAttributes().getValue("Main-Class");
                    if (manifestName.contains(".")) {
                        manifestName = manifestName.substring(manifestName.lastIndexOf(".") + 1);
                        manifest.getMainAttributes().putValue("Main-Class", manifestName);
                    }
                }
            }
        }
        jf.close();
        JarOutputStream jarOut = manifest == null ? new JarOutputStream(fout)
                : new JarOutputStream(fout, manifest);
        Logger.getLogger(getClass().getName()).fine("Restoring " + existingData.size() + " existing files");
        if (!existingData.isEmpty()) {
            for (Map.Entry<JarEntry, Object> entry : existingData.entrySet()) {
                Logger.getLogger(getClass().getName()).fine("Restoring " + entry.getKey().getName());
                jarOut.putNextEntry(entry.getKey());
                jarOut.write((byte[]) entry.getValue());
                jarOut.closeEntry();
            }
        }
        for (ClassNode node : nodes()) {
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            node.accept(writer);
            byte[] data = writer.toByteArray();
            int index = node.name.lastIndexOf("/");
            String fileName;
            if (index > 0) {
                fileName = node.name.substring(0, index + 1).replace(".", "/");
                fileName += node.name.substring(index + 1).concat(".class");
            } else {
                fileName = node.name.concat(".class");
            }
            JarEntry entry = new JarEntry(fileName);
            jarOut.putNextEntry(entry);
            jarOut.write(data);
            jarOut.closeEntry();
        }
        jarOut.close();
    } else {
        if (nodes().size() == 1) {
            File outputFile = new File(out, in.getName());
            ClassNode node = nodes().iterator().next();
            ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_MAXS);
            byte[] data = writer.toByteArray();
            FileOutputStream stream = new FileOutputStream(outputFile);
            stream.write(data);
            stream.close();
        }
    }
}

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

/**
 * <p>//  w  ww .  j  av  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;
}

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;/*from   w  w  w .  jav  a 2  s  .  co 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.sipfoundry.openfire.plugin.presence.SipXOpenfirePlugin.java

void loadExtras(ClassLoader classLoader, File extrasDir) {
    // inspect all jars in the extras dir
    File[] jars = extrasDir.listFiles(new FilenameFilter() {
        @Override//  w ww. j a va  2  s .com
        public boolean accept(File dir, String name) {
            return name.endsWith(".jar");
        }
    });
    if (jars != null) {
        for (File jar : jars) {
            // find all classes that are packet interceptors
            try {
                log.info("loadExtras considering jar: " + jar.getName());
                JarFile jarFile = new JarFile(jar);
                // Get the manifest and its attributes
                Manifest manifest = jarFile.getManifest();
                Attributes attribs = manifest.getMainAttributes();
                String messageInterceptorClassName = attribs.getValue("MessageInterceptorClass");
                if (messageInterceptorClassName != null) {
                    log.info("Found an extra MessageInterceptorClass " + messageInterceptorClassName);

                    Class packetInterceptorClass = Class.forName(messageInterceptorClassName, true,
                            classLoader);
                    AbstractMessagePacketInterceptor abstractMessagePacketInterceptor = (AbstractMessagePacketInterceptor) packetInterceptorClass
                            .newInstance();
                    abstractMessagePacketInterceptor.start(this);
                    InterceptorManager.getInstance().addInterceptor(abstractMessagePacketInterceptor);
                    abstractMessagePacketInterceptors.add(abstractMessagePacketInterceptor);
                }
            } catch (Throwable e) {
                log.error("loadExtras caught exception:", e);
            }
        }
    }
}

From source file:mobac.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * /* ww  w.j a v  a 2s.  com*/
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this MOBAC version.");
        ZipEntry entry = jf.getEntry("META-INF/services/mobac.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:osmcd.mapsources.loader.MapPackManager.java

/**
 * Verifies the class file signatures of the specified map pack
 * /* ww w.ja  va 2  s .co  m*/
 * @param mapPackFile
 * @throws IOException
 * @throws CertificateException
 */
public void testMapPack(File mapPackFile) throws IOException, CertificateException {
    String fileName = mapPackFile.getName();
    JarFile jf = new JarFile(mapPackFile, true);
    try {
        Enumeration<JarEntry> it = jf.entries();
        while (it.hasMoreElements()) {
            JarEntry entry = it.nextElement();
            // We verify only class files
            if (!entry.getName().endsWith(".class"))
                continue; // directory or other entry
            // Get the input stream (triggers) the signature verification for the specific class
            Utilities.readFully(jf.getInputStream(entry));
            if (entry.getCodeSigners() == null)
                throw new CertificateException("Unsigned class file found: " + entry.getName());
            CodeSigner signer = entry.getCodeSigners()[0];
            List<? extends Certificate> cp = signer.getSignerCertPath().getCertificates();
            if (cp.size() > 1)
                throw new CertificateException("Signature certificate not accepted: "
                        + "certificate path contains more than one certificate");
            // Compare the used certificate with the mapPack certificate
            if (!mapPackCert.equals(cp.get(0)))
                throw new CertificateException(
                        "Signature certificate not accepted: " + "not the MapPack signer certificate");
        }
        Manifest mf = jf.getManifest();
        Attributes a = mf.getMainAttributes();
        String mpv = a.getValue("MapPackVersion");
        if (mpv == null)
            throw new IOException("MapPackVersion info missing!");
        int mapPackVersion = Integer.parseInt(mpv);
        if (requiredMapPackVersion != mapPackVersion)
            throw new IOException("This pack \"" + fileName + "\" is not compatible with this OSMCB version.");
        ZipEntry entry = jf.getEntry("META-INF/services/osmcd.program.interfaces.MapSource");
        if (entry == null)
            throw new IOException("MapSources services list is missing in file " + fileName);
    } finally {
        jf.close();
    }

}

From source file:org.eclipse.jubula.client.ui.rcp.widgets.autconfig.JavaAutConfigComponent.java

/** 
 * The action of the JAR name field.//from  w ww.ja  v  a 2s  . co m
 * @return <code>null</code> if the new value is valid. Otherwise, returns
 *         a status parameter indicating the cause of the problem.
 */
DialogStatusParameter modifyJarFieldAction() {

    DialogStatusParameter error = null;
    boolean isEmpty = m_jarTextField.getText().length() == 0;
    if (isValid(m_jarTextField, true) && !isEmpty) {
        if (checkLocalhostServer()) {
            String filename = m_jarTextField.getText();
            File file = new File(filename);
            String workingDir = StringUtils.defaultString(getConfigValue(AutConfigConstants.WORKING_DIR));
            if (!file.isAbsolute() && workingDir.length() != 0) {

                filename = workingDir + "/" + filename; //$NON-NLS-1$
                file = new File(filename);
            }
            try {
                if (!file.exists()) {
                    error = createWarningStatus(
                            NLS.bind(Messages.AUTConfigComponentFileNotFound, file.getCanonicalPath()));
                } else {
                    JarFile jarFile = new JarFile(file);
                    Manifest jarManifest = jarFile.getManifest();
                    if (jarManifest == null) {
                        // no manifest for JAR
                        error = createErrorStatus(Messages.AUTConfigComponentNoManifest);
                    } else if (jarManifest.getMainAttributes().getValue(MAIN_CLASS) == null) {

                        // no main class defined in JAR manifest
                        error = createErrorStatus(Messages.AUTConfigComponentNoMainClass);
                    }
                }
            } catch (ZipException ze) {
                // given file is not a jar file
                error = createErrorStatus(NLS.bind(Messages.AUTConfigComponentFileNotJar, filename));
            } catch (IOException e) {
                // could not find jar file
                error = createWarningStatus(NLS.bind(Messages.AUTConfigComponentFileNotFound, filename));
            }
        }
    } else if (!isEmpty) {
        error = createErrorStatus(Messages.AUTConfigComponentWrongJAR);
    }

    putConfigValue(AutConfigConstants.JAR_FILE, m_jarTextField.getText());

    return error;
}

From source file:org.lockss.plugin.PluginManager.java

/**
 * Given a file representing a JAR, retrieve a list of available
 * plugin classes to load.//from ww w .j  av a  2  s .  c o  m
 */
private List<String> getJarPluginClasses(File blessedJar) throws IOException {
    JarFile jar = new JarFile(blessedJar);
    Manifest manifest = jar.getManifest();
    Map entries = manifest.getEntries();
    List<String> plugins = new ArrayList<String>();

    for (Iterator manIter = entries.keySet().iterator(); manIter.hasNext();) {
        String key = (String) manIter.next();

        Attributes attrs = manifest.getAttributes(key);

        if (attrs.containsKey(LOADABLE_PLUGIN_ATTR)) {
            String s = StringUtil.replaceString(key, "/", ".");

            String pluginName = null;

            if (StringUtil.endsWithIgnoreCase(key, ".class")) {
                pluginName = StringUtil.replaceString(s, ".class", "");
                log.debug2("Adding '" + pluginName + "' to plugin load list.");
                plugins.add(pluginName);
            } else if (StringUtil.endsWithIgnoreCase(key, ".xml")) {
                pluginName = StringUtil.replaceString(s, ".xml", "");
                log.debug2("Adding '" + pluginName + "' to plugin load list.");
                plugins.add(pluginName);
            }
        }

    }

    jar.close();

    return plugins;
}

From source file:org.apache.tomcat.maven.plugin.tomcat8.run.RunMojo.java

@Override
protected void enhanceContext(final Context context) throws MojoExecutionException {
    super.enhanceContext(context);

    try {/*from   www .  j  a  v a2 s  .  c om*/
        ClassLoaderEntriesCalculatorRequest request = new ClassLoaderEntriesCalculatorRequest() //
                .setDependencies(dependencies) //
                .setLog(getLog()) //
                .setMavenProject(project) //
                .setAddWarDependenciesInClassloader(addWarDependenciesInClassloader) //
                .setUseTestClassPath(useTestClasspath);
        final ClassLoaderEntriesCalculatorResult classLoaderEntriesCalculatorResult = classLoaderEntriesCalculator
                .calculateClassPathEntries(request);
        final List<String> classLoaderEntries = classLoaderEntriesCalculatorResult.getClassPathEntries();
        final List<File> tmpDirectories = classLoaderEntriesCalculatorResult.getTmpDirectories();

        final List<String> jarPaths = extractJars(classLoaderEntries);

        List<URL> urls = new ArrayList<URL>(jarPaths.size());

        for (String jarPath : jarPaths) {
            try {
                urls.add(new File(jarPath).toURI().toURL());
            } catch (MalformedURLException e) {
                throw new MojoExecutionException(e.getMessage(), e);
            }
        }

        getLog().debug("classLoaderEntriesCalculator urls: " + urls);

        final URLClassLoader urlClassLoader = new URLClassLoader(urls.toArray(new URL[urls.size()]));

        final ClassRealm pluginRealm = getTomcatClassLoader();

        context.setResources(
                new MyDirContext(new File(project.getBuild().getOutputDirectory()).getAbsolutePath(), //
                        getPath(), //
                        getLog()) {
                    @Override
                    public WebResource getClassLoaderResource(String path) {

                        log.debug("RunMojo#getClassLoaderResource: " + path);
                        URL url = urlClassLoader.getResource(StringUtils.removeStart(path, "/"));
                        // search in parent (plugin) classloader
                        if (url == null) {
                            url = pluginRealm.getResource(StringUtils.removeStart(path, "/"));
                        }

                        if (url == null) {
                            // try in reactors
                            List<WebResource> webResources = findResourcesInDirectories(path, //
                                    classLoaderEntriesCalculatorResult.getBuildDirectories());

                            // so we return the first one
                            if (!webResources.isEmpty()) {
                                return webResources.get(0);
                            }
                        }

                        if (url == null) {
                            return new EmptyResource(this, getPath());
                        }

                        return urlToWebResource(url, path);
                    }

                    @Override
                    public WebResource getResource(String path) {
                        log.debug("RunMojo#getResource: " + path);
                        return super.getResource(path);
                    }

                    @Override
                    public WebResource[] getResources(String path) {
                        log.debug("RunMojo#getResources: " + path);
                        return super.getResources(path);
                    }

                    @Override
                    protected WebResource[] getResourcesInternal(String path, boolean useClassLoaderResources) {
                        log.debug("RunMojo#getResourcesInternal: " + path);
                        return super.getResourcesInternal(path, useClassLoaderResources);
                    }

                    @Override
                    public WebResource[] getClassLoaderResources(String path) {
                        try {
                            Enumeration<URL> enumeration = urlClassLoader
                                    .findResources(StringUtils.removeStart(path, "/"));
                            List<URL> urlsFound = new ArrayList<URL>();
                            List<WebResource> webResources = new ArrayList<WebResource>();
                            while (enumeration.hasMoreElements()) {
                                URL url = enumeration.nextElement();
                                urlsFound.add(url);
                                webResources.add(urlToWebResource(url, path));
                            }
                            log.debug("RunMojo#getClassLoaderResources: " + path + " found : "
                                    + urlsFound.toString());

                            webResources.addAll(findResourcesInDirectories(path,
                                    classLoaderEntriesCalculatorResult.getBuildDirectories()));

                            return webResources.toArray(new WebResource[webResources.size()]);

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private List<WebResource> findResourcesInDirectories(String path,
                            List<String> directories) {
                        try {
                            List<WebResource> webResources = new ArrayList<WebResource>();

                            for (String directory : directories) {

                                File file = new File(directory, path);
                                if (file.exists()) {
                                    webResources.add(urlToWebResource(file.toURI().toURL(), path));
                                }

                            }

                            return webResources;
                        } catch (MalformedURLException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        }
                    }

                    private WebResource urlToWebResource(URL url, String path) {
                        JarFile jarFile = null;

                        try {
                            // url.getFile is
                            // file:/Users/olamy/mvn-repo/org/springframework/spring-web/4.0.0.RELEASE/spring-web-4.0.0.RELEASE.jar!/org/springframework/web/context/ContextLoaderListener.class

                            int idx = url.getFile().indexOf('!');

                            if (idx >= 0) {
                                String filePath = StringUtils.removeStart(url.getFile().substring(0, idx),
                                        "file:");

                                jarFile = new JarFile(filePath);

                                JarEntry jarEntry = jarFile.getJarEntry(StringUtils.removeStart(path, "/"));

                                return new JarResource(this, //
                                        getPath(), //
                                        filePath, //
                                        url.getPath().substring(0, idx), //
                                        jarEntry, //
                                        "", //
                                        null);
                            } else {
                                return new FileResource(this, webAppPath, new File(url.getFile()), true);
                            }

                        } catch (IOException e) {
                            throw new RuntimeException(e.getMessage(), e);
                        } finally {
                            IOUtils.closeQuietly(jarFile);
                        }
                    }

                });

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                for (File tmpDir : tmpDirectories) {
                    try {
                        FileUtils.deleteDirectory(tmpDir);
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        });

        if (classLoaderEntries != null) {
            WebResourceSet webResourceSet = new FileResourceSet() {
                @Override
                public WebResource getResource(String path) {

                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        File file = new File(StringUtils.removeStartIgnoreCase(path, "/WEB-INF/LIB"));
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new FileResource(context.getResources(), getPath(),
                                new File(project.getBuild().getOutputDirectory()), true);
                    }

                    File file = new File(project.getBuild().getOutputDirectory(), path);
                    if (file.exists()) {
                        return new FileResource(context.getResources(), getPath(), file, true);
                    }

                    //if ( StringUtils.endsWith( path, ".class" ) )
                    {
                        // so we search the class file in the jars
                        for (String jarPath : jarPaths) {
                            File jar = new File(jarPath);
                            if (!jar.exists()) {
                                continue;
                            }

                            try (JarFile jarFile = new JarFile(jar)) {
                                JarEntry jarEntry = (JarEntry) jarFile
                                        .getEntry(StringUtils.removeStart(path, "/"));
                                if (jarEntry != null) {
                                    return new JarResource(context.getResources(), //
                                            getPath(), //
                                            jarFile.getName(), //
                                            jar.toURI().toString(), //
                                            jarEntry, //
                                            path, //
                                            jarFile.getManifest());
                                }
                            } catch (IOException e) {
                                getLog().debug("skip error building jar file: " + e.getMessage(), e);
                            }

                        }
                    }

                    return new EmptyResource(null, path);
                }

                @Override
                public String[] list(String path) {
                    if (StringUtils.startsWithIgnoreCase(path, "/WEB-INF/LIB")) {
                        return jarPaths.toArray(new String[jarPaths.size()]);
                    }
                    if (StringUtils.equalsIgnoreCase(path, "/WEB-INF/classes")) {
                        return new String[] { new File(project.getBuild().getOutputDirectory()).getPath() };
                    }
                    return super.list(path);
                }

                @Override
                public Set<String> listWebAppPaths(String path) {

                    if (StringUtils.equalsIgnoreCase("/WEB-INF/lib/", path)) {
                        // adding outputDirectory as well?
                        return new HashSet<String>(jarPaths);
                    }

                    File filePath = new File(getWarSourceDirectory(), path);

                    if (filePath.isDirectory()) {
                        Set<String> paths = new HashSet<String>();

                        String[] files = filePath.list();
                        if (files == null) {
                            return paths;
                        }

                        for (String file : files) {
                            paths.add(file);
                        }

                        return paths;

                    } else {
                        return Collections.emptySet();
                    }
                }

                @Override
                public boolean mkdir(String path) {
                    return super.mkdir(path);
                }

                @Override
                public boolean write(String path, InputStream is, boolean overwrite) {
                    return super.write(path, is, overwrite);
                }

                @Override
                protected void checkType(File file) {
                    //super.checkType( file );
                }

            };

            context.getResources().addJarResources(webResourceSet);
        }

    } catch (TomcatRunException e) {
        throw new MojoExecutionException(e.getMessage(), e);
    }

}