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.builder.tools.sign.LocalSignedJarBuilder.java

/**
 * Copies the content of a Jar/Zip archive into the receiver archive.
 * <p/>An optional {@link IZipEntryFilter} allows to selectively choose which files
 * to copy over./*from   w  w  w.  ja v a  2 s  . c o  m*/
 *
 * @param input  the {@link InputStream} for the Jar/Zip to copy.
 * @param filter the filter or <code>null</code>
 * @throws IOException
 * @throws SignedJarBuilder.IZipEntryFilter.ZipAbortException if the {@link IZipEntryFilter} filter indicated that the write
 *                                                            must be aborted.
 */
public void writeZip(InputStream input, IZipEntryFilter filter)
        throws IOException, IZipEntryFilter.ZipAbortException {
    ZipInputStream zis = new ZipInputStream(input);

    try {
        // loop on the entries of the intermediary package and put them in the final package.
        ZipEntry entry;
        while ((entry = zis.getNextEntry()) != null) {
            String name = entry.getName();

            // do not take directories or anything inside a potential META-INF folder.
            if (entry.isDirectory()) {
                continue;
            }

            // ignore some of the content in META-INF/ but not all
            if (name.startsWith("META-INF/")) {
                // ignore the manifest file.
                String subName = name.substring(9);
                if ("MANIFEST.MF".equals(subName)) {
                    int count;
                    ByteArrayOutputStream out = new ByteArrayOutputStream();
                    while ((count = zis.read(buffer)) != -1) {
                        out.write(buffer, 0, count);
                    }
                    ByteArrayInputStream swapStream = new ByteArrayInputStream(out.toByteArray());
                    Manifest manifest = new Manifest(swapStream);
                    mManifest.getMainAttributes().putAll(manifest.getMainAttributes());
                    continue;
                }

                // special case for Maven meta-data because we really don't care about them in apks.
                if (name.startsWith("META-INF/maven/")) {
                    continue;
                }

                // check for subfolder
                int index = subName.indexOf('/');
                if (index == -1) {
                    // no sub folder, ignores signature files.
                    if (subName.endsWith(".SF") || name.endsWith(".RSA") || name.endsWith(".DSA")) {
                        continue;
                    }
                }
            }

            // if we have a filter, we check the entry against it
            if (filter != null && !filter.checkEntry(name)) {
                continue;
            }

            JarEntry newEntry;

            // Preserve the STORED method of the input entry.
            if (entry.getMethod() == JarEntry.STORED) {
                newEntry = new JarEntry(entry);
            } else {
                // Create a new entry so that the compressed len is recomputed.
                newEntry = new JarEntry(name);
            }

            writeEntry(zis, newEntry);

            zis.closeEntry();
        }
    } finally {
        zis.close();
    }
}

From source file:org.eclipse.ebr.maven.BundleMojo.java

private File generateFinalBundleManifest() throws MojoExecutionException {
    try {/*from   w w w .  ja va  2  s.c  om*/
        File mfile = new File(outputDirectory, "META-INF/MANIFEST.MF");
        final InputStream is = new FileInputStream(mfile);
        Manifest mf;
        try {
            mf = new Manifest(is);
        } finally {
            is.close();
        }
        final Attributes attributes = mf.getMainAttributes();

        if (attributes.getValue(Name.MANIFEST_VERSION) == null) {
            attributes.put(Name.MANIFEST_VERSION, "1.0");
        }

        // shameless self-promotion
        attributes.putValue(CREATED_BY, "Eclipse Bundle Recipe Maven Plug-in");

        final String expandedVersion = getExpandedVersion();
        attributes.putValue(BUNDLE_VERSION, expandedVersion);

        mfile = getFinalBundleManifestFile();
        mfile.getParentFile().mkdirs();
        final BufferedOutputStream os = new BufferedOutputStream(new FileOutputStream(mfile));
        try {
            mf.write(os);
        } finally {
            os.close();
        }

        return mfile;
    } catch (final Exception e) {
        throw new MojoExecutionException("Error generating bundle manifest: " + e.getMessage(), e);
    }
}

