Example usage for java.util.zip Deflater BEST_COMPRESSION

List of usage examples for java.util.zip Deflater BEST_COMPRESSION

Introduction

In this page you can find the example usage for java.util.zip Deflater BEST_COMPRESSION.

Prototype

int BEST_COMPRESSION

To view the source code for java.util.zip Deflater BEST_COMPRESSION.

Click Source Link

Document

Compression level for best compression.

Usage

From source file:de.unidue.inf.is.ezdl.dlcore.utils.StringUtils.java

/**
 * Compresses a string.//from ww w.j  av a2s  .  c o m
 * 
 * @param s
 *            The string to compress
 * @return The compressed string
 */
public static String compress(String s) {
    ByteArrayOutputStream baos = null;
    try {
        byte[] input = s.getBytes("UTF-8");
        Deflater compresser = new Deflater();
        compresser.setLevel(Deflater.BEST_COMPRESSION);
        compresser.setInput(input);
        compresser.finish();
        baos = new ByteArrayOutputStream();
        while (!compresser.finished()) {
            byte[] output = new byte[1024];
            int compressedDataLength = compresser.deflate(output);
            baos.write(output, 0, compressedDataLength);
        }
        baos.flush();
        return Base64.encodeBase64String(baos.toByteArray());

    } catch (UnsupportedEncodingException e) {
        logger.error(e.getMessage(), e);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    } finally {
        ClosingUtils.close(baos);
    }
    return "";
}

From source file:net.rptools.lib.io.PackedFile.java

public void save() throws IOException {
    CodeTimer saveTimer;//from  w  w w  . j  a v  a 2 s . com

    if (!dirty) {
        return;
    }
    saveTimer = new CodeTimer("PackedFile.save");
    saveTimer.setEnabled(log.isDebugEnabled());

    InputStream is = null;

    // Create the new file
    File newFile = new File(tmpDir, new GUID() + ".pak");
    ZipOutputStream zout = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(newFile)));
    zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
    try {
        saveTimer.start(CONTENT_FILE);
        if (hasFile(CONTENT_FILE)) {
            zout.putNextEntry(new ZipEntry(CONTENT_FILE));
            is = getFileAsInputStream(CONTENT_FILE); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop(CONTENT_FILE);

        saveTimer.start(PROPERTY_FILE);
        if (getPropertyMap().isEmpty()) {
            removeFile(PROPERTY_FILE);
        } else {
            zout.putNextEntry(new ZipEntry(PROPERTY_FILE));
            xstream.toXML(getPropertyMap(), zout);
            zout.closeEntry();
        }
        saveTimer.stop(PROPERTY_FILE);

        // Now put each file
        saveTimer.start("addFiles");
        addedFileSet.remove(CONTENT_FILE);
        for (String path : addedFileSet) {
            zout.putNextEntry(new ZipEntry(path));
            is = getFileAsInputStream(path); // When copying, always use an InputStream
            IOUtils.copy(is, zout);
            IOUtils.closeQuietly(is);
            zout.closeEntry();
        }
        saveTimer.stop("addFiles");

        // Copy the rest of the zip entries over
        saveTimer.start("copyFiles");
        if (file.exists()) {
            Enumeration<? extends ZipEntry> entries = zFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                if (!entry.isDirectory() && !addedFileSet.contains(entry.getName())
                        && !removedFileSet.contains(entry.getName()) && !CONTENT_FILE.equals(entry.getName())
                        && !PROPERTY_FILE.equals(entry.getName())) {
                    //                  if (entry.getName().endsWith(".png") ||
                    //                        entry.getName().endsWith(".gif") ||
                    //                        entry.getName().endsWith(".jpeg"))
                    //                     zout.setLevel(Deflater.NO_COMPRESSION); // none needed for images as they are already compressed
                    //                  else
                    //                     zout.setLevel(Deflater.BEST_COMPRESSION); // fast compression
                    zout.putNextEntry(entry);
                    is = getFileAsInputStream(entry.getName()); // When copying, always use an InputStream
                    IOUtils.copy(is, zout);
                    IOUtils.closeQuietly(is);
                    zout.closeEntry();
                } else if (entry.isDirectory()) {
                    zout.putNextEntry(entry);
                    zout.closeEntry();
                }
            }
        }
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        zFile = null;
        saveTimer.stop("copyFiles");

        saveTimer.start("close");
        IOUtils.closeQuietly(zout);
        zout = null;
        saveTimer.stop("close");

        // Backup the original
        saveTimer.start("backup");
        File backupFile = new File(tmpDir, new GUID() + ".mv");
        if (file.exists()) {
            backupFile.delete(); // Always delete the old backup file first; renameTo() is very platform-dependent
            if (!file.renameTo(backupFile)) {
                saveTimer.start("backup file");
                FileUtil.copyFile(file, backupFile);
                file.delete();
                saveTimer.stop("backup file");
            }
        }
        saveTimer.stop("backup");

        saveTimer.start("finalize");
        // Finalize
        if (!newFile.renameTo(file)) {
            saveTimer.start("backup newFile");
            FileUtil.copyFile(newFile, file);
            saveTimer.stop("backup newFile");
        }
        if (backupFile.exists())
            backupFile.delete();
        saveTimer.stop("finalize");

        dirty = false;
    } finally {
        saveTimer.start("cleanup");
        try {
            if (zFile != null)
                zFile.close();
        } catch (IOException e) {
            // ignore close exception
        }
        if (newFile.exists())
            newFile.delete();
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(zout);
        saveTimer.stop("cleanup");

        if (log.isDebugEnabled())
            log.debug(saveTimer);
        saveTimer = null;
    }
}

