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:org.apache.xmlgraphics.util.ClasspathResource.java

private void loadManifests() {
        Enumeration e;//from  w w w .  j  a  v a  2s .  com
        try {

            Iterator it = getClassLoadersForResources().iterator();
            while (it.hasNext()) {
                ClassLoader classLoader = (ClassLoader) it.next();

                e = classLoader.getResources(MANIFEST_PATH);

                while (e.hasMoreElements()) {
                    final URL u = (URL) e.nextElement();
                    try {
                        final Manifest manifest = new Manifest(u.openStream());
                        final Map entries = manifest.getEntries();
                        final Iterator entrysetiterator = entries.entrySet().iterator();
                        while (entrysetiterator.hasNext()) {
                            final Map.Entry entry = (Map.Entry) entrysetiterator.next();
                            final String name = (String) entry.getKey();
                            final Attributes attributes = (Attributes) entry.getValue();
                            final String contentType = attributes.getValue(CONTENT_TYPE_KEY);
                            if (contentType != null) {
                                addToMapping(contentType, name, classLoader);
                            }
                        }
                    } catch (IOException io) {
                        // TODO: Log.
                    }
                }
            }

        } catch (IOException io) {
            // TODO: Log.
        }
    }

From source file:org.pentaho.reporting.libraries.base.versioning.VersionHelper.java

/**
 * Loads the versioning information for the given project-information structure using the project information's
 * internal name as lookup key.//from  www  .  j av  a2s  .co m
 *
 * @param projectInformation the project we load information for.
 */
public VersionHelper(final ProjectInformation projectInformation) {
    if (projectInformation == null) {
        throw new NullPointerException();
    }

    this.projectInformation = projectInformation;

    Manifest manifest = manifestCache.get(projectInformation.getInternalName());
    if (manifest == null) {
        final ClassLoader loader = projectInformation.getClass().getClassLoader();
        try {
            final Enumeration resources = loader.getResources("META-INF/MANIFEST.MF");
            while (resources.hasMoreElements()) {
                final URL url = (URL) resources.nextElement();
                final String urlAsText = url.toURI().toString();
                Manifest maybeManifest = manifestCache.getByURL(urlAsText);
                if (maybeManifest == null) {
                    final InputStream inputStream = url.openStream();
                    try {
                        maybeManifest = new Manifest(new BufferedInputStream(inputStream));
                    } finally {
                        inputStream.close();
                    }
                }

                final Attributes attr = getAttributes(maybeManifest, projectInformation.getInternalName());
                final String maybeTitle = getValue(attr, "Implementation-ProductID", null);
                if (maybeTitle != null) {
                    manifestCache.set(maybeTitle, urlAsText, maybeManifest);
                    if (maybeTitle.equals(projectInformation.getInternalName())) {
                        manifest = maybeManifest;
                        break;
                    }
                } else {
                    manifestCache.set(null, urlAsText, maybeManifest);
                }
            }

        } catch (Exception e) {
            // Ignore; Maybe log.
            if (logger.isDebugEnabled()) {
                logger.debug("Failed to read manifest for retrieving library version information for "
                        + projectInformation.getProductId(), e);
            }
        }
    }
    if (manifest != null) {
        init(manifest);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to create version information for " + projectInformation.getInternalName());
        }
        version = "TRUNK.development";
        title = projectInformation.getInternalName();
        productId = projectInformation.getInternalName();
        releaseMajor = "999";
        releaseMinor = "999";
        releaseMilestone = "999";
        releasePatch = "0";
        releaseBuildNumber = SNAPSHOT_TOKEN;
        releaseNumber = createReleaseVersion();
    }
}

From source file:org.sonatype.guice.bean.reflect.BundleClassSpaceTest.java

public void testClassSpaceResources() throws Exception {
    final Bundle testBundle = framework.getBundleContext().installBundle(COMMONS_LOGGING_JAR.toString());
    final ClassSpace space = new BundleClassSpace(testBundle);

    Enumeration<URL> e;

    e = space.getResources("META-INF/MANIFEST.MF");
    assertTrue(e.hasMoreElements());/*from  w  ww  .  ja v a  2 s  . c o  m*/
    assertTrue(e.nextElement().toString().matches("bundle://.*/META-INF/MANIFEST.MF"));
    assertFalse(e.hasMoreElements());

    e = space.findEntries("META-INF", "*.MF", false);
    assertTrue(e.hasMoreElements());
    assertTrue(e.nextElement().toString().matches("bundle://.*/META-INF/MANIFEST.MF"));
    assertFalse(e.hasMoreElements());

    e = space.findEntries(null, "missing", true);
    assertFalse(e.hasMoreElements());

    final URL manifestURL = space.getResource("META-INF/MANIFEST.MF");
    assertNotNull(manifestURL);
    new Manifest(manifestURL.openStream());
}

From source file:org.springframework.cloud.function.adapter.aws.SpringFunctionInitializer.java

private static Class<?> getStartClass(List<URL> list) {
    logger.info("Searching manifests: " + list);
    for (URL url : list) {
        try {/*from   www.  j  a  v  a2 s. c  o m*/
            logger.info("Searching manifest: " + url);
            InputStream inputStream = url.openStream();
            try {
                Manifest manifest = new Manifest(inputStream);
                String startClass = manifest.getMainAttributes().getValue("Start-Class");
                if (startClass != null) {
                    return ClassUtils.forName(startClass, SpringFunctionInitializer.class.getClassLoader());
                }
            } finally {
                inputStream.close();
            }
        } catch (Exception ex) {
        }
    }
    return null;
}