From source file:org.eclipse.ebr.maven.BundleMojo.java

private void generateSourceBundleL10nFile() throws IOException {
    // read generates manifest for resolving bundle name
    final InputStream is = new FileInputStream(getFinalBundleManifestFile());
    Manifest bundleManifest;//from w w w .  ja v  a 2 s  .co  m
    try {
        bundleManifest = new Manifest(is);
    } finally {
        is.close();
    }
    final Properties l10nProps = readL10nProps(bundleManifest);
    String bundleName = getL10nResolvedValue(bundleManifest, BUNDLE_NAME, l10nProps);
    if (bundleName == null) {
        getLog().warn("Bundle-Name header not found in " + getFinalBundleManifestFile()
                + ", fallback to Bundle-SymbolicName for source bundle");
        bundleName = getSourceBundleSymbolicName();
    }
    final String sourceBundleName = bundleName + " Source";
    String bundleVendor = getL10nResolvedValue(bundleManifest, BUNDLE_VENDOR, l10nProps);
    if (bundleVendor == null) {
        getLog().warn("Bundle-Vendor header not found in " + getFinalBundleManifestFile()
                + ", fallback to 'unknown' for source bundle");
        bundleVendor = "unknown";
    }
    final File l10nOutputDir = new File(dependenciesSourcesDirectory);
    final Properties sourceL10nProps = new Properties();
    sourceL10nProps.setProperty(I18N_KEY_BUNDLE_NAME, sourceBundleName);
    sourceL10nProps.setProperty(I18N_KEY_BUNDLE_VENDOR, bundleVendor);
    final File l10nPropsFile = new File(l10nOutputDir, BUNDLE_LOCALIZATION_DEFAULT_BASENAME + ".properties");
    l10nPropsFile.getParentFile().mkdirs();
    OutputStream out = null;
    try {
        out = new FileOutputStream(l10nPropsFile);
        sourceL10nProps.store(out, "Source Bundle Localization");
    } finally {
        IOUtil.close(out);
    }
}

From source file:org.eclipse.birt.build.mavenrepogen.RepoGen.java

private Manifest getManifest(final File file) throws IOException {
    final ZipInputStream zis = new ZipInputStream(new FileInputStream(file));
    try {/*from  w  w w .j av  a 2  s  . c o m*/
        ZipEntry entry = zis.getNextEntry();
        while (entry != null) {
            // read the manifest to determine the name and version number
            // System.out.println(entry.getName() + " " + entry.isDirectory());
            if ("META-INF/MANIFEST.MF".equals(entry.getName()))
                return new Manifest(zis);
            entry = zis.getNextEntry();
        }
    } finally {
        zis.close();
    }
    return null;
}

From source file:com.trsst.Common.java

public static Attributes getManifestAttributes() {
    Attributes result = null;/*from   w w  w. j a  v a2s  .com*/
    Class<Common> clazz = Common.class;
    String className = clazz.getSimpleName() + ".class";
    URL classPath = clazz.getResource(className);
    if (classPath == null || !classPath.toString().startsWith("jar")) {
        // Class not from JAR
        return null;
    }
    String classPathString = classPath.toString();
    String manifestPath = classPathString.substring(0, classPathString.lastIndexOf("!") + 1)
            + "/META-INF/MANIFEST.MF";
    try {
        Manifest manifest = new Manifest(new URL(manifestPath).openStream());
        result = manifest.getMainAttributes();
    } catch (MalformedURLException e) {
        log.error("Could not locate manifest: " + manifestPath);
    } catch (IOException e) {
        log.error("Could not open manifest: " + manifestPath);
    }
    return result;
}

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

