Example usage for java.util.jar Manifest getMainAttributes

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

Introduction

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

Prototype

public Attributes getMainAttributes() 

Source Link

Document

Returns the main Attributes for the Manifest.

Usage

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

private void processExtensions(File f, Manifest mf, Writer fileWriter, String dashcnb, String codebase,
        String permissions) throws IOException, BuildException {

    File nblibJar = new File(new File(new File(f.getParentFile().getParentFile(), "ant"), "nblib"),
            dashcnb + ".jar");
    if (nblibJar.isFile()) {
        File ext = new File(new File(targetFile, dashcnb), "ant-nblib-" + nblibJar.getName());
        fileWriter.write(constructJarHref(ext, dashcnb));
        signOrCopy(nblibJar, ext);//from  ww w.ja  v  a 2 s  .  c om
    }

    String path = mf.getMainAttributes().getValue("Class-Path");
    if (path == null) {
        return;
    }

    StringTokenizer tok = new StringTokenizer(path, ", ");
    while (tok.hasMoreElements()) {
        String s = tok.nextToken();

        if (s.contains("${java.home}")) {
            continue;
        }

        File e = new File(f.getParentFile(), s);
        if (!e.canRead()) {
            throw new BuildException("Cannot read extension " + e + " referenced from " + f);
        }

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

        String n = e.getName();
        if (n.endsWith(".jar")) {
            n = n.substring(0, n.length() - 4);
        }
        File ext = new File(new File(targetFile, dashcnb), s.replace("../", "").replace('/', '-'));

        if (isSigned(e) != null) {
            signOrCopy(e, ext);
            //                Copy copy = (Copy)getProject().createTask("copy");
            //                copy.setFile(e);
            //                copy.setTofile(ext);
            //                copy.execute();

            String extJnlpName = dashcnb + '-' + ext.getName().replaceFirst("\\.jar$", "") + ".jnlp";
            File jnlp = new File(targetFile, extJnlpName);

            FileWriter writeJNLP = new FileWriter(jnlp);
            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>" + n + "</title>\n");
            writeJNLP.write("    <vendor>NetBeans</vendor>\n");
            writeJNLP.write("  </information>\n");
            writeJNLP.write(permissions + "\n");
            writeJNLP.write("  <resources>\n");
            writeJNLP
                    .write("<property name=\"jnlp.packEnabled\" value=\"" + String.valueOf(pack200) + "\"/>\n");
            writeJNLP.write(constructJarHref(ext, dashcnb));
            writeJNLP.write("  </resources>\n");
            writeJNLP.write("  <component-desc/>\n");
            writeJNLP.write("</jnlp>\n");
            writeJNLP.close();

            fileWriter.write("    <extension name='" + e.getName().replaceFirst("\\.jar$", "") + "' href='"
                    + extJnlpName + "'/>\n");
        } else {
            signOrCopy(e, ext);

            fileWriter.write(constructJarHref(ext, dashcnb));
        }
    }
}

From source file:org.apache.cocoon.servlet.CocoonServlet.java