From source file:at.gv.egiz.bku.spring.ConfigurationFactoryBean.java

protected Configuration getVersionConfiguration() throws IOException {

    Map<String, Object> map = new HashMap<String, Object>();
    map.put(MOCCA_IMPLEMENTATIONNAME_PROPERTY, "MOCCA");

    // implementation version
    String version = null;/*  w ww. java 2  s.  c om*/
    try {
        Resource resource = resourceLoader.getResource("META-INF/MANIFEST.MF");
        Manifest properties = new Manifest(resource.getInputStream());
        Attributes attributes = properties.getMainAttributes();
        // TODO: replace by Implementation-Version ?
        version = attributes.getValue("Implementation-Build");
    } catch (Exception e) {
        log.warn("Failed to get implemenation version from manifest. {}", e.getMessage());
    }

    if (version == null) {
        version = "UNKNOWN";
    }
    map.put(MOCCA_IMPLEMENTATIONVERSION_PROPERTY, version);

    // signature layout
    try {
        String classContainer = JarLocation.get(CreateXMLSignatureCommandImpl.class);
        URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF");
        log.debug(manifestUrl.toString());
        Manifest manifest = new Manifest(manifestUrl.openStream());
        Attributes attributes = manifest.getMainAttributes();
        String signatureLayout = attributes.getValue("SignatureLayout");
        if (signatureLayout != null) {
            map.put(SIGNATURE_LAYOUT_PROPERTY, signatureLayout);
        }
    } catch (Exception e) {
        log.warn("Failed to get signature layout from manifest.", e);
    }

    return new MapConfiguration(map);
}

From source file:org.owasp.webgoat.application.WebGoatServletListener.java

private void setApplicationVariables(ServletContext context) {
    Application app = Application.getInstance();
    try {//  w  ww  .j av a 2 s  .  c o m
        InputStream inputStream = context.getResourceAsStream("/META-INF/MANIFEST.MF");
        Manifest manifest = new Manifest(inputStream);
        Attributes attr = manifest.getMainAttributes();
        String name = attr.getValue("Specification-Title");
        String version = attr.getValue("Specification-Version");
        String build = attr.getValue("Implementation-Version");
        app.setName(name);
        app.setVersion(version);
        app.setBuild(build);
    } catch (IOException ioe) {
        context.log("Error setting application variables", ioe);
    }
}

From source file:org.thiesen.ant.git.ExtractGitInfo.java

private String loadJGitVersion() {
    try {/*from   w ww. jav  a2 s .  c om*/
        final Enumeration<URL> resources = getClass().getClassLoader().getResources("META-INF/MANIFEST.MF");
        while (resources.hasMoreElements()) {

            final Manifest manifest = new Manifest(resources.nextElement().openStream());

            final Attributes mainAttributes = manifest.getMainAttributes();

            if ("org.eclipse.jgit".equalsIgnoreCase(mainAttributes.getValue("Bundle-SymbolicName"))) {
                return mainAttributes.getValue("Implementation-Title") + " "
                        + mainAttributes.getValue("Implementation-Version");
            }

        }

    } catch (final IOException E) {
        // do nothing
    }
    return "unknown version";

}

From source file:hudson.ClassicPluginStrategy.java

private static Manifest loadLinkedManifest(File archive) throws IOException {
    // resolve the .hpl file to the location of the manifest file        
    try {/* w w  w. j  a va2 s.  c o  m*/
        // Locate the manifest
        String firstLine;
        FileInputStream manifestHeaderInput = new FileInputStream(archive);
        try {
            firstLine = IOUtils.readFirstLine(manifestHeaderInput, "UTF-8");
        } finally {
            manifestHeaderInput.close();
        }
        if (firstLine.startsWith("Manifest-Version:")) {
            // this is the manifest already
        } else {
            // indirection
            archive = resolve(archive, firstLine);
        }

        // Read the manifest
        FileInputStream manifestInput = new FileInputStream(archive);
        try {
            return new Manifest(manifestInput);
        } finally {
            manifestInput.close();
        }
    } catch (IOException e) {
        throw new IOException("Failed to load " + archive, e);
    }
}

From source file:org.geoserver.ManifestLoader.java

private static Map<String, Manifest> loadManifest(final ClassLoader loader) throws IllegalArgumentException {

    if (loader == null) {
        throw new IllegalArgumentException("Unable to run with null arguments");
    }//from   w  w w . j  a  v  a  2 s .  c  om

    Map<String, Manifest> manifests = new HashMap<String, Manifest>();
    try {
        Enumeration<URL> resources = loader.getResources("META-INF/MANIFEST.MF");
        while (resources.hasMoreElements()) {
            InputStream is = null;
            try {
                URL resource = resources.nextElement();

                if (LOGGER.isLoggable(Level.FINE))
                    LOGGER.fine("Loading resources: " + resource.getFile());

                is = resource.openStream();

                manifests.put(resource.getPath(), new Manifest(is));

            } catch (IOException e) {
                // handle
                LOGGER.log(java.util.logging.Level.SEVERE,
                        "Error loading resources file: " + e.getLocalizedMessage(), e);
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    } catch (IOException e) {
        LOGGER.log(java.util.logging.Level.SEVERE, "Error loading resources file: " + e.getLocalizedMessage(),
                e);
    }

    return manifests;
}

From source file:com.speed.ob.api.ClassStore.java

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