From source file:org.seasr.meandre.components.tools.io.WriteArchive.java

@Override
public void executeCallBack(ComponentContext cc) throws Exception {
    componentInputCache.storeIfAvailable(cc, IN_LOCATION);
    componentInputCache.storeIfAvailable(cc, IN_FILE_NAME);
    componentInputCache.storeIfAvailable(cc, IN_DATA);

    if (archiveStream == null && componentInputCache.hasData(IN_LOCATION)) {
        Object input = componentInputCache.retrieveNext(IN_LOCATION);
        if (input instanceof StreamDelimiter)
            throw new ComponentExecutionException(
                    String.format("Stream delimiters should not arrive on port '%s'!", IN_LOCATION));

        String location = DataTypeParser.parseAsString(input)[0];
        if (appendExtension)
            location += String.format(".%s", archiveFormat);
        outputFile = getLocation(location, defaultFolder);
        File parentDir = outputFile.getParentFile();

        if (!parentDir.exists()) {
            if (parentDir.mkdirs())
                console.finer("Created directory: " + parentDir);
        } else if (!parentDir.isDirectory())
            throw new IOException(parentDir.toString() + " must be a directory!");

        if (appendTimestamp) {
            String name = outputFile.getName();
            String timestamp = new SimpleDateFormat(timestampFormat).format(new Date());

            int pos = name.lastIndexOf(".");
            if (pos < 0)
                name += "_" + timestamp;
            else/*from w  w  w.j  a v  a 2 s.c o m*/
                name = String.format("%s_%s%s", name.substring(0, pos), timestamp, name.substring(pos));

            outputFile = new File(parentDir, name);
        }

        console.fine(String.format("Writing file %s", outputFile));

        if (archiveFormat.equals("zip")) {
            archiveStream = new ZipArchiveOutputStream(outputFile);
            ((ZipArchiveOutputStream) archiveStream).setLevel(Deflater.BEST_COMPRESSION);
        }

        else

        if (archiveFormat.equals("tar") || archiveFormat.equals("tgz")) {
            OutputStream fileStream = new BufferedOutputStream(new FileOutputStream(outputFile));
            if (archiveFormat.equals("tgz"))
                fileStream = new GzipCompressorOutputStream(fileStream);
            archiveStream = new TarArchiveOutputStream(fileStream);
        }
    }

    // Return if we haven't received a zip or tar location yet
    if (archiveStream == null)
        return;

    while (componentInputCache.hasDataAll(new String[] { IN_FILE_NAME, IN_DATA })) {
        Object inFileName = componentInputCache.retrieveNext(IN_FILE_NAME);
        Object inData = componentInputCache.retrieveNext(IN_DATA);

        // check for StreamInitiator
        if (inFileName instanceof StreamInitiator || inData instanceof StreamInitiator) {
            if (inFileName instanceof StreamInitiator && inData instanceof StreamInitiator) {
                StreamInitiator siFileName = (StreamInitiator) inFileName;
                StreamInitiator siData = (StreamInitiator) inData;

                if (siFileName.getStreamId() != siData.getStreamId())
                    throw new ComponentExecutionException("Unequal stream ids received!!!");

                if (siFileName.getStreamId() == streamId)
                    isStreaming = true;
                else
                    // Forward the delimiter(s)
                    cc.pushDataComponentToOutput(OUT_LOCATION, siFileName);

                continue;
            } else
                throw new ComponentExecutionException("Unbalanced StreamDelimiter received!");
        }

        // check for StreamTerminator
        if (inFileName instanceof StreamTerminator || inData instanceof StreamTerminator) {
            if (inFileName instanceof StreamTerminator && inData instanceof StreamTerminator) {
                StreamTerminator stFileName = (StreamTerminator) inFileName;
                StreamTerminator stData = (StreamTerminator) inData;

                if (stFileName.getStreamId() != stData.getStreamId())
                    throw new ComponentExecutionException("Unequal stream ids received!!!");

                if (stFileName.getStreamId() == streamId) {
                    // end of stream reached
                    closeArchiveAndPushOutput();
                    isStreaming = false;
                    break;
                } else {
                    // Forward the delimiter(s)
                    if (isStreaming)
                        console.warning(
                                "Likely streaming error - received StreamTerminator for a different stream id than the current active stream! - forwarding it");
                    cc.pushDataComponentToOutput(OUT_LOCATION, stFileName);
                    continue;
                }
            } else
                throw new ComponentExecutionException("Unbalanced StreamDelimiter received!");
        }

        byte[] entryData = null;

        if (inData instanceof byte[] || inData instanceof Bytes)
            entryData = DataTypeParser.parseAsByteArray(inData);

        else

        if (inData instanceof Document) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            DOMUtils.writeXML((Document) inData, baos, outputProperties);
            entryData = baos.toByteArray();
        }

        else
            entryData = DataTypeParser.parseAsString(inData)[0].getBytes("UTF-8");

        String entryName = DataTypeParser.parseAsString(inFileName)[0];

        console.fine(String.format("Adding %s entry: %s", archiveFormat.toUpperCase(), entryName));

        ArchiveEntry entry = null;
        if (archiveFormat.equals("zip"))
            entry = new ZipArchiveEntry(entryName);

        else

        if (archiveFormat.equals("tar") || archiveFormat.equals("tgz")) {
            entry = new TarArchiveEntry(entryName);
            ((TarArchiveEntry) entry).setSize(entryData.length);
        }

        archiveStream.putArchiveEntry(entry);
        archiveStream.write(entryData);
        archiveStream.closeArchiveEntry();

        if (!isStreaming) {
            closeArchiveAndPushOutput();
            break;
        }
    }
}