private File extractLibraries() {
    try {//from   w  ww . 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:org.teragrid.portal.filebrowser.applet.ConfigOperation.java

private void readVersionInformation() {
    InputStream stream = null;/*from   w  ww. ja 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:org.openspaces.pu.container.servicegrid.PUServiceBeanImpl.java

private List<URL> getManifestClassPathJars(String puName, InputStream manifestStream) {
    List<URL> exportedManifestUrls = new ArrayList<URL>();
    try {/*from  ww  w . j av  a 2  s.c o  m*/

        Manifest manifest = new Manifest(manifestStream);

        String manifestClasspathLibs = manifest.getMainAttributes().getValue("Class-Path");
        if (manifestClasspathLibs != null) {
            String[] manifestLibFiles = StringUtils.tokenizeToStringArray(manifestClasspathLibs, " ");
            for (String fileName : manifestLibFiles) {

                try {
                    fileName = PlaceholderReplacer.replacePlaceholders(System.getenv(), fileName);
                } catch (PlaceholderResolutionException e) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Could not resolve manifest classpath entry: " + fileName
                                + " of processing unit " + puName, e);
                    }
                    continue;
                }

                URL url = null;
                try {
                    url = new URL(fileName);
                    if (!"file".equals(url.getProtocol())) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Only file protocol is supported in urls, found : '" + fileName
                                    + "' in manifest classpath of processing unit " + puName);
                        }
                        continue;
                    }
                } catch (MalformedURLException e) {
                    // moving on, checking if file path has been provided
                }

                File file;
                if (url != null) {
                    try {
                        file = new File(url.toURI());
                    } catch (URISyntaxException e) {
                        if (logger.isWarnEnabled()) {
                            logger.warn("Invalid url: " + url + " provided in pu " + puName
                                    + " manifest classpath, ignoring entry", e);
                        }
                        continue;
                    }
                } else {
                    file = new File(fileName);
                }

                if (!file.isAbsolute()) {
                    file = new File(SystemInfo.singleton().getXapHome(), fileName);
                }

                if (!file.isFile()) {
                    if (logger.isWarnEnabled()) {
                        logger.warn("Did not find manifest classpath entry: " + file.getAbsolutePath()
                                + " for processing unit: " + puName + ", ignoring entry.");
                    }
                    continue;
                }

                if (logger.isDebugEnabled()) {
                    logger.debug("Adding " + file.getAbsolutePath()
                            + " read from MANIFEST.MF to processing unit: " + puName + " classpath");
                }

                URL urlToAdd = file.toURI().toURL();
                exportedManifestUrls.add(urlToAdd);
            }
        }
    } catch (IOException e) {
        if (logger.isWarnEnabled()) {
            logger.warn(failedReadingManifest(puName), e);
        }
    } finally {
        try {
            manifestStream.close();
        } catch (IOException e) {
            if (logger.isWarnEnabled()) {
                logger.warn("Failed closing manifest input stream.", e);
            }
        }
    }
    return exportedManifestUrls;
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlProducesOsgiManifest() throws IOException {
    compile("modules/osgi/a/module.ceylon", "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon");

    final String moduleName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a";
    final String moduleVersion = "1.1.0";

    final Manifest manifest = getManifest(moduleName, moduleVersion);

    Attributes attr = manifest.getMainAttributes();
    assertEquals("2", attr.get(OsgiUtil.OsgiManifest.Bundle_ManifestVersion));

    assertEquals(moduleName, attr.get(OsgiUtil.OsgiManifest.Bundle_SymbolicName));
    String bundleVersion = (String) attr.get(OsgiUtil.OsgiManifest.Bundle_Version);
    int qualifierIndex = bundleVersion.lastIndexOf('.');
    String bundleVersionWithoutQualifier = qualifierIndex > 0 ? bundleVersion.substring(0, qualifierIndex)
            : bundleVersion;/*from   ww w .  ja  v  a 2s .  c om*/
    assertEquals(moduleVersion, bundleVersionWithoutQualifier);
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlOsgiManifestReexportsSharedImportedModules() throws IOException {
    compile("modules/osgi/a/module.ceylon", "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon");

    compile("modules/osgi/c/module.ceylon", "modules/osgi/c/package.ceylon", "modules/osgi/c/C.ceylon");

    final String moduleCName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.c";
    final String moduleVersion = "1.1.0";

    final Manifest manifest = getManifest(moduleCName, moduleVersion);
    final String[] requireBundle = ((String) manifest.getMainAttributes()
            .get(OsgiUtil.OsgiManifest.Require_Bundle)).split(",");

    assertEquals(3, requireBundle.length);
    assertThat(Arrays.asList(requireBundle), CoreMatchers.hasItems(
            "ceylon.language;bundle-version=" + Versions.CEYLON_VERSION_NUMBER + ";visibility:=reexport",
            "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a;bundle-version=1.1.0;visibility:=reexport",
            "com.redhat.ceylon.dist;bundle-version=" + Versions.CEYLON_VERSION_NUMBER
                    + ";visibility:=reexport"));
}

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

private File extractLibraries() {
    try {//from   ww w.  j  a  v a  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:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlOsgiManifestRequresImportedModules() throws IOException {
    compile("modules/osgi/a/module.ceylon", "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon");

    compile("modules/osgi/b/module.ceylon", "modules/osgi/b/package.ceylon", "modules/osgi/b/B.ceylon");

    final String moduleBName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.b";
    final String moduleVersion = "1.1.0";

    final Manifest manifest = getManifest(moduleBName, moduleVersion);

    final String[] requireBundle = ((String) manifest.getMainAttributes()
            .get(OsgiUtil.OsgiManifest.Require_Bundle)).split(",");
    assertEquals(3, requireBundle.length);

    assertThat(Arrays.asList(requireBundle),
            CoreMatchers.hasItems(//from ww  w .jav a 2 s.  co  m
                    "ceylon.language;bundle-version=" + Versions.CEYLON_VERSION_NUMBER
                            + ";visibility:=reexport",
                    "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a;bundle-version=1.1.0",
                    "com.redhat.ceylon.dist;bundle-version=" + Versions.CEYLON_VERSION_NUMBER
                            + ";visibility:=reexport"));
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlOsgiManifestFiltersProvidedBundles() throws IOException {
    compile("modules/osgi/a/module.ceylon", "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon");

    ArrayList<String> options = new ArrayList<>(defaultOptions);
    options.addAll(Arrays.asList("-osgi-provided-bundles",
            "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a , ceylon.language"));

    compilesWithoutWarnings(options, "modules/osgi/b/module.ceylon", "modules/osgi/b/package.ceylon",
            "modules/osgi/b/B.ceylon");

    final String moduleBName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.b";
    final String moduleVersion = "1.1.0";

    final Manifest manifest = getManifest(moduleBName, moduleVersion);

    final String[] requireBundle = ((String) manifest.getMainAttributes()
            .get(OsgiUtil.OsgiManifest.Require_Bundle)).split(",");
    assertEquals(1, requireBundle.length);

    assertThat(Arrays.asList(requireBundle), CoreMatchers.hasItems("com.redhat.ceylon.dist;bundle-version="
            + Versions.CEYLON_VERSION_NUMBER + ";visibility:=reexport"));
}

From source file:com.redhat.ceylon.compiler.java.test.cmr.CMRTests.java

@Test
public void testMdlOsgiManifestFiltersProvidedBundle() throws IOException {
    compile("modules/osgi/a/module.ceylon", "modules/osgi/a/package.ceylon", "modules/osgi/a/A.ceylon");

    ArrayList<String> options = new ArrayList<>(defaultOptions);
    options.addAll(/*from   ww  w . ja  v  a2 s  .  c o  m*/
            Arrays.asList("-osgi-provided-bundles", "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.a"));

    compilesWithoutWarnings(options, "modules/osgi/b/module.ceylon", "modules/osgi/b/package.ceylon",
            "modules/osgi/b/B.ceylon");

    final String moduleBName = "com.redhat.ceylon.compiler.java.test.cmr.modules.osgi.b";
    final String moduleVersion = "1.1.0";

    final Manifest manifest = getManifest(moduleBName, moduleVersion);

    final String[] requireBundle = ((String) manifest.getMainAttributes()
            .get(OsgiUtil.OsgiManifest.Require_Bundle)).split(",");
    assertEquals(2, requireBundle.length);

    assertThat(Arrays.asList(requireBundle),
            CoreMatchers.hasItems(
                    "ceylon.language;bundle-version=" + Versions.CEYLON_VERSION_NUMBER
                            + ";visibility:=reexport",
                    "com.redhat.ceylon.dist;bundle-version=" + Versions.CEYLON_VERSION_NUMBER
                            + ";visibility:=reexport"));
}