Example usage for java.util.jar Attributes getValue

List of usage examples for java.util.jar Attributes getValue

Introduction

In this page you can find the example usage for java.util.jar Attributes getValue.

Prototype

public String getValue(Name name) 

Source Link

Document

Returns the value of the specified Attributes.Name, or null if the attribute was not found.

Usage

From source file:org.jboss.tools.tycho.sitegenerator.FetchSourcesFromManifests.java

public void execute() throws MojoExecutionException, MojoFailureException {
    if (!skip) {/*from  w ww .  j  av a2s  . co m*/
        if (this.zipCacheFolder == null) {
            this.zipCacheFolder = new File(project.getBasedir() + File.separator + "cache" + File.separator);
        }
        if (this.zipCacheFolder != null && !this.zipCacheFolder.isDirectory()) {
            try {
                if (!this.zipCacheFolder.exists()) {
                    this.zipCacheFolder.mkdirs();
                }
            } catch (Exception ex) {
                throw new MojoExecutionException("'zipCacheFolder' must be a directory", ex);
            }
        }
        if (this.outputFolder == null) {
            this.outputFolder = new File(project.getBasedir() + File.separator + "zips" + File.separator);
        }
        if (this.outputFolder.equals(this.zipCacheFolder)) {
            throw new MojoExecutionException("zipCacheFolder and outputFolder can not be the same folder");
        }

        zipsDirectory = new File(this.outputFolder, "all");
        if (!zipsDirectory.exists()) {
            zipsDirectory.mkdirs();
        }

        File digestFile = new File(this.outputFolder, "ALL_REVISIONS.txt");
        FileWriter dfw;
        StringBuffer sb = new StringBuffer();
        String branch = project.getProperties().getProperty("mvngit.branch");
        sb.append("-=> " + project.getGroupId() + ":" + project.getArtifactId() + ":" + project.getVersion()
                + columnSeparator + branch + " <=-\n");

        String pluginPath = project.getBasedir() + File.separator + "target" + File.separator + "repository"
                + File.separator + "plugins";
        String sep = " " + columnSeparator + " ";

        if (sourceFetchMap == null) {
            getLog().warn(
                    "No <sourceFetchMap> defined in pom. Can't fetch sources without a list of plugins. Did you forget to enable fetch-source-zips profile?");
        } else {
            for (String projectName : this.sourceFetchMap.keySet()) {
                String pluginNameOrBuildInfoJsonUrl = this.sourceFetchMap.get(projectName);
                // jbosstools-base = org.jboss.tools.common
                getLog().debug("For project " + projectName + ": plugin name or buildinfo.json = "
                        + pluginNameOrBuildInfoJsonUrl);

                String SHA = null;
                String qualifier = null;
                String SHASource = null;

                // if the value is a buildinfo.json URL, not a plugin name
                if ((pluginNameOrBuildInfoJsonUrl.startsWith("http")
                        || pluginNameOrBuildInfoJsonUrl.startsWith("ftp"))
                        && pluginNameOrBuildInfoJsonUrl.matches(".+buildinfo.*json")) {
                    getLog().debug("Read JSON from: " + pluginNameOrBuildInfoJsonUrl);
                    ModelNode obj;
                    try {
                        obj = ModelNode.fromJSONStream((new URL(pluginNameOrBuildInfoJsonUrl)).openStream());
                    } catch (IOException e) {
                        throw new MojoExecutionException(
                                "Problem occurred reading " + pluginNameOrBuildInfoJsonUrl, e);
                    }
                    SHA = getSHA(obj);
                    getLog().debug("Found SHA = " + SHA);
                    // create qualifier from buildinfo.json BUILD_ALIAS and ZIPSUFFIX
                    qualifier = getProperty(obj, "BUILD_ALIAS") + "-" + getProperty(obj, "ZIPSUFFIX");
                    getLog().debug("Found qualifier = " + qualifier);
                    SHASource = pluginNameOrBuildInfoJsonUrl;
                } else {
                    // find the first matching plugin jar, eg., target/repository/plugins/org.jboss.tools.common_3.6.0.Alpha2-v20140304-0055-B440.jar
                    File[] matchingFiles = listFilesMatching(new File(pluginPath),
                            pluginNameOrBuildInfoJsonUrl + "_.+\\.jar");
                    // for (File file : matchingFiles) getLog().debug(file.toString());
                    if (matchingFiles.length < 1) {
                        throw new MojoExecutionException("No matching plugin found in " + pluginPath + " for "
                                + pluginNameOrBuildInfoJsonUrl
                                + "_.+\\.jar.\nCheck your pom.xml for this line: <" + projectName + ">"
                                + pluginNameOrBuildInfoJsonUrl + "</" + projectName + ">");
                    }
                    File jarFile = matchingFiles[0];
                    File manifestFile = null;

                    try {
                        FileInputStream fin = new FileInputStream(jarFile);
                        manifestFile = File.createTempFile(MANIFEST, "");
                        OutputStream out = new FileOutputStream(manifestFile);
                        BufferedInputStream bin = new BufferedInputStream(fin);
                        ZipInputStream zin = new ZipInputStream(bin);
                        ZipEntry ze = null;
                        while ((ze = zin.getNextEntry()) != null) {
                            // getLog().debug(ze.getName());
                            if (ze.getName().equals("META-INF/" + MANIFEST)) {
                                // getLog().debug("Found " + ze.getName() + " in " +
                                // jarFile);
                                byte[] buffer = new byte[8192];
                                int len;
                                while ((len = zin.read(buffer)) != -1) {
                                    out.write(buffer, 0, len);
                                }
                                out.close();
                                break;
                            }
                        }
                        zin.close();
                        // getLog().debug("Saved " + jarFile + "!/META-INF/" + MANIFEST);
                    } catch (Exception ex) {
                        throw new MojoExecutionException("Error extracting " + MANIFEST + " from " + jarFile,
                                ex);
                    }

                    // retrieve the MANIFEST.MF file, eg., org.jboss.tools.usage_1.2.100.Alpha2-v20140221-1555-B437.jar!/META-INF/MANIFEST.MF
                    Manifest manifest;
                    try {
                        manifest = new Manifest(new FileInputStream(manifestFile));
                    } catch (Exception ex) {
                        throw new MojoExecutionException("Error while reading manifest file " + MANIFEST, ex);
                    }

                    // parse out the commitId from Eclipse-SourceReferences:
                    // scm:git:https://github.com/jbosstools/jbosstools-base.git;path="usage/plugins/org.jboss.tools.usage";commitId=184e18cc3ac7c339ce406974b6a4917f73909cc4
                    Attributes attr = manifest.getMainAttributes();
                    String ESR = null;
                    SHA = null;
                    ESR = attr.getValue("Eclipse-SourceReferences");
                    // getLog().debug(ESR);
                    if (ESR != null) {
                        SHA = ESR.substring(ESR.lastIndexOf(";commitId=") + 10);
                        // getLog().debug(SHA);
                    } else {
                        SHA = "UNKNOWN";
                    }
                    // cleanup
                    manifestFile.delete();

                    qualifier = getQualifier(pluginNameOrBuildInfoJsonUrl, jarFile.toString(), true);
                    SHASource = removePrefix(jarFile.toString(), pluginPath) + " " + MANIFEST;
                }
                // fetch github source archive for that SHA, eg., https://github.com/jbosstools/jbosstools-base/archive/184e18cc3ac7c339ce406974b6a4917f73909cc4.zip
                // to jbosstools-base_184e18cc3ac7c339ce406974b6a4917f73909cc4_sources.zip
                String URL = "";
                String outputZipName = "";
                try {
                    if (SHA == null || SHA.equals("UNKNOWN")) {
                        getLog().warn("Cannot fetch " + projectName
                                + " sources: no Eclipse-SourceReferences in " + SHASource);
                    } else {
                        URL = "https://github.com/jbosstools/" + projectName + "/archive/" + SHA + ".zip";
                        outputZipName = projectName + "_" + SHA + "_sources.zip";
                        fetchUpstreamSourcesZip(projectName, SHA);
                    }
                } catch (Exception ex) {
                    throw new MojoExecutionException("Error while downloading github source archive", ex);
                }

                // github project, plugin, version, SHA, origin/branch@SHA, remote zipfile, local zipfile
                String revisionLine = projectName + sep + pluginNameOrBuildInfoJsonUrl + sep + qualifier + sep
                        + SHA + sep + "origin/" + branch + "@" + SHA + sep + URL + sep + outputZipName + "\n";
                // getLog().debug(revisionLine);
                sb.append(revisionLine);
            }
        }

        /*
        JBIDE-19467 check if SHA in buildinfo_projectName.json matches projectName_65cb06bb81773714b9e3fc1c312e33aaa068dc33_sources.zip.
        Note: this may fail if you've built stuff locally because those plugins will use different SHAs (eg., from a pull-request topic branch)
                
        To test this is working via commandline shell equivalent
                
        cd jbosstools-build-sites/aggregate/site
        for j in target/buildinfo/buildinfo_jbosstools-*; do
           echo -n $j; k=${j##*_}; k=${k/.json}; echo " :: $k";
           cat $j | grep HEAD | head -1 | sed "s#[\t\w\ ]\+\"HEAD\" : \"\(.\+\)\",#0: \1#";
           ls cache/${k}_*_sources.zip  | sed -e "s#cache/${k}_\(.\+\)_sources.zip#1: \1#";
           echo "";
        done
        */
        if (skipCheckSHAs) {
            getLog().warn(
                    "skipCheckSHAs=true :: Skip check that buildinfo_*.json HEAD SHA matches MANIFEST.MF Eclipse-SourceReferences commitId SHA.");
        } else {
            File buildinfoFolder = new File(this.project.getBuild().getDirectory(), "buildinfo");
            if (buildinfoFolder.isDirectory()) {
                try {
                    File[] buildInfoFiles = listFilesMatching(buildinfoFolder, "buildinfo_.+.json");
                    for (int i = 0; i < buildInfoFiles.length; i++) {
                        InputStream in = null;
                        ModelNode obj = null;
                        String upstreamSHA = null;
                        String upstreamProjectName = buildInfoFiles[i].toString()
                                .replaceAll(".+buildinfo_(.+).json", "$1");
                        getLog().debug(i + ": " + buildInfoFiles[i].toString() + " :: " + upstreamProjectName);
                        try {
                            getLog().debug("Read JSON from: " + buildInfoFiles[i].toString());
                            in = new FileInputStream(buildInfoFiles[i]);
                            obj = ModelNode.fromJSONStream(in);
                            upstreamSHA = getSHA(obj);
                            getLog().debug("Found SHA = " + upstreamSHA);
                            // check if there's a file called upstreamProjectName_upstreamSHA_sources.zip
                            String outputZipName = upstreamProjectName + "_" + upstreamSHA + "_sources.zip";
                            File outputZipFile = new File(zipsDirectory, outputZipName);
                            if (!outputZipFile.isFile()) {
                                getLog().debug("Check " + outputFolder.toString() + " for "
                                        + upstreamProjectName + "_.+_sources.zip");
                                // find the sources we DID download, eg., jbosstools-browsersim_9255a5b7c04fb10768c14942e60092e860881d6b_sources.zip
                                File[] wrongZipFiles = listFilesMatching(zipsDirectory,
                                        upstreamProjectName + "_.+_sources.zip");
                                String wrongZips = "";
                                for (int j = 0; j < wrongZipFiles.length; j++) {
                                    getLog().debug(wrongZipFiles[j].toString());
                                    wrongZips += (wrongZips.isEmpty() ? "" : ", ") + wrongZipFiles[j].toString()
                                            .replaceAll(".+" + upstreamProjectName + "_(.+)_sources.zip", "$1");
                                }
                                if (!wrongZips.isEmpty()) {
                                    throw new MojoFailureException("\n\n" + buildInfoFiles[i].toString()
                                            + "\ncontains " + upstreamSHA + ", but upstream "
                                            + upstreamProjectName
                                            + " project's MANIFEST.MF has Eclipse-SourceReferences \n"
                                            + "commitId " + wrongZips + ". \n\n"
                                            + "If you have locally built projects which are being aggregated here, ensure \n"
                                            + "they are built from the latest SHA from HEAD, not a local topic branch. \n\n"
                                            + "It's also possible that some recent changes have not yet been built upstream. \n"
                                            + "If that's the case, trigger a build for the "
                                            + upstreamProjectName + " project \n"
                                            + "to ensure that the latest commits have been built and can be aggregated here. \n\n"
                                            + "Or, use -DskipCheckSHAs=true to bypass this check.\n\n"); // JBIDE-22808
                                } else {
                                    getLog().warn("\n" + buildInfoFiles[i].toString() + "\ncontains "
                                            + upstreamSHA + ", but upstream " + upstreamProjectName
                                            + " project's MANIFEST.MF has no Eclipse-SourceReferences commitId.\n"
                                            + "Using sources from " + upstreamSHA + ".");
                                    // fetch sources from upstreamProjectName's upstreamSHA (but do not log in the digestFile)
                                    fetchUpstreamSourcesZip(upstreamProjectName, upstreamSHA);
                                }
                            }
                        } finally {
                            IOUtils.closeQuietly(in);
                        }
                    }
                } catch (Exception ex) {
                    throw new MojoExecutionException("Problem occurred checking upstream buildinfo.json files!",
                            ex);
                }
            }
        }

        /*
        JBIDE-19467 check if SHA in buildinfo_projectName.json matches projectName_65cb06bb81773714b9e3fc1c312e33aaa068dc33_sources.zip.
        Note: this may fail if you've built stuff locally because those plugins will use different SHAs (eg., from a pull-request topic branch)
                
        To test this is working via commandline shell equivalent
                
        cd jbosstools-build-sites/aggregate/site
        for j in target/buildinfo/buildinfo_jbosstools-*; do
           echo -n $j; k=${j##*_}; k=${k/.json}; echo " :: $k";
           cat $j | grep HEAD | head -1 | sed "s#[\t\w\ ]\+\"HEAD\" : \"\(.\+\)\",#0: \1#";
           ls cache/${k}_*_sources.zip  | sed -e "s#cache/${k}_\(.\+\)_sources.zip#1: \1#";
           echo "";
        done
        */
        if (skipCheckSHAs) {
            getLog().warn(
                    "skipCheckSHAs=true :: Skip check that buildinfo_*.json HEAD SHA matches MANIFEST.MF Eclipse-SourceReferences commitId SHA.");
        } else {
            File buildinfoFolder = new File(this.project.getBuild().getDirectory(), "buildinfo");
            if (buildinfoFolder.isDirectory()) {
                try {
                    File[] buildInfoFiles = listFilesMatching(buildinfoFolder, "buildinfo_.+.json");
                    for (int i = 0; i < buildInfoFiles.length; i++) {
                        InputStream in = null;
                        ModelNode obj = null;
                        String upstreamSHA = null;
                        String upstreamProjectName = buildInfoFiles[i].toString()
                                .replaceAll(".+buildinfo_(.+).json", "$1");
                        getLog().debug(i + ": " + buildInfoFiles[i].toString() + " :: " + upstreamProjectName);
                        try {
                            getLog().debug("Read JSON from: " + buildInfoFiles[i].toString());
                            in = new FileInputStream(buildInfoFiles[i]);
                            obj = ModelNode.fromJSONStream(in);
                            upstreamSHA = getSHA(obj);
                            getLog().debug("Found SHA = " + upstreamSHA);
                            // check if there's a file called upstreamProjectName_upstreamSHA_sources.zip
                            String outputZipName = upstreamProjectName + "_" + upstreamSHA + "_sources.zip";
                            File outputZipFile = new File(zipsDirectory, outputZipName);
                            if (!outputZipFile.isFile()) {
                                getLog().debug("Check " + outputFolder.toString() + " for "
                                        + upstreamProjectName + "_.+_sources.zip");
                                // find the sources we DID download, eg., jbosstools-browsersim_9255a5b7c04fb10768c14942e60092e860881d6b_sources.zip
                                File[] wrongZipFiles = listFilesMatching(zipsDirectory,
                                        upstreamProjectName + "_.+_sources.zip");
                                String wrongZips = "";
                                for (int j = 0; j < wrongZipFiles.length; j++) {
                                    getLog().debug(wrongZipFiles[j].toString());
                                    wrongZips += (wrongZips.isEmpty() ? "" : ", ") + wrongZipFiles[j].toString()
                                            .replaceAll(".+" + upstreamProjectName + "_(.+)_sources.zip", "$1");
                                }
                                if (!wrongZips.isEmpty()) {
                                    throw new MojoFailureException("\n" + buildInfoFiles[i].toString()
                                            + "\ncontains " + upstreamSHA + ", but upstream "
                                            + upstreamProjectName
                                            + " project's MANIFEST.MF has Eclipse-SourceReferences\ncommitId "
                                            + wrongZips
                                            + ". \nIf you have locally built projects which are aggregated here, \nensure they are built from the latest SHA from HEAD, not a local topic branch.\n"
                                            + "Or, use -DskipCheckSHAs=true to bypass this check.");
                                } else {
                                    getLog().warn("\n" + buildInfoFiles[i].toString() + "\ncontains "
                                            + upstreamSHA + ", but upstream " + upstreamProjectName
                                            + " project's MANIFEST.MF has no Eclipse-SourceReferences commitId.\n"
                                            + "Using sources from " + upstreamSHA + ".");
                                    // fetch sources from upstreamProjectName's upstreamSHA (but do not log in the digestFile)
                                    fetchUpstreamSourcesZip(upstreamProjectName, upstreamSHA);
                                }
                            }
                        } finally {
                            IOUtils.closeQuietly(in);
                        }
                    }
                } catch (Exception ex) {
                    throw new MojoExecutionException("Problem occurred checking upstream buildinfo.json files!",
                            ex);
                }
            }
        }

        // JBDS-3364 JBDS-3208 JBIDE-19467 when not using publish.sh, unpack downloaded source zips and combine them into a single zip
        createCombinedZipFile(zipsDirectory, zipFiles, CACHE_ZIPS);

        // getLog().debug("Generating aggregate site metadata");
        try {
            {
                File buildPropertiesAllXml = new File(this.outputFolder, "build.properties.all.xml");
                if (!buildPropertiesAllXml.exists()) {
                    buildPropertiesAllXml.createNewFile();
                }
                FileOutputStream xmlOut = new FileOutputStream(buildPropertiesAllXml);
                allBuildProperties.storeToXML(xmlOut, null);
                xmlOut.close();
            }

            {
                File buildPropertiesFileTxt = new File(this.outputFolder, "build.properties.file.txt");
                if (!buildPropertiesFileTxt.exists()) {
                    buildPropertiesFileTxt.createNewFile();
                }
                FileOutputStream textOut = new FileOutputStream(buildPropertiesFileTxt);
                allBuildProperties.store(textOut, null);
                textOut.close();
            }
        } catch (Exception ex) {
            throw new MojoExecutionException("Error while creating 'metadata' files", ex);
        }

        try {
            dfw = new FileWriter(digestFile);
            dfw.write(sb.toString());
            dfw.close();
        } catch (Exception ex) {
            throw new MojoExecutionException("Error writing to " + digestFile.toString(), ex);
        }
        // getLog().debug("Written to " + digestFile.toString() + ":\n\n" + sb.toString());
    } else {
        getLog().info("fetch-sources-from-manifests (fetch-sources) :: skipped.");
    }
}

