Example usage for java.util.jar Manifest write

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

Introduction

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

Prototype

public void write(OutputStream out) throws IOException 

Source Link

Document

Writes the Manifest to the specified OutputStream.

Usage

From source file:org.apache.hadoop.hbase.mapreduce.hadoopbackport.TestJarFinder.java

@Test
public void testExistingManifest() throws Exception {
    File dir = new File(System.getProperty("test.build.dir", "target/test-dir"),
            TestJarFinder.class.getName() + "-testExistingManifest");
    delete(dir);//from w w w  .  j  a  v  a  2 s  .co  m
    dir.mkdirs();

    File metaInfDir = new File(dir, "META-INF");
    metaInfDir.mkdirs();
    File manifestFile = new File(metaInfDir, "MANIFEST.MF");
    Manifest manifest = new Manifest();
    OutputStream os = new FileOutputStream(manifestFile);
    manifest.write(os);
    os.close();

    File propsFile = new File(dir, "props.properties");
    Writer writer = new FileWriter(propsFile);
    new Properties().store(writer, "");
    writer.close();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream zos = new JarOutputStream(baos);
    JarFinder.jarDir(dir, "", zos);
    JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
    Assert.assertNotNull(jis.getManifest());
    jis.close();
}

From source file:org.apache.hadoop.util.TestJarFinder.java

@Test
public void testExistingManifest() throws Exception {
    File dir = GenericTestUtils.getTestDir(TestJarFinder.class.getName() + "-testExistingManifest");
    delete(dir);/*from  w  w  w  .  j a va  2 s.c  om*/
    dir.mkdirs();

    File metaInfDir = new File(dir, "META-INF");
    metaInfDir.mkdirs();
    File manifestFile = new File(metaInfDir, "MANIFEST.MF");
    Manifest manifest = new Manifest();
    OutputStream os = new FileOutputStream(manifestFile);
    manifest.write(os);
    os.close();

    File propsFile = new File(dir, "props.properties");
    Writer writer = new FileWriter(propsFile);
    new Properties().store(writer, "");
    writer.close();
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    JarOutputStream zos = new JarOutputStream(baos);
    JarFinder.jarDir(dir, "", zos);
    JarInputStream jis = new JarInputStream(new ByteArrayInputStream(baos.toByteArray()));
    Assert.assertNotNull(jis.getManifest());
    jis.close();
}

From source file:org.apache.sling.ide.test.impl.helpers.ProjectAdapter.java

public void createOsgiBundleManifest(OsgiBundleManifest osgiManifest) throws CoreException, IOException {

    Manifest m = new Manifest();
    for (Map.Entry<String, String> entry : osgiManifest.getAttributes().entrySet()) {
        m.getMainAttributes().putValue(entry.getKey(), entry.getValue());
    }/*ww  w. j a va 2s .  co m*/

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    m.write(out);

    createOrUpdateFile(Path.fromPortableString("src/META-INF/MANIFEST.MF"),
            new ByteArrayInputStream(out.toByteArray()));
}

From source file:org.apache.sling.maven.slingstart.PreparePackageMojo.java

private int createSubsystemManifest(Feature feature, Map<String, Integer> startOrderMap, ZipOutputStream os)
        throws IOException {
    int subsystemStartLevel = -1;
    ZipEntry ze = new ZipEntry("SUBSYSTEM-MANIFEST-BASE.MF");
    try {//from  w  w w  .j  a v a2s  . co  m
        os.putNextEntry(ze);

        Manifest mf = new Manifest();
        Attributes attributes = mf.getMainAttributes();
        attributes.putValue("Manifest-Version", "1.0"); // Manifest does not work without this value
        attributes.putValue("Subsystem-SymbolicName", feature.getName());
        attributes.putValue("Subsystem-Version", "1"); // Version must be an integer (cannot be a long), TODO better idea?
        attributes.putValue("Subsystem-Type", feature.getType());
        for (Section section : feature.getAdditionalSections("subsystem-manifest")) {
            String sl = section.getAttributes().get("startLevel");
            try {
                subsystemStartLevel = Integer.parseInt(sl);
            } catch (NumberFormatException nfe) {
                // Not a valid start level
            }

            BufferedReader br = new BufferedReader(new StringReader(section.getContents()));
            String line = null;
            while ((line = br.readLine()) != null) {
                int idx = line.indexOf(':');
                if (idx > 0) {
                    String key = line.substring(0, idx);
                    String value;
                    idx++;
                    if (line.length() > idx)
                        value = line.substring(idx);
                    else
                        value = "";
                    attributes.putValue(key.trim(), value.trim());
                }
            }
        }
        mf.write(os);
    } finally {
        os.closeEntry();
    }

    return subsystemStartLevel;
}

