Example usage for java.util.jar JarOutputStream putNextEntry

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

Introduction

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

Prototype

public void putNextEntry(ZipEntry ze) throws IOException 

Source Link

Document

Begins writing a new JAR file entry and positions the stream to the start of the entry data.

Usage

From source file:gov.redhawk.rap.internal.PluginProviderServlet.java

private void addFiles(final JarOutputStream out, final IPath path, final File... listFiles) throws IOException {
    for (final File f : listFiles) {
        if (f.getName().charAt(0) == '.') {
            continue;
        } else if (f.getName().equals("MANIFEST.MF")) {
            continue;
        }//  w w w. j a  v  a2s .c  o m
        final IPath filePath = path.append(f.getName());
        String str = filePath.toString();
        if (str.startsWith("/")) {
            str = str.substring(1);
        }
        if (f.isDirectory()) {
            if (!str.endsWith("/")) {
                str = str + "/";
            }
            final JarEntry entry = new JarEntry(str);
            entry.setSize(0);
            entry.setTime(f.lastModified());
            out.putNextEntry(entry);
            out.closeEntry();
            addFiles(out, filePath, f.listFiles());
        } else {
            final JarEntry entry = new JarEntry(str);
            entry.setSize(f.length());
            entry.setTime(f.lastModified());
            out.putNextEntry(entry);
            final FileInputStream istream = new FileInputStream(f);
            try {
                IOUtils.copy(istream, out);
            } finally {
                istream.close();
            }
            out.closeEntry();
        }
    }
}

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 ww.  j  a v a 2 s. c o  m*/
        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: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 {//from   w w  w.j  a  va 2 s  .  com
        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.taobao.android.builder.tools.multidex.FastMultiDexer.java

protected void copyStream(InputStream inputStream, JarOutputStream jos, JarEntry ze, String pathName) {
    try {//  w  w  w.  j  av  a 2 s.  co  m

        ZipEntry newEntry = new ZipEntry(pathName);
        // Make sure there is date and time set.
        if (ze.getTime() != -1) {
            newEntry.setTime(ze.getTime()); // If found set it into output file.
        }
        jos.putNextEntry(newEntry);
        IOUtils.copy(inputStream, jos);
        IOUtils.closeQuietly(inputStream);
    } catch (Exception e) {
        throw new GradleException("copy stream exception", e);
    }
}

From source file:org.apache.hadoop.mapred.TestTaskTrackerLocalization.java

/**
 * @param jobConf//from w ww. j  a v a  2 s  .  co  m
 * @throws IOException
 * @throws FileNotFoundException
 */
private void uploadJobJar(JobConf jobConf) throws IOException, FileNotFoundException {
    File jobJarFile = new File(TEST_ROOT_DIR, "jobjar-on-dfs.jar");
    JarOutputStream jstream = new JarOutputStream(new FileOutputStream(jobJarFile));
    ZipEntry ze = new ZipEntry("lib/lib1.jar");
    jstream.putNextEntry(ze);
    jstream.closeEntry();
    ze = new ZipEntry("lib/lib2.jar");
    jstream.putNextEntry(ze);
    jstream.closeEntry();
    jstream.finish();
    jstream.close();
    jobConf.setJar(jobJarFile.toURI().toString());
}

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

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File hudsonTemplateWar = new File(warTemplateFile);

    if (!hudsonTemplateWar.exists() || !hudsonTemplateWar.isFile()) {
        String message = "The given Hudson template WAR [" + hudsonTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);//  w w  w .j  a  v a 2 s . co  m
        throw new IllegalStateException(message);
    }

    String deployLocation = hudsonWarNamingStrategy.getWarFilePath(configuration);

    File hudsonDeployFile = new File(deployLocation);

    if (hudsonDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + hudsonDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile hudsonTemplateWarJar = new JarFile(hudsonTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = hudsonTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(hudsonTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct HUDSON_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedHudsonWar = File.createTempFile("hudson", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedHudsonWar),
                hudsonTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = hudsonTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

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

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(hudsonTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into it's deployment location so that it can be picked up and deployed by Tomcat.
        FileUtils.moveFile(updatedHudsonWar, hudsonDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:com.threerings.media.tile.bundle.tools.TileSetBundler.java

/**
 * Create a tileset bundle jar file.// w  w w.j av a  2  s .co m
 *
 * @param target the tileset bundle file that will be created.
 * @param bundle contains the tilesets we'd like to save out to the bundle.
 * @param improv the image provider.
 * @param imageBase the base directory for getting images for non-ObjectTileSet tilesets.
 * @param keepOriginalPngs bundle up the original PNGs as PNGs instead of converting to the
 * FastImageIO raw format
 */
public static boolean createBundleJar(File target, TileSetBundle bundle, ImageProvider improv, String imageBase,
        boolean keepOriginalPngs, boolean uncompressed) throws IOException {
    // now we have to create the actual bundle file
    FileOutputStream fout = new FileOutputStream(target);
    Manifest manifest = new Manifest();
    JarOutputStream jar = new JarOutputStream(fout, manifest);
    jar.setLevel(uncompressed ? Deflater.NO_COMPRESSION : Deflater.BEST_COMPRESSION);

    try {
        // write all of the image files to the bundle, converting the
        // tilesets to trimmed tilesets in the process
        Iterator<Integer> iditer = bundle.enumerateTileSetIds();

        // Store off the updated TileSets in a separate Map so we can wait to change the
        // bundle till we're done iterating.
        HashIntMap<TileSet> toUpdate = new HashIntMap<TileSet>();
        while (iditer.hasNext()) {
            int tileSetId = iditer.next().intValue();
            TileSet set = bundle.getTileSet(tileSetId);
            String imagePath = set.getImagePath();

            // sanity checks
            if (imagePath == null) {
                log.warning("Tileset contains no image path " + "[set=" + set + "]. It ain't gonna work.");
                continue;
            }

            // if this is an object tileset, trim it
            if (!keepOriginalPngs && (set instanceof ObjectTileSet)) {
                // set the tileset up with an image provider; we
                // need to do this so that we can trim it!
                set.setImageProvider(improv);

                // we're going to trim it, so adjust the path
                imagePath = adjustImagePath(imagePath);
                jar.putNextEntry(new JarEntry(imagePath));

                try {
                    // create a trimmed object tileset, which will
                    // write the trimmed tileset image to the jar
                    // output stream
                    TrimmedObjectTileSet tset = TrimmedObjectTileSet.trimObjectTileSet((ObjectTileSet) set,
                            jar);
                    tset.setImagePath(imagePath);
                    // replace the original set with the trimmed
                    // tileset in the tileset bundle
                    toUpdate.put(tileSetId, tset);

                } catch (Exception e) {
                    e.printStackTrace(System.err);

                    String msg = "Error adding tileset to bundle " + imagePath + ", " + set.getName() + ": "
                            + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }

            } else {
                // read the image file and convert it to our custom
                // format in the bundle
                File ifile = new File(imageBase, imagePath);
                try {
                    BufferedImage image = ImageIO.read(ifile);
                    if (!keepOriginalPngs && FastImageIO.canWrite(image)) {
                        imagePath = adjustImagePath(imagePath);
                        jar.putNextEntry(new JarEntry(imagePath));
                        set.setImagePath(imagePath);
                        FastImageIO.write(image, jar);
                    } else {
                        jar.putNextEntry(new JarEntry(imagePath));
                        FileInputStream imgin = new FileInputStream(ifile);
                        StreamUtil.copy(imgin, jar);
                    }
                } catch (Exception e) {
                    String msg = "Failure bundling image " + ifile + ": " + e;
                    throw (IOException) new IOException(msg).initCause(e);
                }
            }
        }
        bundle.putAll(toUpdate);

        // now write a serialized representation of the tileset bundle
        // object to the bundle jar file
        JarEntry entry = new JarEntry(BundleUtil.METADATA_PATH);
        jar.putNextEntry(entry);
        ObjectOutputStream oout = new ObjectOutputStream(jar);
        oout.writeObject(bundle);
        oout.flush();

        // finally close up the jar file and call ourself done
        jar.close();

        return true;

    } catch (Exception e) {
        // remove the incomplete jar file and rethrow the exception
        jar.close();
        if (!target.delete()) {
            log.warning("Failed to close botched bundle '" + target + "'.");
        }
        String errmsg = "Failed to create bundle " + target + ": " + e;
        throw (IOException) new IOException(errmsg).initCause(e);
    }
}

From source file:org.codehaus.mojo.jspc.CompileMojo.java

protected void createJarArchive(File archiveFile, File tempJarDir) throws IOException {
    JarOutputStream jos = null;
    try {/*w w w. j  a  va 2 s  .  c om*/
        jos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(archiveFile)), new Manifest());

        int pathLength = tempJarDir.getAbsolutePath().length() + 1;
        Collection<File> files = FileUtils.listFiles(tempJarDir, null, true);
        for (final File file : files) {
            if (!file.isFile()) {
                continue;
            }

            if (getLog().isDebugEnabled()) {
                getLog().debug("file: " + file.getAbsolutePath());
            }

            // Add entry
            String name = file.getAbsolutePath().substring(pathLength);
            // normalize path as the JspCompiler expects '/' as separator
            name = name.replace('\\', '/');
            JarEntry jarFile = new JarEntry(name);
            jos.putNextEntry(jarFile);

            FileUtils.copyFile(file, jos);
        }
    } finally {
        IOUtils.closeQuietly(jos);
    }
}

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

@Override
public void configure(ProjectServiceConfiguration configuration) {

    // Get a reference to our template WAR, and make sure it exists.
    File jenkinsTemplateWar = new File(warTemplateFile);

    if (!jenkinsTemplateWar.exists() || !jenkinsTemplateWar.isFile()) {
        String message = "The given Jenkins template WAR [" + jenkinsTemplateWar
                + "] either did not exist or was not a file!";
        LOG.error(message);//  ww w  . ja v  a  2 s  .co m
        throw new IllegalStateException(message);
    }

    String pathProperty = perOrg ? configuration.getOrganizationIdentifier()
            : configuration.getProjectIdentifier();

    String deployedUrl = configuration.getProperties().get(ProjectServiceConfiguration.PROFILE_BASE_URL)
            + jenkinsPath + pathProperty + "/jenkins/";
    deployedUrl.replace("//", "/");
    URL deployedJenkinsUrl;
    try {
        deployedJenkinsUrl = new URL(deployedUrl);
    } catch (MalformedURLException e) {
        throw new RuntimeException(e);
    }
    String webappName = deployedJenkinsUrl.getPath();
    if (webappName.startsWith("/")) {
        webappName = webappName.substring(1);
    }
    if (webappName.endsWith("/")) {
        webappName = webappName.substring(0, webappName.length() - 1);
    }
    webappName = webappName.replace("/", "#");
    webappName = webappName + ".war";

    // Calculate our final filename.

    String deployLocation = targetWebappsDir + webappName;

    File jenkinsDeployFile = new File(deployLocation);

    if (jenkinsDeployFile.exists()) {
        String message = "When trying to deploy new WARfile [" + jenkinsDeployFile.getAbsolutePath()
                + "] a file or directory with that name already existed! Continuing with provisioning.";
        LOG.info(message);
        return;
    }

    try {
        // Get a reference to our template war
        JarFile jenkinsTemplateWarJar = new JarFile(jenkinsTemplateWar);

        // Extract our web.xml from this war
        JarEntry webXmlEntry = jenkinsTemplateWarJar.getJarEntry(webXmlFilename);
        String webXmlContents = IOUtils.toString(jenkinsTemplateWarJar.getInputStream(webXmlEntry));

        // Update the web.xml to contain the correct JENKINS_HOME value
        String updatedXml = applyDirectoryToWebXml(webXmlContents, configuration);

        File tempDirFile = new File(tempDir);
        if (!tempDirFile.exists()) {
            tempDirFile.mkdirs();
        }

        // Put the web.xml back into the war
        File updatedJenkinsWar = File.createTempFile("jenkins", ".war", tempDirFile);

        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(updatedJenkinsWar),
                jenkinsTemplateWarJar.getManifest());

        // Loop through our existing zipfile and add in all of the entries to it except for our web.xml
        JarEntry curEntry = null;
        Enumeration<JarEntry> entries = jenkinsTemplateWarJar.entries();
        while (entries.hasMoreElements()) {
            curEntry = entries.nextElement();

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

            if (curEntry.getName().equals(webXmlEntry.getName())) {
                JarEntry newEntry = new JarEntry(curEntry.getName());
                jarOutStream.putNextEntry(newEntry);

                // Substitute our edited entry content.
                IOUtils.write(updatedXml, jarOutStream);
            } else {
                jarOutStream.putNextEntry(curEntry);
                IOUtils.copy(jenkinsTemplateWarJar.getInputStream(curEntry), jarOutStream);
            }
        }

        // Clean up our resources.
        jarOutStream.close();

        // Move the war into its deployment location so that it can be picked up and deployed by the app server.
        FileUtils.moveFile(updatedJenkinsWar, jenkinsDeployFile);
    } catch (IOException ioe) {
        // Log this exception and rethrow wrapped in a RuntimeException
        LOG.error(ioe.getMessage());
        throw new RuntimeException(ioe);
    }
}

From source file:kr.motd.maven.exec.ExecMojo.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 classPath List&lt;String> of all classpath elements.
 * @return//w ww.j  a v a 2s. c o  m
 * @throws IOException
 */
private File createJar(List<String> classPath, String mainClass) throws IOException {
    File file = File.createTempFile("maven-exec", ".jar");
    file.deleteOnExit();
    FileOutputStream fos = new FileOutputStream(file);
    JarOutputStream jos = new JarOutputStream(fos);
    jos.setLevel(JarOutputStream.STORED);
    JarEntry je = new JarEntry("META-INF/MANIFEST.MF");
    jos.putNextEntry(je);

    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();
    for (String el : classPath) {
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp.append(new URL(new File(el).toURI().toASCIIString()).toExternalForm() + " ");
    }

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

    man.write(jos);
    jos.close();

    return file;
}