Example usage for java.util.jar JarOutputStream JarOutputStream

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

Introduction

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

Prototype

public JarOutputStream(OutputStream out, Manifest man) throws IOException 

Source Link

Document

Creates a new JarOutputStream with the specified Manifest.

Usage

From source file:oz.tez.deployment.utils.ClassPathUtils.java

/**
 * Will create a JAR file frombase dir//from  w  w  w .  ja v a 2 s  .com
 *
 * @param source
 * @param jarName
 * @return
 */
public static File toJar(File source, String jarName) {
    if (!source.isAbsolute()) {
        throw new IllegalArgumentException("Source must be expressed through absolute path");
    }
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    File jarFile = new File(jarName);
    try {
        JarOutputStream target = new JarOutputStream(new FileOutputStream(jarFile), manifest);
        add(source, source.getAbsolutePath().length(), target);
        target.close();
    } catch (Exception e) {
        throw new IllegalStateException(
                "Failed to create JAR file '" + jarName + "' from " + source.getAbsolutePath(), e);
    }
    return jarFile;
}

From source file:io.dstream.tez.utils.ClassPathUtils.java

/**
 * Will create a JAR file from base dir/*from  w w w .j  a v  a  2s .co  m*/
 *
 * @param sourceDir
 * @param jarName
 * @return
 */
public static File toJar(File sourceDir, String jarName) {
    if (!sourceDir.isAbsolute()) {
        throw new IllegalArgumentException("Source must be expressed through absolute path");
    }
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    File jarFile = new File(jarName);
    try {
        JarOutputStream target = new JarOutputStream(new FileOutputStream(jarFile), manifest);
        add(sourceDir, sourceDir.getAbsolutePath().length(), target);
        target.close();
    } catch (Exception e) {
        throw new IllegalStateException(
                "Failed to create JAR file '" + jarName + "' from " + sourceDir.getAbsolutePath(), e);
    }
    return jarFile;
}

From source file:org.commonjava.web.test.fixture.JarKnockouts.java

public void rewriteJar(final File source, final File targetDir) throws IOException {
    targetDir.mkdirs();/*ww w . ja va  2  s.  co  m*/
    final File target = new File(targetDir, source.getName());

    JarFile in = null;
    JarOutputStream out = null;
    try {
        in = new JarFile(source);

        final BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(target));
        out = new JarOutputStream(fos, in.getManifest());

        final Enumeration<JarEntry> entries = in.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (!knockout(entry.getName())) {
                final InputStream stream = in.getInputStream(entry);
                out.putNextEntry(entry);
                copy(stream, out);
                out.closeEntry();
            }
        }
    } finally {
        closeQuietly(out);
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
    }
}

From source file:com.opensymphony.xwork2.util.fs.JarEntryRevisionTest.java

private String createJarFile(long time) throws Exception {
    Manifest manifest = new Manifest();
    manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    Path jarPath = Paths//www  . j a v  a 2  s .  c o  m
            .get(Thread.currentThread().getContextClassLoader().getResource("xwork-jar.jar").toURI())
            .getParent();
    File jarFile = jarPath.resolve("JarEntryRevisionTest_testNeedsReloading.jar").toFile();
    FileOutputStream fos = new FileOutputStream(jarFile, false);
    JarOutputStream target = new JarOutputStream(fos, manifest);
    target.putNextEntry(new ZipEntry("com/opensymphony/xwork2/util/fs/"));
    ZipEntry entry = new ZipEntry("com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class");
    entry.setTime(time);
    target.putNextEntry(entry);
    InputStream source = getClass()
            .getResourceAsStream("/com/opensymphony/xwork2/util/fs/JarEntryRevisionTest.class");
    IOUtils.copy(source, target);
    source.close();
    target.closeEntry();
    target.close();
    fos.close();

    return jarFile.toURI().toURL().toExternalForm();
}

From source file:org.echocat.nodoodle.transport.HandlerPacker.java

public void pack(Handler<?> handler, OutputStream to) throws IOException {
    if (handler == null) {
        throw new NullPointerException();
    }//  w ww .  ja v a2  s . c  o m
    if (!(handler instanceof Serializable)) {
        throw new IllegalArgumentException(handler + " is not of type " + Serializable.class.getName() + ".");
    }
    if (to == null) {
        throw new NullPointerException();
    }
    final String dataFileName = getDataFileName();
    // noinspection unchecked
    final Class<? extends Handler<?>> handlerType = (Class<? extends Handler<?>>) handler.getClass();
    final Map<String, JarResource> fileNameToJarResource = buildFileNameToJarResource();
    final Manifest manifest = createManifest(dataFileName, fileNameToJarResource.keySet());
    final JarOutputStream jar = new JarOutputStream(to, manifest);

    final Set<String> namesOfWrittenTypeFiles = new HashSet<String>();
    writeTypes(handlerType, jar, namesOfWrittenTypeFiles);
    writeJarResourcesDependencies(fileNameToJarResource, jar);
    writeData(handler, jar, dataFileName);

    jar.finish();
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/* ww  w.jav a2  s.c  om*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir(expectedHomeDir);
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:com.tasktop.c2c.server.jenkins.configuration.service.JenkinsServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("JenkinsServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {/*from  w w  w  .j a  v a2  s  .c  om*/
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#jenkins.war";
        configurator.setTargetJenkinsHomeBaseDir(expectedHomeDir);
        configurator.setTargetWebappsDir(webappsTarget);
        configurator.setJenkinsPath("/s/");
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:averroes.JarFile.java

/**
 * Get the output stream of this JAR archive.
 * //from   w w  w . ja  va2s.co  m
 * @return
 * @throws IOException
 */
public JarOutputStream getJarOutputStream() throws IOException {
    if (jarOutputStream == null) {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
        jarOutputStream = new JarOutputStream(new FileOutputStream(fileName), manifest);
    }
    return jarOutputStream;
}

From source file:org.commonjava.web.test.fixture.JarKnockouts.java

public static File rewriteJar(final File source, final File targetDir, final Set<JarKnockouts> jarKnockouts)
        throws IOException {
    final JarKnockouts allKnockouts = new JarKnockouts();
    for (final JarKnockouts jk : jarKnockouts) {
        allKnockouts.knockoutPaths(jk.getKnockedOutPaths());
    }/*from  www  .ja  v a  2 s  .  c om*/

    targetDir.mkdirs();
    final File target = new File(targetDir, source.getName());

    JarFile in = null;
    JarOutputStream out = null;
    try {
        in = new JarFile(source);

        final BufferedOutputStream fos = new BufferedOutputStream(new FileOutputStream(target));
        out = new JarOutputStream(fos, in.getManifest());

        final Enumeration<JarEntry> entries = in.entries();
        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (!allKnockouts.knockout(entry.getName())) {
                final InputStream stream = in.getInputStream(entry);
                out.putNextEntry(entry);
                copy(stream, out);
                out.closeEntry();
            }
        }
    } finally {
        closeQuietly(out);
        if (in != null) {
            try {
                in.close();
            } catch (final IOException e) {
            }
        }
    }

    return target;
}

From source file:org.eclipse.gemini.blueprint.test.internal.util.ManifestUtilsTest.java

private void createJar(Manifest mf) throws Exception {
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    JarOutputStream out = new JarOutputStream(storage.getOutputStream(), mf);
    out.flush();//from   ww w  .ja  v  a 2s. c om
    out.close();
}