From source file:fr.itldev.koya.alfservice.KoyaContentService.java

/**
 *
 * @param nodeRefs//  ww w. j a  v a2s  .com
 * @return
 * @throws KoyaServiceException
 */
public File zip(List<String> nodeRefs) throws KoyaServiceException {
    File tmpZipFile = null;
    try {
        tmpZipFile = TempFileProvider.createTempFile("tmpDL", ".zip");
        FileOutputStream fos = new FileOutputStream(tmpZipFile);
        CheckedOutputStream checksum = new CheckedOutputStream(fos, new Adler32());
        BufferedOutputStream buff = new BufferedOutputStream(checksum);
        ZipArchiveOutputStream zipStream = new ZipArchiveOutputStream(buff);
        // NOTE: This encoding allows us to workaround bug...
        // http://bugs.sun.com/bugdatabase/view_bug.do;:WuuT?bug_id=4820807
        zipStream.setEncoding("UTF-8");

        zipStream.setMethod(ZipArchiveOutputStream.DEFLATED);
        zipStream.setLevel(Deflater.BEST_COMPRESSION);

        zipStream.setCreateUnicodeExtraFields(ZipArchiveOutputStream.UnicodeExtraFieldPolicy.ALWAYS);
        zipStream.setUseLanguageEncodingFlag(true);
        zipStream.setFallbackToUTF8(true);

        try {
            for (String nodeRef : nodeRefs) {
                addToZip(koyaNodeService.getNodeRef(nodeRef), zipStream, "");
            }
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
            throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
        } finally {
            zipStream.close();
            buff.close();
            checksum.close();
            fos.close();

        }
    } catch (IOException | WebScriptException e) {
        logger.error(e.getMessage(), e);
        throw new WebScriptException(HttpServletResponse.SC_BAD_REQUEST, e.getMessage());
    }

    return tmpZipFile;
}

