Example usage for java.util.jar JarOutputStream setLevel

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

Introduction

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

Prototype

public void setLevel(int level) 

Source Link

Document

Sets the compression level for subsequent entries which are DEFLATED.

Usage

From source file:JarUtil.java

/**
 * Writes all given files to the specified jar-file.
 * /*from   w  w w  .  ja va 2s .c o m*/
 * @param files
 *            all files that should be added to the JAR file
 * @param sourceDir
 *            The parent directory containing the given files.
 * @param target
 *            The jar file which should be created
 * @param compress
 *            True when the jar file should be compressed
 * @throws FileNotFoundException
 *             when a file could not be found
 * @throws IOException
 *             when a file could not be read or the jar file could not be
 *             written to.
 */
public static void jar(File sourceDir, OutputStream target, boolean compress) throws IOException {
    File[] files = sourceDir.listFiles();
    // creates target-jar-file:
    JarOutputStream out = new JarOutputStream(target);
    if (compress) {
        out.setLevel(ZipOutputStream.DEFLATED);
    } else {
        out.setLevel(ZipOutputStream.STORED);
    }
    // create a CRC32 object:
    CRC32 crc = new CRC32();
    byte[] buffer = new byte[1024 * 1024];
    // add all files:
    int sourceDirLength = sourceDir.getAbsolutePath().length() + 1;
    for (File file : files) {
        addFile(file, out, crc, sourceDirLength, buffer);
    }
    out.close();
}

From source file:JarUtil.java

/**
 * Adds the given file to the specified JAR file.
 * /*from w  w  w . j  av a 2s  .c o m*/
 * @param file
 *            the file that should be added
 * @param jarFile
 *            The JAR to which the file should be added
 * @param parentDir
 *            the parent directory of the file, this is used to calculate
 *            the path witin the JAR file. When null is given, the file will
 *            be added into the root of the JAR.
 * @param compress
 *            True when the jar file should be compressed
 * @throws FileNotFoundException
 *             when the jarFile does not exist
 * @throws IOException
 *             when a file could not be written or the jar-file could not
 *             read.
 */
public static void addToJar(File file, File jarFile, File parentDir, boolean compress)
        throws FileNotFoundException, IOException {
    File tmpJarFile = File.createTempFile("tmp", ".jar", jarFile.getParentFile());
    JarOutputStream out = new JarOutputStream(new FileOutputStream(tmpJarFile));
    if (compress) {
        out.setLevel(ZipOutputStream.DEFLATED);
    } else {
        out.setLevel(ZipOutputStream.STORED);
    }
    // copy contents of old jar to new jar:
    JarFile inputFile = new JarFile(jarFile);
    JarInputStream in = new JarInputStream(new FileInputStream(jarFile));
    CRC32 crc = new CRC32();
    byte[] buffer = new byte[512 * 1024];
    JarEntry entry = (JarEntry) in.getNextEntry();
    while (entry != null) {
        InputStream entryIn = inputFile.getInputStream(entry);
        add(entry, entryIn, out, crc, buffer);
        entryIn.close();
        entry = (JarEntry) in.getNextEntry();
    }
    in.close();
    inputFile.close();

    int sourceDirLength;
    if (parentDir == null) {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1;
    } else {
        sourceDirLength = file.getAbsolutePath().lastIndexOf(File.separatorChar) + 1
                - parentDir.getAbsolutePath().length();
    }
    addFile(file, out, crc, sourceDirLength, buffer);
    out.close();

    // remove old jar file and rename temp file to old one:
    if (jarFile.delete()) {
        if (!tmpJarFile.renameTo(jarFile)) {
            throw new IOException(
                    "Unable to rename temporary JAR file to [" + jarFile.getAbsolutePath() + "].");
        }
    } else {
        throw new IOException("Unable to delete old JAR file [" + jarFile.getAbsolutePath() + "].");
    }

}

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

/**
 * Creates a jar based on the given entries and manifest. This method will
 * always close the given output stream.
 * /* w  w w  .java  2 s.  c  o m*/
 * @param manifest jar manifest
 * @param entries map of resources keyed by the jar entry named
 * @param outputStream output stream for writing the jar
 * @return number of byte written to the jar
 */