From source file:com.liferay.blade.cli.command.CreateCommandTest.java

@Test
public void testCreateWorkspaceGradleServiceBuilderProjectDefault() throws Exception {
    File workspace = new File(_rootDir, "workspace");

    File modulesDir = new File(workspace, "modules");

    String projectPath = modulesDir.getAbsolutePath();

    String[] args = { "create", "-d", projectPath, "-t", "service-builder", "-p", "com.liferay.sample",
            "sample" };

    _makeWorkspace(workspace);//from   w ww.j  av a 2  s. c o m

    TestUtil.runBlade(workspace, _extensionsDir, args);

    _checkFileExists(projectPath + "/sample/build.gradle");

    _checkFileDoesNotExists(projectPath + "/sample/settings.gradle");

    _checkFileExists(projectPath + "/sample/sample-api/build.gradle");

    _checkFileExists(projectPath + "/sample/sample-service/build.gradle");

    File file = _checkFileExists(projectPath + "/sample/sample-service/build.gradle");

    _contains(file, ".*compileOnly project\\(\":modules:sample:sample-api\"\\).*");

    BuildTask buildService = GradleRunnerUtil.executeGradleRunner(workspace.getPath(), "buildService");

    GradleRunnerUtil.verifyGradleRunnerOutput(buildService);

    BuildTask buildTask = GradleRunnerUtil.executeGradleRunner(workspace.getPath(), "jar");

    GradleRunnerUtil.verifyGradleRunnerOutput(buildTask);

    GradleRunnerUtil.verifyBuildOutput(projectPath + "/sample/sample-api", "com.liferay.sample.api-1.0.0.jar");
    GradleRunnerUtil.verifyBuildOutput(projectPath + "/sample/sample-service",
            "com.liferay.sample.service-1.0.0.jar");

    File serviceJar = new File(projectPath,
            "sample/sample-service/build/libs/com.liferay.sample.service-1.0.0.jar");

    _verifyImportPackage(serviceJar);

    try (JarFile serviceJarFile = new JarFile(serviceJar)) {
        Manifest manifest = serviceJarFile.getManifest();

        Attributes mainAttributes = manifest.getMainAttributes();

        String springContext = mainAttributes.getValue("Liferay-Spring-Context");

        Assert.assertTrue(springContext.equals("META-INF/spring"));
    }
}

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