From source file:com.nary.Debug.java

public static void saveClass(OutputStream _out, Object _class, boolean _compress) throws IOException {
    if (_compress) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream OOS = new ObjectOutputStream(bos);
        OOS.writeObject(_class);

        byte[] dataArray = bos.toByteArray();
        byte[] test = new byte[dataArray.length]; // this is where the byte array gets compressed to
        Deflater def = new Deflater(Deflater.BEST_COMPRESSION);
        def.setInput(dataArray);//from  ww w .j a v a  2s .c  o m
        def.finish();
        def.deflate(test);
        _out.write(test, 0, def.getTotalOut());
    } else {
        ObjectOutputStream OS = new ObjectOutputStream(_out);
        OS.writeObject(_class);
    }
}

From source file:org.apache.tez.common.TezCommonUtils.java

@Private
public static Deflater newBestCompressionDeflater() {
    return new Deflater(Deflater.BEST_COMPRESSION, NO_WRAP);
}

From source file:be.ibridge.kettle.job.entry.zipfile.JobEntryZipFile.java

public Result execute(Result prev_result, int nr, Repository rep, Job parentJob) {
    LogWriter log = LogWriter.getInstance();
    Result result = new Result(nr);
    result.setResult(false);//  w w  w  .  j a v  a 2 s . c  o  m
    boolean Fileexists = false;

    String realZipfilename = StringUtil.environmentSubstitute(zipFilename);
    String realWildcard = StringUtil.environmentSubstitute(wildcard);
    String realWildcardExclude = StringUtil.environmentSubstitute(wildcardexclude);
    String realTargetdirectory = StringUtil.environmentSubstitute(sourcedirectory);
    String realMovetodirectory = StringUtil.environmentSubstitute(movetodirectory);

    if (realZipfilename != null) {
        FileObject fileObject = null;
        try {
            fileObject = KettleVFS.getFileObject(realZipfilename);
            // Check if Zip File exists
            if (fileObject.exists()) {
                Fileexists = true;
                log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileExists1.Label")
                        + realZipfilename + Messages.getString("JobZipFiles.Zip_FileExists2.Label"));
            } else {
                Fileexists = false;
            }

            // Let's start the process now
            if (ifzipfileexists == 3 && Fileexists) {
                // the zip file exists and user want to Fail
                result.setResult(false);
                result.setNrErrors(1);

            } else if (ifzipfileexists == 2 && Fileexists) {
                // the zip file exists and user want to do nothing
                result.setResult(true);

            } else if (afterzip == 2 && realMovetodirectory == null) {
                // After Zip, Move files..User must give a destination Folder
                result.setResult(false);
                result.setNrErrors(1);
                log.logError(toString(),
                        Messages.getString("JobZipFiles.AfterZip_No_DestinationFolder_Defined.Label"));

            } else
            // After Zip, Move files..User must give a destination Folder
            {

                if (ifzipfileexists == 0 && Fileexists) {

                    // the zip file exists and user want to create new one with unique name
                    //Format Date

                    DateFormat dateFormat = new SimpleDateFormat("hhmmss_mmddyyyy");
                    realZipfilename = realZipfilename + "_" + dateFormat.format(new Date()) + ".zip";
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileNameChange1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileNameChange1.Label"));

                } else if (ifzipfileexists == 1 && Fileexists) {
                    log.logDebug(toString(), Messages.getString("JobZipFiles.Zip_FileAppend1.Label")
                            + realZipfilename + Messages.getString("JobZipFiles.Zip_FileAppend2.Label"));
                }

                // Get all the files in the directory...

                File f = new File(realTargetdirectory);

                String[] filelist = f.list();

                log.logDetailed(toString(),
                        Messages.getString("JobZipFiles.Files_Found1.Label") + filelist.length
                                + Messages.getString("JobZipFiles.Files_Found2.Label") + realTargetdirectory
                                + Messages.getString("JobZipFiles.Files_Found3.Label"));

                Pattern pattern = null;
                if (!Const.isEmpty(realWildcard)) {
                    pattern = Pattern.compile(realWildcard);

                }
                Pattern patternexclude = null;
                if (!Const.isEmpty(realWildcardExclude)) {
                    patternexclude = Pattern.compile(realWildcardExclude);

                }

                // Prepare Zip File
                byte[] buffer = new byte[18024];

                FileOutputStream dest = new FileOutputStream(realZipfilename);
                BufferedOutputStream buff = new BufferedOutputStream(dest);
                ZipOutputStream out = new ZipOutputStream(buff);

                // Set the method
                out.setMethod(ZipOutputStream.DEFLATED);

                // Set the compression level
                if (compressionrate == 0) {
                    out.setLevel(Deflater.NO_COMPRESSION);
                } else if (compressionrate == 1) {
                    out.setLevel(Deflater.DEFAULT_COMPRESSION);
                }
                if (compressionrate == 2) {
                    out.setLevel(Deflater.BEST_COMPRESSION);
                }
                if (compressionrate == 3) {
                    out.setLevel(Deflater.BEST_SPEED);
                }

                // Specify Zipped files (After that we will move,delete them...)
                String[] ZippedFiles = new String[filelist.length];
                int FileNum = 0;

                // Get the files in the list...
                for (int i = 0; i < filelist.length && !parentJob.isStopped(); i++) {
                    boolean getIt = true;
                    boolean getItexclude = false;

                    // First see if the file matches the regular expression!
                    if (pattern != null) {
                        Matcher matcher = pattern.matcher(filelist[i]);
                        getIt = matcher.matches();
                    }

                    if (patternexclude != null) {
                        Matcher matcherexclude = patternexclude.matcher(filelist[i]);
                        getItexclude = matcherexclude.matches();
                    }

                    // Get processing File
                    String targetFilename = realTargetdirectory + Const.FILE_SEPARATOR + filelist[i];
                    File file = new File(targetFilename);

                    if (getIt && !getItexclude && !file.isDirectory()) {

                        // We can add the file to the Zip Archive

                        log.logDebug(toString(),
                                Messages.getString("JobZipFiles.Add_FilesToZip1.Label") + filelist[i]
                                        + Messages.getString("JobZipFiles.Add_FilesToZip2.Label")
                                        + realTargetdirectory
                                        + Messages.getString("JobZipFiles.Add_FilesToZip3.Label"));

                        // Associate a file input stream for the current file
                        FileInputStream in = new FileInputStream(targetFilename);

                        // Add ZIP entry to output stream.
                        out.putNextEntry(new ZipEntry(filelist[i]));

                        int len;
                        while ((len = in.read(buffer)) > 0) {
                            out.write(buffer, 0, len);
                        }

                        out.closeEntry();

                        // Close the current file input stream
                        in.close();

                        // Get Zipped File
                        ZippedFiles[FileNum] = filelist[i];
                        FileNum = FileNum + 1;
                    }
                }

                // Close the ZipOutPutStream
                out.close();

                //-----Get the list of Zipped Files and Move or Delete Them
                if (afterzip == 1 || afterzip == 2) {
                    // iterate through the array of Zipped files
                    for (int i = 0; i < ZippedFiles.length; i++) {
                        if (ZippedFiles[i] != null) {
                            // Delete File
                            FileObject fileObjectd = KettleVFS
                                    .getFileObject(realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);

                            // Here we can move, delete files
                            if (afterzip == 1) {
                                // Delete File
                                boolean deleted = fileObjectd.delete();
                                if (!deleted) {
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Delete_File1.Label")
                                                    + realTargetdirectory + Const.FILE_SEPARATOR
                                                    + ZippedFiles[i] + Messages
                                                            .getString("JobZipFiles.Cant_Delete_File2.Label"));

                                }
                                // File deleted
                                log.logDebug(toString(),
                                        Messages.getString("JobZipFiles.File_Deleted1.Label")
                                                + realTargetdirectory + Const.FILE_SEPARATOR + ZippedFiles[i]
                                                + Messages.getString("JobZipFiles.File_Deleted2.Label"));
                            } else if (afterzip == 2) {
                                // Move File   
                                try {
                                    FileObject fileObjectm = KettleVFS.getFileObject(
                                            realMovetodirectory + Const.FILE_SEPARATOR + ZippedFiles[i]);
                                    fileObjectd.moveTo(fileObjectm);
                                } catch (IOException e) {
                                    log.logError(toString(),
                                            Messages.getString("JobZipFiles.Cant_Move_File1.Label")
                                                    + ZippedFiles[i]
                                                    + Messages.getString("JobZipFiles.Cant_Move_File2.Label")
                                                    + e.getMessage());
                                    result.setResult(false);
                                    result.setNrErrors(1);
                                }
                                // File moved
                                log.logDebug(toString(), Messages.getString("JobZipFiles.File_Moved1.Label")
                                        + ZippedFiles[i] + Messages.getString("JobZipFiles.File_Moved2.Label"));
                            }
                        }
                    }
                }
                result.setResult(true);
            }
        } catch (IOException e) {
            log.logError(toString(),
                    Messages.getString("JobZipFiles.Cant_CreateZipFile1.Label") + realZipfilename
                            + Messages.getString("JobZipFiles.Cant_CreateZipFile2.Label") + e.getMessage());
            result.setResult(false);
            result.setNrErrors(1);
        } finally {
            if (fileObject != null) {
                try {
                    fileObject.close();
                } catch (IOException ex) {
                }
                ;
            }
        }
    } else {
        result.setResult(false);
        result.setNrErrors(1);
        log.logError(toString(), Messages.getString("JobZipFiles.No_ZipFile_Defined.Label"));
    }

    return result;
}