From source file:org.apache.sling.tooling.support.install.impl.InstallServlet.java

private static void createJar(final File sourceDir, final File jarFile, final Manifest mf) throws IOException {
    final JarOutputStream zos = new JarOutputStream(new FileOutputStream(jarFile));
    try {/*  w  w  w. j a v  a  2 s .  co m*/
        zos.setLevel(Deflater.NO_COMPRESSION);
        // manifest first
        final ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(anEntry);
        mf.write(zos);
        zos.closeEntry();
        zipDir(sourceDir, zos, "");
    } finally {
        try {
            zos.close();
        } catch (final IOException ignore) {
            // ignore
        }
    }
}

From source file:org.cloudifysource.dsl.internal.packaging.Packager.java

private static void createManifestFile(final File destPuFolder) throws IOException {
    final File manifestFolder = new File(destPuFolder, "META-INF");
    final File manifestFile = new File(manifestFolder, "MANIFEST.MF");

    final Manifest manifest = new Manifest();

    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    manifest.getMainAttributes().putValue("Class-Path",
            "lib/platform/cloudify/dsl.jar lib/platform/usm/usm.jar "
                    // added support for @grab annotation in groovy file - requires ivy and groovy in same classloader
                    + "tools/groovy/embeddable/groovy-all-1.8.6.jar tools/groovy/lib/ivy-2.2.0.jar ");

    OutputStream out = null;/* w ww  .j a  va2 s  . c o  m*/

    try {
        out = new BufferedOutputStream(new FileOutputStream(manifestFile));
        manifest.write(out);

    } finally {
        if (out != null) {

            try {
                out.close();
            } catch (final IOException e) {
                logger.log(Level.SEVERE, "Failed to close file: " + manifestFile, e);
            }

        }
    }

}

From source file:org.codehaus.enunciate.modules.BasicAppModule.java

/**
 * Copies the classpath elements to WEB-INF.
 *
 * @throws java.io.IOException//from  w  w  w  .java  2 s. c  o  m
 */