/**
 * <p>/* www  .java  2  s. co  m*/
 * 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.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/*from ww w  . j  av  a 2s. c o  m*/
        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:org.apache.cocoon.servlet.CocoonServlet.java

private File extractLibraries() {
    try {/*from   ww  w  .j a  v  a  2  s .c o m*/
        URL manifestURL = this.servletContext.getResource("/META-INF/MANIFEST.MF");
        if (manifestURL == null) {
            this.getLogger().fatalError("Unable to get Manifest");
            return null;
        }

        Manifest mf = new Manifest(manifestURL.openStream());
        Attributes attr = mf.getMainAttributes();
        String libValue = attr.getValue("Cocoon-Libs");
        if (libValue == null) {
            this.getLogger().fatalError("Unable to get 'Cocoon-Libs' attribute from the Manifest");
            return null;
        }

        List libList = new ArrayList();
        for (StringTokenizer st = new StringTokenizer(libValue, " "); st.hasMoreTokens();) {
            libList.add(st.nextToken());
        }

        File root = new File(this.workDir, "lib");
        root.mkdirs();

        File[] oldLibs = root.listFiles();
        for (int i = 0; i < oldLibs.length; i++) {
            String oldLib = oldLibs[i].getName();
            if (!libList.contains(oldLib)) {
                this.getLogger().debug("Removing old library " + oldLibs[i]);
                oldLibs[i].delete();
            }
        }

        this.getLogger().warn("Extracting libraries into " + root);
        byte[] buffer = new byte[65536];
        for (Iterator i = libList.iterator(); i.hasNext();) {
            String libName = (String) i.next();

            long lastModified = -1;
            try {
                lastModified = Long.parseLong(attr.getValue("Cocoon-Lib-" + libName.replace('.', '_')));
            } catch (Exception e) {
                this.getLogger().debug("Failed to parse lastModified: "
                        + attr.getValue("Cocoon-Lib-" + libName.replace('.', '_')));
            }

            File lib = new File(root, libName);
            if (lib.exists() && lib.lastModified() != lastModified) {
                this.getLogger().debug("Removing modified library " + lib);
                lib.delete();
            }

            InputStream is = null;
            OutputStream os = null;
            try {
                is = this.servletContext.getResourceAsStream("/WEB-INF/lib/" + libName);
                if (is != null) {
                    this.getLogger().debug("Extracting " + libName);
                    os = new FileOutputStream(lib);
                    int count;
                    while ((count = is.read(buffer)) > 0) {
                        os.write(buffer, 0, count);
                    }
                } else {
                    this.getLogger().warn("Skipping " + libName);
                }
            } finally {
                if (os != null)
                    os.close();
                if (is != null)
                    is.close();
            }

            if (lastModified != -1) {
                lib.setLastModified(lastModified);
            }
        }

        return root;
    } catch (IOException e) {
        this.getLogger().fatalError("Exception while processing Manifest file", e);
        return null;
    }
}