public static int createJar(Manifest manifest, Map entries, OutputStream outputStream) throws IOException {
    int writtenBytes = 0;

    // load manifest
    // add it to the jar
    JarOutputStream jarStream = null;

    try {
        // add a jar stream on top
        jarStream = (manifest != null ? new JarOutputStream(outputStream, manifest)
                : new JarOutputStream(outputStream));

        // select fastest level (no compression)
        jarStream.setLevel(Deflater.NO_COMPRESSION);

        // add deps
        for (Iterator iter = entries.entrySet().iterator(); iter.hasNext();) {
            Map.Entry element = (Map.Entry) iter.next();

            String entryName = (String) element.getKey();

            // safety check - all entries must start with /
            if (!entryName.startsWith(SLASH))
                entryName = SLASH + entryName;

            Resource entryValue = (Resource) element.getValue();

            // skip special/duplicate entries (like MANIFEST.MF)
            if (MANIFEST_JAR_LOCATION.equals(entryName)) {
                iter.remove();
            } else {
                // write jar entry
                writtenBytes += JarUtils.writeToJar(entryValue, entryName, jarStream);
            }
        }
    } finally {
        try {
            jarStream.flush();
        } catch (IOException ex) {
            // ignore
        }
        try {
            jarStream.finish();
        } catch (IOException ex) {
            // ignore
        }

    }

    return writtenBytes;
}

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

/**
 * Create a tileset bundle jar file.//from   ww w.j ava2 s .  c  o 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:com.threerings.cast.bundle.tools.MetadataBundlerTask.java

/**
 * Creates the base output stream to which to write our bundle's files.
 *//*from   www .  j av  a2 s  .com*/
protected OutputStream createOutputStream(File target) throws IOException {
    JarOutputStream jout = new JarOutputStream(new FileOutputStream(target));
    jout.setLevel(Deflater.BEST_COMPRESSION);
    return jout;
}

From source file:com.izforge.izpack.compiler.container.provider.JarOutputStreamProvider.java

public JarOutputStream provide(CompilerData compilerData) {
    File file = new File(compilerData.getOutput());
    JarOutputStream jarOutputStream = null;
    FileOutputStream fileOutputStream = null;
    FileUtils.deleteQuietly(file);//from   w ww  .  j  av a  2 s . c  om
    try {
        if (compilerData.isMkdirs()) {
            FileUtils.forceMkdirParent(file);
        }
        fileOutputStream = new FileOutputStream(file);
        jarOutputStream = new JarOutputStream(fileOutputStream);
        int level = compilerData.getComprLevel();
        if (level >= 0 && level < 10) {
            jarOutputStream.setLevel(level);
        } else {
            jarOutputStream.setLevel(Deflater.BEST_COMPRESSION);
        }
    } catch (IOException e) {
        IOUtils.closeQuietly(fileOutputStream);
    }

    return jarOutputStream;
}

From source file:com.googlecode.mycontainer.maven.plugin.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())
 * //w ww.  ja va 2  s . c  o m
 * @param classPath
 *            List&lt;String> of all classpath elements.
 * @return
 * @throws IOException
 */
private File createJar(List 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.
    String cp = "";
    for (Iterator it = classPath.iterator(); it.hasNext();) {
        String el = (String) it.next();
        // NOTE: if File points to a directory, this entry MUST end in '/'.
        cp += UrlUtils.getURL(new File(el)).toExternalForm() + " ";
    }

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

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

    return file;
}

From source file:com.headwire.aem.tooling.intellij.eclipse.stub.JarBuilder.java

public InputStream buildJar(final IFolder sourceDir) throws CoreException {

    ByteArrayOutputStream store = new ByteArrayOutputStream();

    JarOutputStream zos = null;
    InputStream manifestInput = null;
    try {/*  w  w  w  . j  a v  a2s .  c  om*/
        IResource manifestResource = sourceDir.findMember(JarFile.MANIFEST_NAME);
        if (manifestResource == null || manifestResource.getType() != IResource.FILE) {
            throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID,
                    "No file named " + JarFile.MANIFEST_NAME + " found under " + sourceDir));
        }

        manifestInput = ((IFile) manifestResource).getContents();

        Manifest manifest = new Manifest(manifestInput);

        zos = new JarOutputStream(store);
        zos.setLevel(Deflater.NO_COMPRESSION);
        // manifest first
        final ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME);
        zos.putNextEntry(anEntry);
        manifest.write(zos);
        zos.closeEntry();
        zipDir(sourceDir, zos, "");
    } catch (IOException e) {
        throw new CoreException(new Status(IStatus.ERROR, Activator.PLUGIN_ID, e.getMessage(), e));
    } finally {
        IOUtils.closeQuietly(zos);
        IOUtils.closeQuietly(manifestInput);
    }

    return new ByteArrayInputStream(store.toByteArray());
}

From source file:net.hasor.maven.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 w  w  . j av a2 s.  co  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;
}

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// ww w .  jav  a 2  s .  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;
}