protected void doLibCopy() throws IOException {
    Enunciate enunciate = getEnunciate();
    File buildDir = getBuildDir();
    File webinf = new File(buildDir, "WEB-INF");
    File webinfClasses = new File(webinf, "classes");
    File webinfLib = new File(webinf, "lib");

    //initialize the include filters.
    AntPatternMatcher pathMatcher = new AntPatternMatcher();
    pathMatcher.setPathSeparator(File.separator);
    List<File> explicitIncludes = new ArrayList<File>();
    List<String> includePatterns = new ArrayList<String>();
    WebAppConfig webAppConfig = getWebAppConfig();
    if (webAppConfig != null) {
        for (IncludeExcludeLibs el : webAppConfig.getIncludeLibs()) {
            if (el.getFile() != null) {
                //add explicit files to the include files list.
                explicitIncludes.add(el.getFile());
            }

            String pattern = el.getPattern();
            if (pattern != null) {
                //normalize the pattern to the platform.
                pattern = pattern.replace('/', File.separatorChar);
                if (pathMatcher.isPattern(pattern)) {
                    //make sure that the includes pattern list only has patterns.
                    includePatterns.add(pattern);
                } else {
                    warn("Pattern '%s' is not a valid pattern, so it will not be applied.", pattern);
                }
            }
        }
    }

    if (includePatterns.isEmpty()) {
        //if no include patterns are specified, the implicit pattern is "**/*".
        String starPattern = "**" + File.separatorChar + "*";
        debug("No include patterns have been specified.  Using the implicit '%s' pattern.", starPattern);
        includePatterns.add(starPattern);
    }

    List<String> warLibs = new ArrayList<String>();
    if (webAppConfig == null || webAppConfig.isIncludeClasspathLibs()) {
        debug("Using the Enunciate classpath as the initial list of libraries to be passed through the include/exclude filter.");
        //prime the list of libs to include in the war with what's on the enunciate classpath.
        warLibs.addAll(Arrays.asList(enunciate.getEnunciateRuntimeClasspath().split(File.pathSeparator)));
    }

    // Apply the "in filter" (i.e. the filter that specifies the files to be included).
    List<File> includedLibs = new ArrayList<File>();
    for (String warLib : warLibs) {
        File libFile = new File(warLib);
        if (libFile.exists()) {
            for (String includePattern : includePatterns) {
                String absolutePath = libFile.getAbsolutePath();
                if (absolutePath.startsWith(File.separator)) {
                    //lob off the beginning "/" for Linux boxes.
                    absolutePath = absolutePath.substring(1);
                }
                if (pathMatcher.match(includePattern, absolutePath)) {
                    debug("Library '%s' passed the include filter. It matches pattern '%s'.",
                            libFile.getAbsolutePath(), includePattern);
                    includedLibs.add(libFile);
                    break;
                } else if (enunciate.isDebug()) {
                    debug("Library '%s' did NOT match include pattern '%s'.", includePattern);
                }
            }
        }
    }

    //Now, with what's left, apply the "exclude filter".
    boolean excludeDefaults = webAppConfig == null || webAppConfig.isExcludeDefaultLibs();
    List<String> manifestClasspath = new ArrayList<String>();
    Iterator<File> toBeIncludedIt = includedLibs.iterator();
    while (toBeIncludedIt.hasNext()) {
        File toBeIncluded = toBeIncludedIt.next();
        if (excludeDefaults && knownExclude(toBeIncluded)) {
            toBeIncludedIt.remove();
        } else if (webAppConfig != null) {
            for (IncludeExcludeLibs excludeLibs : webAppConfig.getExcludeLibs()) {
                boolean exclude = false;
                if ((excludeLibs.getFile() != null) && (excludeLibs.getFile().equals(toBeIncluded))) {
                    exclude = true;
                    debug("%s was explicitly excluded.", toBeIncluded);
                } else {
                    String pattern = excludeLibs.getPattern();
                    if (pattern != null) {
                        pattern = pattern.replace('/', File.separatorChar);
                        if (pathMatcher.isPattern(pattern)) {
                            String absolutePath = toBeIncluded.getAbsolutePath();
                            if (absolutePath.startsWith(File.separator)) {
                                //lob off the beginning "/" for Linux boxes.
                                absolutePath = absolutePath.substring(1);
                            }

                            if (pathMatcher.match(pattern, absolutePath)) {
                                exclude = true;
                                debug("%s was excluded because it matches pattern '%s'", toBeIncluded, pattern);
                            }
                        }
                    }
                }

                if (exclude) {
                    toBeIncludedIt.remove();
                    if ((excludeLibs.isIncludeInManifest()) && (!toBeIncluded.isDirectory())) {
                        //include it in the manifest anyway.
                        manifestClasspath.add(toBeIncluded.getName());
                        debug("'%s' will be included in the manifest classpath.", toBeIncluded.getName());
                    }
                    break;
                }
            }
        }
    }

    //now add the lib files that are explicitly included.
    includedLibs.addAll(explicitIncludes);

    //now we've got the final list, copy the libs.
    for (File includedLib : includedLibs) {
        if (includedLib.isDirectory()) {
            debug("Adding the contents of %s to WEB-INF/classes.", includedLib);
            enunciate.copyDir(includedLib, webinfClasses);
        } else {
            debug("Including %s in WEB-INF/lib.", includedLib);
            enunciate.copyFile(includedLib, includedLib.getParentFile(), webinfLib);
        }
    }

    // write the manifest file.
    Manifest manifest = webAppConfig == null ? WebAppConfig.getDefaultManifest() : webAppConfig.getManifest();
    if ((manifestClasspath.size() > 0) && (manifest.getMainAttributes().getValue("Class-Path") == null)) {
        StringBuilder manifestClasspathValue = new StringBuilder();
        Iterator<String> manifestClasspathIt = manifestClasspath.iterator();
        while (manifestClasspathIt.hasNext()) {
            String entry = manifestClasspathIt.next();
            manifestClasspathValue.append(entry);
            if (manifestClasspathIt.hasNext()) {
                manifestClasspathValue.append(" ");
            }
        }
        manifest.getMainAttributes().putValue("Class-Path", manifestClasspathValue.toString());
    }
    File metaInf = new File(buildDir, "META-INF");
    metaInf.mkdirs();
    FileOutputStream manifestFileOut = new FileOutputStream(new File(metaInf, "MANIFEST.MF"));
    manifest.write(manifestFileOut);
    manifestFileOut.flush();
    manifestFileOut.close();
}

From source file:org.codehaus.mojo.cassandra.AbstractCassandraMojo.java

/**
 * Create a jar with just a manifest containing a Main-Class entry for SurefireBooter and a Class-Path entry for
 * all classpath elements. Copied from surefire (ForkConfiguration#createJar())
 *
 * @param jarFile   The jar file to create/update
 * @param mainClass The main class to run.
 * @throws java.io.IOException if something went wrong.
 *//*from  w w  w.  j  a  va2 s . c om*/
