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:org.ow2.proactive.utils.ObjectByteConverter.java

/**
 * Convert the given Serializable Object into a byte array.
 * <p>/*from   ww  w  .  j  av a  2s  . com*/
 * The returned byteArray can be compressed by setting compress boolean argument value to <code>true</code>.
 * 
 * @param obj the Serializable object to be compressed
 * @param compress true if the returned byteArray must be also compressed, false if no compression is required.
 * @return a compressed (or not) byteArray representing the Serialization of the given object.
 * @throws IOException if an I/O exception occurs when writing the output byte array
 */
public static final byte[] objectToByteArray(Object obj, boolean compress) throws IOException {
    ByteArrayOutputStream baos = null;
    ObjectOutputStream oos = null;
    if (obj == null) {
        return null;
    }
    try {
        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(baos);
        oos.writeObject(obj);
        oos.flush();
        if (!compress) {
            // Return the UNCOMPRESSED data
            return baos.toByteArray();
        } else {
            // Compressor with highest level of compression
            Deflater compressor = new Deflater();
            compressor.setLevel(Deflater.BEST_COMPRESSION);
            // Give the compressor the data to compress
            compressor.setInput(baos.toByteArray());
            compressor.finish();

            ByteArrayOutputStream bos = null;
            try {
                // Create an expandable byte array to hold the compressed data.
                bos = new ByteArrayOutputStream();
                // Compress the data
                byte[] buf = new byte[512];
                while (!compressor.finished()) {
                    int count = compressor.deflate(buf);
                    bos.write(buf, 0, count);
                }
                // Return the COMPRESSED data
                return bos.toByteArray();
            } finally {
                if (bos != null) {
                    bos.close();
                }
            }
        }
    } finally {
        if (oos != null) {
            oos.close();
        }
        if (baos != null) {
            baos.close();
        }
    }
}

From source file:net.yacy.crawler.data.CacheTest.java

/**
 * Run before each unit test/*ww  w .  j a  va  2s  . c o m*/
 */
@Before
public void setUp() {
    Cache.init(new File(System.getProperty("java.io.tmpdir") + File.separator + "testCache"), "peerSalt",
            Math.max(Math.max(TEXT_CONTENT.getBytes(StandardCharsets.UTF_8).length * 10,
                    Cache.DEFAULT_COMPRESSOR_BUFFER_SIZE * 2), Cache.DEFAULT_BACKEND_BUFFER_SIZE * 2),
            2000, Deflater.BEST_COMPRESSION);
    Cache.clear();
}

From source file:com.alibaba.citrus.service.requestcontext.session.encoder.AbstractSerializationEncoder.java

/** ? */
public String encode(Map<String, Object> attrs, StoreContext storeContext) throws SessionEncoderException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // 1. ?//from  www .  j  a  v  a  2s. co m
    // 2. 
    Deflater def = new Deflater(Deflater.BEST_COMPRESSION, false);
    DeflaterOutputStream dos = new DeflaterOutputStream(baos, def);

    try {
        serializer.serialize(assertNotNull(attrs, "objectToEncode is null"), dos);
    } catch (Exception e) {
        throw new SessionEncoderException("Failed to encode session state", e);
    } finally {
        try {
            dos.close();
        } catch (IOException e) {
        }

        def.end();
    }

    byte[] plaintext = baos.toByteArray().toByteArray();

    // 3. 
    byte[] cryptotext = encrypt(plaintext);

    // 4. base64?
    try {
        String encodedValue = new String(Base64.encodeBase64(cryptotext, false), "ISO-8859-1");

        return URLEncoder.encode(encodedValue, "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        throw new SessionEncoderException("Failed to encode session state", e);
    }
}

From source file:com.oneis.appserver.StaticFileResponse.java

public long getContentLengthGzipped() {
    if (allowCompression) {
        if (uncompressed.length < 4) {
            return NOT_GZIPABLE;
        }/*w  ww. j  a  v  a2 s.  c om*/

        if (compressed == null) {
            try {
                // Compress the file, and cache it so it's only compressed once
                ByteArrayOutputStream c = new ByteArrayOutputStream(uncompressed.length / 2);
                GZIPOutputStreamEx compressor = new GZIPOutputStreamEx(c, uncompressed.length / 2,
                        Deflater.BEST_COMPRESSION);
                compressor.write(uncompressed);
                compressor.close();
                compressed = c.toByteArray();
            } catch (IOException e) {
                System.out.println("Failed to compress static file");
                return NOT_GZIPABLE;
            }
        }

        // If it's smaller uncompressed (taking into account headers to say it's compressed), send it uncompressed
        return ((compressed.length + 20) > uncompressed.length) ? NOT_GZIPABLE : compressed.length;
    }

    return NOT_GZIPABLE;
}

From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.safe.TSafeDeflateJsonQueryHandler.java

public TSafeDeflateJsonQueryHandler(final String compression) {
    fLogger = Logger.getLogger(this.getClass().getName());
    fDebug = (fLogger.getLevel() == Level.FINEST);

    int tmpComp = DEFAULT_COMPRESSION_LEVEL;

    if (WebsockConstants.FASTEST_COMPRESSION.equals(compression)) {
        tmpComp = Deflater.BEST_SPEED;
    } else if (WebsockConstants.BEST_COMPRESSION.equals(compression)) {
        tmpComp = Deflater.BEST_COMPRESSION;
    } else {//w w w.j  av  a2  s. c  o m
        fLogger.log(Level.WARNING, "unknown compression level '" + compression + "'; using default.");
    }

    fCompression = tmpComp;
}

