Example usage for java.util.jar Manifest Manifest

List of usage examples for java.util.jar Manifest Manifest

Introduction

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

Prototype

public Manifest(Manifest man) 

Source Link

Document

Constructs a new Manifest that is a copy of the specified Manifest.

Usage

From source file:com.taobao.android.apatch.MergePatch.java

private void fillManifest(Attributes main) throws IOException {
    JarFile jarFile;//from  www .  ja  va 2s .co m
    Manifest manifest;
    StringBuffer fromBuffer = new StringBuffer();
    StringBuffer toBuffer = new StringBuffer();
    String from;
    String to;
    String name;
    // String classes;
    for (File file : patchs) {
        jarFile = new JarFile(file);
        JarEntry dexEntry = jarFile.getJarEntry("META-INF/PATCH.MF");
        manifest = new Manifest(jarFile.getInputStream(dexEntry));
        Attributes attributes = manifest.getMainAttributes();

        from = attributes.getValue("From-File");
        if (fromBuffer.length() > 0) {
            fromBuffer.append(',');
        }
        fromBuffer.append(from);
        to = attributes.getValue("To-File");
        if (toBuffer.length() > 0) {
            toBuffer.append(',');
        }
        toBuffer.append(to);

        name = attributes.getValue("Patch-Name");
        // classes = attributes.getValue(name + "-Patch-Classes");
        main.putValue(name + "-Patch-Classes", attributes.getValue(name + "-Patch-Classes"));
        main.putValue(name + "-Prepare-Classes", attributes.getValue(name + "-Prepare-Classes"));
        main.putValue(name + "-Used-Methods", attributes.getValue(name + "-Used-Methods"));
        main.putValue(name + "-Modified-Classes", attributes.getValue(name + "-Modified-Classes"));
        main.putValue(name + "-Used-Classes", attributes.getValue(name + "-Used-Classes"));
        main.putValue(name + "-add-classes", attributes.getValue(name + "-add-classes"));

    }
    main.putValue("From-File", fromBuffer.toString());
    main.putValue("To-File", toBuffer.toString());
}

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

public void execute() throws MojoExecutionException, MojoFailureException {
    if (!skip) {/*from   ww  w .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:org.hl7.fhir.instance.conf.ServerConformanceProvider.java

private String getBuildDateFromManifest() {
    if (myRestfulServer != null && myRestfulServer.getServletContext() != null) {
        InputStream inputStream = myRestfulServer.getServletContext()
                .getResourceAsStream("/META-INF/MANIFEST.MF");
        if (inputStream != null) {
            try {
                Manifest manifest = new Manifest(inputStream);
                return manifest.getMainAttributes().getValue("Build-Time");
            } catch (IOException e) {
                // fall through
            }/*from ww w . ja  va  2 s .  com*/
        }
    }
    return null;
}

From source file:io.selendroid.standalone.builder.SelendroidServerBuilder.java

private static String getVersionFromManifest(String path) throws IOException {
    String manifestPath = path.substring(0, path.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF";
    Manifest manifest = new Manifest(new URL(manifestPath).openStream());
    Attributes attr = manifest.getMainAttributes();
    return attr.getValue("version");
}

From source file:de.upb.wdqa.wdvd.FeatureExtractor.java

private static String getBuildTime() {
    String result = null;//from   ww  w . j  ava 2  s.c o m
    try {
        Enumeration<URL> resources;
        resources = FeatureExtractor.class.getClassLoader().getResources("META-INF/MANIFEST.MF");

        //      while (resources.hasMoreElements()) {
        Manifest manifest = new Manifest(resources.nextElement().openStream());
        // check that this is your manifest and do what you need or get the next one

        result = manifest.getMainAttributes().getValue("Build-Time");

    } catch (IOException e) {
    }

    return result;
}

From source file:org.universAAL.itests.IntegrationTest.java

/**
 * This method copies contents of target/classes to target/test-classes.
 * Thanks to that regular classes of given bundle can be used for testing
 * without a need to load the bundle from maven repository. It is very
 * important because in the maven build cycle "test" precedes "install". If
 * this method will not be invoked, when bundle does not exist in the maven
 * repository there is a deadlock - bundle cannot be tested because it is
 * not in the repo and bundle cannot be installed in the repo because tests
 * fail./*from   w  w  w .ja  v  a  2s . co m*/
 *
 * Additionally method rewrites bundle manifest for purpose of adding
 * imports to packages related to itests bundle.
 *
 * @throws IOException
 *
 */
private void prepareClassesToTests() throws Exception {
    FileUtils.copyDirectory(new File("./target/classes"), new File("./target/test-classes"));
    File separatedArtifactDepsFile = new File(IntegrationTestConsts.SEPARATED_ARTIFACT_DEPS);
    if (separatedArtifactDepsFile.exists()) {
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(new FileInputStream(separatedArtifactDepsFile)));
        String line = null;
        while ((line = reader.readLine()) != null) {
            if (!line.isEmpty()) {
                unzipInpuStream(new URL(line).openStream(), "target/test-classes");
            }
        }
    }

    Manifest bundleMf = new Manifest(new FileInputStream("./target/classes/META-INF/MANIFEST.MF"));
    Attributes mainAttribs = bundleMf.getMainAttributes();

    bundleSymbolicName = mainAttribs.getValue("Bundle-SymbolicName");
    bundleVersion = mainAttribs.getValue("Bundle-Version");
    bundleVersion = bundleVersion.replaceFirst("\\.SNAPSHOT", "-SNAPSHOT");

    mainAttribs.put(new Attributes.Name("Import-Package"),
            mainAttribs.getValue("Import-Package") + ",org.universAAL.itests,org.springframework.util");
    String dynamicImports = mainAttribs.getValue("DynamicImport-Package");
    if (dynamicImports == null) {
        dynamicImports = "*";
        mainAttribs.put(new Attributes.Name("DynamicImport-Package"), dynamicImports);
    }

    bundleMf.write(new FileOutputStream("./target/test-classes/META-INF/MANIFEST.MF"));
}