From source file:org.apache.sling.osgi.obr.Repository.java

File spoolModified(InputStream ins) throws IOException {
    JarInputStream jis = new JarInputStream(ins);

    // immediately handle the manifest
    JarOutputStream jos;//  w  w  w  .  ja  v  a 2s  .  c o  m
    Manifest manifest = jis.getManifest();
    if (manifest == null) {
        throw new IOException("Missing Manifest !");
    }

    String symbolicName = manifest.getMainAttributes().getValue("Bundle-SymbolicName");
    if (symbolicName == null || symbolicName.length() == 0) {
        throw new IOException("Missing Symbolic Name in Manifest !");
    }

    String version = manifest.getMainAttributes().getValue("Bundle-Version");
    Version v = Version.parseVersion(version);
    if (v.getQualifier().indexOf("SNAPSHOT") >= 0) {
        String tStamp;
        synchronized (DATE_FORMAT) {
            tStamp = DATE_FORMAT.format(new Date());
        }
        version = v.getMajor() + "." + v.getMinor() + "." + v.getMicro() + "."
                + v.getQualifier().replaceAll("SNAPSHOT", tStamp);
        manifest.getMainAttributes().putValue("Bundle-Version", version);
    }

    File bundle = new File(this.repoLocation, symbolicName + "-" + v + ".jar");
    OutputStream out = null;
    try {
        out = new FileOutputStream(bundle);
        jos = new JarOutputStream(out, manifest);

        jos.setMethod(JarOutputStream.DEFLATED);
        jos.setLevel(Deflater.BEST_COMPRESSION);

        JarEntry entryIn = jis.getNextJarEntry();
        while (entryIn != null) {
            JarEntry entryOut = new JarEntry(entryIn.getName());
            entryOut.setTime(entryIn.getTime());
            entryOut.setComment(entryIn.getComment());
            jos.putNextEntry(entryOut);
            if (!entryIn.isDirectory()) {
                spool(jis, jos);
            }
            jos.closeEntry();
            jis.closeEntry();
            entryIn = jis.getNextJarEntry();
        }

        // close the JAR file now to force writing
        jos.close();

    } finally {
        IOUtils.closeQuietly(out);
    }

    return bundle;
}

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 .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.android.server.wifi.WifiLogger.java

private static String compressToBase64(byte[] input) {
    String result;//from   w  w w  .j  a  v  a2  s  .c o m
    //compress
    Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);
    compressor.setInput(input);
    compressor.finish();
    ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
    final byte[] buf = new byte[1024];

    while (!compressor.finished()) {
        int count = compressor.deflate(buf);
        bos.write(buf, 0, count);
    }

    try {
        compressor.end();
        bos.close();
    } catch (IOException e) {
        Log.e(TAG, "ByteArrayOutputStream close error");
        result = android.util.Base64.encodeToString(input, Base64.DEFAULT);
        return result;
    }

    byte[] compressed = bos.toByteArray();
    if (DBG) {
        Log.d(TAG, " length is:" + (compressed == null ? "0" : compressed.length));
    }

    //encode
    result = android.util.Base64.encodeToString(compressed.length < input.length ? compressed : input,
            Base64.DEFAULT);

    if (DBG) {
        Log.d(TAG, "FwMemoryDump length is :" + result.length());
    }

    return result;
}