private void parseDirectoryManifest(File rootPath, File path, List<PackageDeclaration> packages)
        throws SecurityException {
    File[] files = path.listFiles();
    for (File file : files) {
        // TODO Java7 check for non-symlink,
        // without this check it might generate an infinite loop
        // @link http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#isSymbolicLink(java.nio.file.Path)
        if (!file.isDirectory()) {
            if (file.getName().equals(MANIFEST_FILENAME)) {
                try {
                    Manifest manifest = new Manifest(new FileInputStream(file));
                    parseManifest(manifest, packages);
                } catch (Exception ex) {
                    LOGGER.log(Logger.LOG_WARNING, "Unable to read manifest in " + file.getAbsolutePath(), ex);
                }//from  w ww. j  a  v a 2 s . c o m
            }
            if (FilenameUtils.getExtension(file.getName()).equals("jar") && file.exists()) {
                try {
                    parseJarManifest(file, packages);
                } catch (IOException ex) {
                    LOGGER.log(Logger.LOG_WARNING, "Unable to fetch packages in " + file.getAbsolutePath(), ex);
                }
            }
        } else {
            parseDirectoryManifest(rootPath, file, packages);
        }
    }
}

From source file:interactivespaces.launcher.bootstrap.InteractiveSpacesFrameworkBootstrap.java

/**
 * Get the Interactive Spaces version from the JAR manifest.
 *
 * @return The interactive spaces version
 *//*from w  w  w.jav a2s.  c o m*/
private String getInteractiveSpacesVersion() {
    String classContainer = getClass().getProtectionDomain().getCodeSource().getLocation().toString();

    InputStream in = null;
    try {
        URL manifestUrl = new URL("jar:" + classContainer + "!/META-INF/MANIFEST.MF");
        in = manifestUrl.openStream();
        Manifest manifest = new Manifest(in);
        Attributes attributes = manifest.getMainAttributes();

        return attributes.getValue(MANIFEST_PROPERTY_INTERACTIVESPACES_VERSION);
    } catch (IOException ex) {
        return null;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                // Don't care
            }
        }
    }

}

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

private File extractLibraries() {
    try {/*from w  w  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:org.eclipse.wb.internal.core.editor.palette.dialogs.ImportArchiveDialog.java

private List<PaletteElementInfo> extractElementsFromJarByManifest(JarInputStream jarStream) throws Exception {
    List<PaletteElementInfo> elements = Lists.newArrayList();
    Manifest manifest = jarStream.getManifest();
    // check manifest, if null find it
    if (manifest == null) {
        try {// w  w  w. j a  va 2 s .co  m
            while (true) {
                JarEntry entry = jarStream.getNextJarEntry();
                if (entry == null) {
                    break;
                }
                if (JarFile.MANIFEST_NAME.equalsIgnoreCase(entry.getName())) {
                    // read manifest data
                    byte[] buffer = IOUtils.toByteArray(jarStream);
                    jarStream.closeEntry();
                    // create manifest
                    manifest = new Manifest(new ByteArrayInputStream(buffer));
                    break;
                }
            }
        } catch (Throwable e) {
            DesignerPlugin.log(e);
            manifest = null;
        }
    }
    if (manifest != null) {
        // extract all "Java-Bean: True" classes
        for (Iterator<Map.Entry<String, Attributes>> I = manifest.getEntries().entrySet().iterator(); I
                .hasNext();) {
            Map.Entry<String, Attributes> mapElement = I.next();
            Attributes attributes = mapElement.getValue();
            if (JAVA_BEAN_VALUE.equalsIgnoreCase(attributes.getValue(JAVA_BEAN_KEY))) {
                String beanClass = mapElement.getKey();
                if (beanClass == null || beanClass.length() <= JAVA_BEAN_CLASS_SUFFIX.length()) {
                    continue;
                }
                // convert 'aaa/bbb/ccc.class' to 'aaa.bbb.ccc'
                PaletteElementInfo element = new PaletteElementInfo();
                element.className = StringUtils.substringBeforeLast(beanClass, JAVA_BEAN_CLASS_SUFFIX)
                        .replace('/', '.');
                element.name = CodeUtils.getShortClass(element.className);
                elements.add(element);
            }
        }
    }
    return elements;
}

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

private File extractLibraries() {
    try {/*  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;
    }
}