From source file:com.liferay.portal.plugin.PluginPackageUtil.java

private PluginPackage _readPluginPackageServletManifest(ServletContext servletContext) throws IOException {
    Attributes attributes = null;

    String servletContextName = servletContext.getServletContextName();

    InputStream inputStream = servletContext.getResourceAsStream("/META-INF/MANIFEST.MF");

    if (inputStream != null) {
        Manifest manifest = new Manifest(inputStream);

        attributes = manifest.getMainAttributes();
    } else {/*from w ww  .  j  av a  2 s. c  om*/
        attributes = new Attributes();
    }

    String artifactGroupId = attributes.getValue("Implementation-Vendor-Id");

    if (Validator.isNull(artifactGroupId)) {
        artifactGroupId = attributes.getValue("Implementation-Vendor");
    }

    if (Validator.isNull(artifactGroupId)) {
        artifactGroupId = GetterUtil.getString(attributes.getValue("Bundle-Vendor"), servletContextName);
    }

    String artifactId = attributes.getValue("Implementation-Title");

    if (Validator.isNull(artifactId)) {
        artifactId = GetterUtil.getString(attributes.getValue("Bundle-Name"), servletContextName);
    }

    String version = attributes.getValue("Implementation-Version");

    if (Validator.isNull(version)) {
        version = GetterUtil.getString(attributes.getValue("Bundle-Version"), Version.UNKNOWN);
    }

    if (version.equals(Version.UNKNOWN) && _log.isWarnEnabled()) {
        _log.warn("Plugin package on context " + servletContextName
                + " cannot be tracked because this WAR does not contain a "
                + "liferay-plugin-package.xml file");
    }

    PluginPackage pluginPackage = new PluginPackageImpl(artifactGroupId + StringPool.SLASH + artifactId
            + StringPool.SLASH + version + StringPool.SLASH + "war");

    pluginPackage.setName(artifactId);

    String shortDescription = attributes.getValue("Bundle-Description");

    if (Validator.isNotNull(shortDescription)) {
        pluginPackage.setShortDescription(shortDescription);
    }

    String pageURL = attributes.getValue("Bundle-DocURL");

    if (Validator.isNotNull(pageURL)) {
        pluginPackage.setPageURL(pageURL);
    }

    return pluginPackage;
}