From source file:com.izforge.izpack.installer.unpacker.CompressedFileUnpacker.java

/**
 * Unpacks a pack file.//  w  w  w .j a  va 2 s  .  c om
 *
 * @param file            the pack file meta-data
 * @param packInputStream the pack input stream
 * @param target          the target
 * @throws IOException        for any I/O error
 * @throws InstallerException for any installer exception
 */
@Override
public void unpack(PackFile file, InputStream packInputStream, File target)
        throws IOException, InstallerException {
    File tmpfile = File.createTempFile("izpack-uncompress", null, FileUtils.getTempDirectory());
    OutputStream fo = null;
    InputStream finalStream = null;

    try {
        fo = IOUtils.buffer(FileUtils.openOutputStream(tmpfile));
        IOUtils.copyLarge(packInputStream, fo, 0, file.size());
        fo.flush();
        fo.close();

        InputStream in = IOUtils.buffer(FileUtils.openInputStream(tmpfile));

        if (compressionFormat == PackCompression.DEFLATE) {
            DeflateParameters deflateParameters = new DeflateParameters();
            deflateParameters.setCompressionLevel(Deflater.BEST_COMPRESSION);
            finalStream = new DeflateCompressorInputStream(in, deflateParameters);
        } else {
            finalStream = new CompressorStreamFactory().createCompressorInputStream(compressionFormat.toName(),
                    in);
        }

        copy(file, finalStream, target);
    } catch (CompressorException e) {
        throw new IOException(e);
    } finally {
        IOUtils.closeQuietly(fo);
        IOUtils.closeQuietly(finalStream);
        FileUtils.deleteQuietly(tmpfile);
    }
}

From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.unsafe.DeflateJsonQueryHandler.java

public DeflateJsonQueryHandler(final String compression) {
    fLogger = Logger.getLogger(this.getClass().getName());
    fDebug = (fLogger.getLevel() == Level.FINEST);

    fInflater = new Inflater(true);

    int tmpComp = DEFAULT_COMPRESSION_LEVEL;

    if (WebsockConstants.FASTEST_COMPRESSION.equals(compression)) {
        tmpComp = Deflater.BEST_SPEED;
    } else if (WebsockConstants.BEST_COMPRESSION.equals(compression)) {
        tmpComp = Deflater.BEST_COMPRESSION;
    } else {/*w  w w  . j ava  2  s. c  o m*/
        fLogger.log(Level.WARNING, "unknown compression level '" + compression + "'; using default.");
    }

    fCompression = tmpComp;
}

From source file:org.mycore.services.zipper.MCRZipServlet.java

@Override
protected ZipArchiveOutputStream createContainer(ServletOutputStream sout, String comment) {
    ZipArchiveOutputStream zout = new ZipArchiveOutputStream(new BufferedOutputStream(sout));
    zout.setComment(comment);/*from  ww w  .  ja  v  a 2 s . c  o m*/
    zout.setLevel(Deflater.BEST_COMPRESSION);
    return zout;
}

From source file:spade.storage.CompressedTextFile.java

@Override
public boolean initialize(String arguments) {
    clock = System.currentTimeMillis();
    scaffoldInMemory = new HashMap<Integer, Pair<SortedSet<Integer>, SortedSet<Integer>>>();
    edgesInMemory = 0;//ww  w. java  2 s .  c o m
    hashToID = new HashMap<String, Integer>();
    alreadyRenamed = new Vector<String>();
    compresser = new Deflater(Deflater.BEST_COMPRESSION);
    W = 10;
    L = 5;
    nextVertexID = 0;
    try {
        if (arguments == null) {
            return false;
        }
        annotationsFile = new File(filePath + "/annotations.txt");
        scaffoldFile = new File(filePath + "/scaffold.txt");
        annotationsScanner = new Scanner(annotationsFile);
        scaffoldScanner = new Scanner(scaffoldFile);
        benchmarks = new PrintWriter("/Users/melanie/Documents/benchmarks/compression_time_TextFile.txt",
                "UTF-8");
        filePath = arguments;
        scaffoldWriter = new FileWriter(filePath + "/scaffold.txt", false);
        scaffoldWriter.write("[BEGIN]\n");
        annotationsWriter = new FileWriter(filePath + "/annotations.txt", false);
        annotationsWriter.write("[BEGIN]\n");

        return true;
    } catch (Exception ex) {
        logger.log(Level.SEVERE, "Compressed Storage Initialized not successful!", ex);
        return false;
    }
}

From source file:de.blizzy.backup.Utils.java

public static void zipFile(File source, File target) throws IOException {
    ZipOutputStream out = null;//from  ww  w.  j a v a  2  s.c o m
    try {
        out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(target)));
        out.setLevel(Deflater.BEST_COMPRESSION);

        ZipEntry entry = new ZipEntry(source.getName());
        entry.setTime(source.lastModified());
        out.putNextEntry(entry);

        Files.copy(source.toPath(), out);
    } finally {
        IOUtils.closeQuietly(out);
    }
}