protected void createCassandraJar(File jarFile, String mainClass, File cassandraDir) throws IOException {
    File conf = new File(cassandraDir, "conf");
    FileOutputStream fos = null;
    JarOutputStream jos = null;
    try {
        fos = new FileOutputStream(jarFile);
        jos = new JarOutputStream(fos);
        jos.setLevel(JarOutputStream.STORED);
        jos.putNextEntry(new JarEntry("META-INF/MANIFEST.MF"));

        Manifest man = new Manifest();

        // we can't use StringUtils.join here since we need to add a '/' to
        // the end of directory entries - otherwise the jvm will ignore them.
        StringBuilder cp = new StringBuilder();
        cp.append(new URL(conf.toURI().toASCIIString()).toExternalForm());
        cp.append(' ');
        getLog().debug("Adding plugin artifact: " + ArtifactUtils.versionlessKey(pluginArtifact)
                + " to the classpath");
        cp.append(new URL(pluginArtifact.getFile().toURI().toASCIIString()).toExternalForm());
        cp.append(' ');

        for (Artifact artifact : this.pluginDependencies) {
            getLog().debug("Adding plugin dependency artifact: " + ArtifactUtils.versionlessKey(artifact)
                    + " to the classpath");
            // NOTE: if File points to a directory, this entry MUST end in '/'.
            cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
            cp.append(' ');
        }

        if (addMainClasspath || addTestClasspath) {
            if (addTestClasspath) {
                getLog().debug("Adding: " + testClassesDirectory + " to the classpath");
                cp.append(new URL(testClassesDirectory.toURI().toASCIIString()).toExternalForm());
                cp.append(' ');
            }
            if (addMainClasspath) {
                getLog().debug("Adding: " + classesDirectory + " to the classpath");
                cp.append(new URL(classesDirectory.toURI().toASCIIString()).toExternalForm());
                cp.append(' ');
            }
            for (Artifact artifact : (Set<Artifact>) this.project.getArtifacts()) {
                if ("jar".equals(artifact.getType()) && !Artifact.SCOPE_PROVIDED.equals(artifact.getScope())
                        && (!Artifact.SCOPE_TEST.equals(artifact.getScope()) || addTestClasspath)) {
                    getLog().debug("Adding dependency: " + ArtifactUtils.versionlessKey(artifact)
                            + " to the classpath");
                    // NOTE: if File points to a directory, this entry MUST end in '/'.
                    cp.append(new URL(artifact.getFile().toURI().toASCIIString()).toExternalForm());
                    cp.append(' ');
                }
            }
        }

        man.getMainAttributes().putValue("Manifest-Version", "1.0");
        man.getMainAttributes().putValue("Class-Path", cp.toString().trim());
        man.getMainAttributes().putValue("Main-Class", mainClass);

        man.write(jos);
    } finally {
        IOUtil.close(jos);
        IOUtil.close(fos);
    }
}

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

private File generateFinalBundleManifest() throws MojoExecutionException {
    try {// www. j a va  2s. 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 File generateSourceBundleManifest() throws MojoExecutionException {
    try {//w  ww  . j a  v a 2 s .  c  o m
        generateSourceBundleL10nFile();

        final Manifest mf = new Manifest();
        final Attributes attributes = mf.getMainAttributes();

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

        final String expandedVersion = getExpandedVersion();
        attributes.putValue(BUNDLE_VERSION, expandedVersion);
        attributes.putValue(BUNDLE_MANIFESTVERSION, "2");
        attributes.putValue(BUNDLE_SYMBOLICNAME, getSourceBundleSymbolicName());
        attributes.putValue(BUNDLE_NAME, I18N_KEY_PREFIX + I18N_KEY_BUNDLE_NAME);
        attributes.putValue(BUNDLE_VENDOR, I18N_KEY_PREFIX + I18N_KEY_BUNDLE_VENDOR);
        //attributes.putValue(BUNDLE_LOCALIZATION, BUNDLE_LOCALIZATION_DEFAULT_BASENAME);
        attributes.putValue("Eclipse-SourceBundle",
                project.getArtifactId() + ";version=\"" + expandedVersion + "\";roots:=\".\"");
        attributes.putValue(CREATED_BY, "Eclipse Bundle Recipe Maven Plug-in");

        final File mfile = getSourceBundleManifestFile();
        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 source bundle manifest: " + e.getMessage(), e);
    }
}