From source file:com.stacksync.desktop.util.FileUtil.java

public static String getPropertyFromManifest(String manifestPath, String property) {
    try {/*from  w  w w .ja v  a2 s.  c om*/
        URLClassLoader cl = (URLClassLoader) FileUtil.class.getClassLoader();

        URL url = cl.findResource(manifestPath);
        Manifest manifest = new Manifest(url.openStream());
        Attributes attr = manifest.getMainAttributes();

        return attr.getValue(property);
    } catch (IOException ex) {
        logger.debug("Exception: ", ex);
        return null;
    }
}

From source file:at.gv.egovernment.moa.id.configuration.config.ConfigurationProvider.java

private String parseVersionFromManifest() {

    try {//w ww.  j a va 2  s  .  c  o  m
        Class clazz = ConfigurationProvider.class;
        String className = clazz.getSimpleName() + ".class";
        String classPath = clazz.getResource(className).toString();

        if (classPath.startsWith("jar")) {
            log.info("MOA-ID-Configuration Version can NOT parsed from Manifest. Set blank Version");
            return Constants.DEFAULT_VERSION;

        }

        String manifestPath = classPath.substring(0,
                classPath.lastIndexOf("WEB-INF/classes/") + "WEB-INF/classes/".length())
                + "../../META-INF/MANIFEST.MF";

        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
        ;

        Attributes attributes = manifest.getMainAttributes();
        String version = attributes.getValue("version");

        if (MiscUtil.isNotEmpty(version))
            return version;

        else {
            log.info("MOA-ID-Configuration Version not found in Manifest. Set blank Version");
            return Constants.DEFAULT_VERSION;

        }

    } catch (Throwable e) {
        log.info("MOA-ID Version can NOT parsed from Manifest. Set blank Version");

        return Constants.DEFAULT_VERSION;
    }

}

From source file:org.orbisgis.framework.BundleTools.java

private List<String> getClassPath() {
    List<String> classPath = new LinkedList<String>();
    // Read declared class in the manifest
    try {/* w  w  w .  j  ava 2  s  .  co  m*/
        Enumeration<URL> resources = BundleTools.class.getClassLoader().getResources("META-INF/MANIFEST.MF");
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            try {
                Manifest manifest = new Manifest(url.openStream());
                String value = manifest.getMainAttributes().getValue(Attributes.Name.CLASS_PATH);
                if (value != null) {
                    String[] pathElements = value.split(" ");
                    if (pathElements == null) {
                        pathElements = new String[] { value };
                    }
                    classPath.addAll(Arrays.asList(pathElements));
                }
            } catch (IOException ex) {
                LOGGER.log(Logger.LOG_WARNING, "Unable to retrieve Jar MANIFEST " + url, ex);
            }
        }
    } catch (IOException ex) {
        LOGGER.log(Logger.LOG_WARNING, "Unable to retrieve Jar MANIFEST", ex);
    }
    // Read packages in the class path
    String javaClasspath = System.getProperty("java.class.path");
    String[] pathElements = javaClasspath.split(":");
    if (pathElements == null) {
        pathElements = new String[] { javaClasspath };
    }
    classPath.addAll(Arrays.asList(pathElements));
    return classPath;
}

From source file:org.jahia.utils.maven.plugin.osgi.BuildFrameworkPackageListMojo.java

private void scanExistingManifest(Map<String, Map<String, Map<String, VersionLocation>>> packageVersionCounts)
        throws IOException, Exception {
    FileInputStream in = null;//from  w  ww. j av a2  s  .c  o  m
    try {
        if (inputManifestFile.exists()) {
            in = new FileInputStream(inputManifestFile);
            Manifest mf = new Manifest(in);
            String exportPackageStr = mf.getMainAttributes().getValue("Export-Package");
            String bundleVersion = mf.getMainAttributes().getValue("Bundle-Version");
            ManifestElement[] manifestElements = ManifestElement.parseHeader("Export-Package",
                    exportPackageStr);
            if (manifestElements != null) {
                for (ManifestElement manifestElement : manifestElements) {
                    String[] packageNames = manifestElement.getValueComponents();
                    String version = manifestElement.getAttribute("version");
                    if (version != null) {
                        for (String packageName : packageNames) {
                            if (version.equals(bundleVersion)) {
                                if (packageName.startsWith("org.jahia")) {
                                    updateVersionLocationCounts(packageVersionCounts,
                                            inputManifestFile.toString(), version, bundleVersion, packageName);
                                } else {
                                    updateVersionLocationCounts(packageVersionCounts,
                                            inputManifestFile.toString(), null, bundleVersion, packageName);
                                }
                            } else {
                                updateVersionLocationCounts(packageVersionCounts, inputManifestFile.toString(),
                                        version, bundleVersion, packageName);
                            }
                        }
                    } else {
                        for (String packageName : packageNames) {
                            updateVersionLocationCounts(packageVersionCounts, inputManifestFile.toString(),
                                    null, bundleVersion, packageName);
                        }
                    }
                }
                getLog().info("Found " + manifestElements.length + " package exports.");
            }
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}