From source file:org.apache.cocoon.portlet.CocoonPortlet.java

private File extractLibraries() {
    try {//  w  w w  . j a va  2 s  . c o  m
        URL manifestURL = this.portletContext.getResource("/META-INF/MANIFEST.MF");
        if (manifestURL == null) {
            this.getLogger().fatalError("Unable to get Manifest");
            return null;
        }

        Manifest mf = new Manifest(manifestURL.openStream());
        Attributes attr = mf.getMainAttributes();
        String libValue = attr.getValue("Cocoon-Libs");
        if (libValue == null) {
            this.getLogger().fatalError("Unable to get 'Cocoon-Libs' attribute from the Manifest");
            return null;
        }

        List libList = new ArrayList();
        for (StringTokenizer st = new StringTokenizer(libValue, " "); st.hasMoreTokens();) {
            libList.add(st.nextToken());
        }

        File root = new File(this.workDir, "lib");
        root.mkdirs();

        File[] oldLibs = root.listFiles();
        for (int i = 0; i < oldLibs.length; i++) {
            String oldLib = oldLibs[i].getName();
            if (!libList.contains(oldLib)) {
                this.getLogger().debug("Removing old library " + oldLibs[i]);
                oldLibs[i].delete();
            }
        }

        this.getLogger().warn("Extracting libraries into " + root);
        byte[] buffer = new byte[65536];
        for (Iterator i = libList.iterator(); i.hasNext();) {
            String libName = (String) i.next();

            long lastModified = -1;
            try {
                lastModified = Long.parseLong(attr.getValue("Cocoon-Lib-" + libName.replace('.', '_')));
            } catch (Exception e) {
                this.getLogger().debug("Failed to parse lastModified: "
                        + attr.getValue("Cocoon-Lib-" + libName.replace('.', '_')));
            }

            File lib = new File(root, libName);
            if (lib.exists() && lib.lastModified() != lastModified) {
                this.getLogger().debug("Removing modified library " + lib);
                lib.delete();
            }

            InputStream is = this.portletContext.getResourceAsStream("/WEB-INF/lib/" + libName);
            if (is == null) {
                this.getLogger().warn("Skipping " + libName);
            } else {
                this.getLogger().debug("Extracting " + libName);
                OutputStream os = null;
                try {
                    os = new FileOutputStream(lib);
                    int count;
                    while ((count = is.read(buffer)) > 0) {
                        os.write(buffer, 0, count);
                    }
                } finally {
                    if (is != null)
                        is.close();
                    if (os != null)
                        os.close();
                }
            }

            if (lastModified != -1) {
                lib.setLastModified(lastModified);
            }
        }

        return root;
    } catch (IOException e) {
        this.getLogger().fatalError("Exception while processing Manifest file", e);
        return null;
    }
}

From source file:org.teragrid.portal.filebrowser.applet.ConfigOperation.java

private void readVersionInformation() {
    InputStream stream = null;/*from w  w  w . j  a  v  a  2 s.  com*/
    try {
        JarFile tgfmJar = null;
        URL jarname = Class.forName("org.teragrid.portal.filebrowser.applet.ConfigOperation")
                .getResource("ConfigOperation.class");
        JarURLConnection c = (JarURLConnection) jarname.openConnection();
        tgfmJar = c.getJarFile();
        stream = tgfmJar.getInputStream(tgfmJar.getEntry("META-INF/MANIFEST.MF"));
        Manifest manifest = new Manifest(stream);
        Attributes attributes = manifest.getMainAttributes();
        for (Object attributeName : attributes.keySet()) {
            if (((Attributes.Name) attributeName).toString().equals(("Implementation-Version"))) {
                ConfigSettings.SOFTWARE_VERSION = attributes.getValue("Implementation-Version");
            } else if (((Attributes.Name) attributeName).toString().equals(("Built-Date"))) {
                ConfigSettings.SOFTWARE_BUILD_DATE = attributes.getValue("Built-Date");
            }

            LogManager
                    .debug(attributeName + ": " + attributes.getValue((Attributes.Name) attributeName) + "\n");
        }

        stream.close();
    } catch (Exception e) {
        LogManager.error("Failed to retreive version information.", e);
    } finally {
        try {
            stream.close();
        } catch (Exception e) {
        }
    }
}

From source file:test.BuilderTest.java

/**
 * -exportcontents provides a header that is only relevant in the analyze
 * phase, it augments the Export-Package header.
 *///from   ww  w  .java  2  s. c  o m

public static void testExportContents() throws Exception {
    Builder builder = new Builder();
    try {
        builder.setProperty(Analyzer.INCLUDE_RESOURCE, "test/activator/inherits=src/test/activator/inherits");
        builder.setProperty("-exportcontents", "*;x=true;version=1");
        builder.build();
        assertTrue(builder.check());
        Manifest manifest = builder.calcManifest();
        Attributes main = manifest.getMainAttributes();
        Parameters map = OSGiHeader.parseHeader(main.getValue("Export-Package"));
        Map<String, String> export = map.get("test.activator.inherits");
        assertNotNull(export);
        assertEquals("1", export.get("version"));
        assertEquals("true", export.get("x"));
    } finally {
        builder.close();
    }
}

From source file:test.BuilderTest.java

/**
 * Check if we can create digests/*from  w ww. j a  v a2  s.  c om*/
 * 
 * @throws Exception
 */

public static void testDigests() throws Exception {
    Builder b = new Builder();
    try {
        b.addClasspath(IO.getFile(new File(""), "jar/osgi.jar"));
        b.setExportPackage("org.osgi.framework");
        b.setProperty(Constants.DIGESTS, "MD5, SHA1");
        Jar jar = b.build();
        assertTrue(b.check());
        File f = File.createTempFile("test", ".jar");
        jar.write(f);

        Jar other = new Jar(f);
        Manifest manifest = other.getManifest();
        assertNotNull(manifest);
        Attributes attrs = manifest.getAttributes("org/osgi/framework/BundleActivator.class");
        assertNotNull(attrs);
        assertEquals("RTRhr3kadnulINegRhpmog==", attrs.getValue("MD5-Digest"));
        assertEquals("BfVfpnE3Srx/0UWwtzNecrAGf8A=", attrs.getValue("SHA-Digest"));
        other.close();
    } finally {
        b.close();
    }
}