Java 类java.util.zip.DeflaterOutputStream 实例源码

项目:itext2    文件:PRStream.java   
/**
 * Creates a new PDF stream object that will replace a stream
 * in a existing PDF file.
 * @param   reader  the reader that holds the existing PDF
 * @param   conts   the new content
 * @param   compressionLevel    the compression level for the content
 * @since   2.1.3 (replacing the existing constructor without param compressionLevel)
 */
public PRStream(PdfReader reader, byte[] conts, int compressionLevel) {
    this.reader = reader;
    this.offset = -1;
    if (Document.compress) {
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Deflater deflater = new Deflater(compressionLevel);
            DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater);
            zip.write(conts);
            zip.close();
            deflater.end();
            bytes = stream.toByteArray();
        }
        catch (IOException ioe) {
            throw new ExceptionConverter(ioe);
        }
        put(PdfName.FILTER, PdfName.FLATEDECODE);
    }
    else
        bytes = conts;
    setLength(bytes.length);
}
项目:FxEditor    文件:CKit.java   
public static String compressString(String s) throws Exception
{
    if(s == null)
    {
        return "";
    }

    ByteArrayOutputStream ba = new ByteArrayOutputStream(s.length() * 2 + 20);
    DeflaterOutputStream out = new DeflaterOutputStream(ba);
    byte[] bytes = s.getBytes(CHARSET_UTF8);
    out.write(bytes);
    out.finish();
    out.flush();

    byte[] compressed = ba.toByteArray();
    return Hex.toHexString(compressed);
}
项目:sstore-soft    文件:ScriptWriterZipped.java   
protected void openFile() {

        try {
            FileAccess           fa  = database.getFileAccess();
            java.io.OutputStream fos = fa.openOutputStreamElement(outFile);

            outDescriptor = fa.getFileSync(fos);
            fileStreamOut = new DeflaterOutputStream(fos,
                    new Deflater(Deflater.DEFAULT_COMPRESSION), bufferSize);
        } catch (IOException e) {
            throw Error.error(ErrorCode.FILE_IO_ERROR,
                              ErrorCode.M_Message_Pair, new Object[] {
                e.toString(), outFile
            });
        }
    }
项目:AndroidSDK2.0    文件:ProtocolParser20.java   
static private byte[] compress(byte[] source) throws IOException
    {
//        ByteArrayInputStream in = new ByteArrayInputStream(source);
//        ByteArrayOutputStream bous = new ByteArrayOutputStream();
//        DeflaterOutputStream out =    new DeflaterOutputStream(bous);
//        byte[] buffer = new byte[1024];
//        int len;
//        while((len = in.read(buffer)) > 0) {
//            out.write(buffer, 0, len);
//        }
//        byte[] ret = bous.toByteArray();
//
//        bous.flush();
//        in.close();
//        out.close();
//        return ret;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        Deflater deflater = new Deflater(Deflater.DEFLATED);
        DeflaterOutputStream deflaterStream = new DeflaterOutputStream(baos, deflater);
        deflaterStream.write(source);
        deflaterStream.finish();

        return baos.toByteArray();
    }
项目:spring-web-jsflow    文件:CompressionCodec.java   
@Override
public OneWayCodec createEncoder() throws Exception {
    return new OneWayCodec() {
        private final Deflater deflater = new Deflater(compressionLevel);

        @Override
        public byte[] code(final byte[] data) throws Exception {
            deflater.reset();
            final ByteArrayOutputStream bout = new ByteArrayOutputStream(data.length / 2);
            try (final DeflaterOutputStream out = new DeflaterOutputStream(bout, deflater)) {
                out.write(data);
            }
            return bout.toByteArray();
        }
    };
}
项目:EatDubbo    文件:BenchmarkRunner.java   
private static byte[] compressDeflate(byte[] data)
{
    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream(500);
        DeflaterOutputStream compresser = new DeflaterOutputStream(bout);
        compresser.write(data, 0, data.length);
        compresser.finish();
        compresser.flush();
        return bout.toByteArray();
    }
    catch (IOException ex) {
        AssertionError ae = new AssertionError("IOException while writing to ByteArrayOutputStream!");
        ae.initCause(ex);
        throw ae;
    }
}
项目:EatDubbo    文件:Bytes.java   
/**
 * zip.
 * 
 * @param bytes source.
 * @return compressed byte array.
 * @throws IOException.
 */
public static byte[] zip(byte[] bytes) throws IOException
{
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    OutputStream os = new DeflaterOutputStream(bos);
    try
    {
        os.write(bytes);
    }
    finally
    {
        os.close();
        bos.close();
    }
    return bos.toByteArray();
}
项目:rocketmq-rocketmq-all-4.1.0-incubating    文件:UtilAll.java   
public static byte[] compress(final byte[] src, final int level) throws IOException {
    byte[] result = src;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
    java.util.zip.Deflater defeater = new java.util.zip.Deflater(level);
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, defeater);
    try {
        deflaterOutputStream.write(src);
        deflaterOutputStream.finish();
        deflaterOutputStream.close();
        result = byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        defeater.end();
        throw e;
    } finally {
        try {
            byteArrayOutputStream.close();
        } catch (IOException ignored) {
        }

        defeater.end();
    }

    return result;
}
项目:cas4.0.x-server-wechat    文件:GoogleAccountsServiceTests.java   
protected static String encodeMessage(final String xmlString) throws IOException {
    byte[] xmlBytes = xmlString.getBytes("UTF-8");
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(
            byteOutputStream);
    deflaterOutputStream.write(xmlBytes, 0, xmlBytes.length);
    deflaterOutputStream.close();

    // next, base64 encode it
    Base64 base64Encoder = new Base64();
    byte[] base64EncodedByteArray = base64Encoder.encode(byteOutputStream
            .toByteArray());
    return new String(base64EncodedByteArray);
}
项目:dubbo2    文件:Bytes.java   
/**
 * zip.
 * 
 * @param bytes source.
 * @return compressed byte array.
 * @throws IOException.
 */
public static byte[] zip(byte[] bytes) throws IOException
{
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    OutputStream os = new DeflaterOutputStream(bos);
    try
    {
        os.write(bytes);
    }
    finally
    {
        os.close();
        bos.close();
    }
    return bos.toByteArray();
}
项目:dubbo2    文件:BenchmarkRunner.java   
private static byte[] compressDeflate(byte[] data)
{
    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream(500);
        DeflaterOutputStream compresser = new DeflaterOutputStream(bout);
        compresser.write(data, 0, data.length);
        compresser.finish();
        compresser.flush();
        return bout.toByteArray();
    }
    catch (IOException ex) {
        AssertionError ae = new AssertionError("IOException while writing to ByteArrayOutputStream!");
        ae.initCause(ex);
        throw ae;
    }
}
项目:CorePatch    文件:DeflateUncompressorTest.java   
@Test
public void testNowrap() throws IOException {
  // Recompress with nowrap set to false.
  Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, false /* nowrap */);
  ByteArrayOutputStream compressedContentBuffer = new ByteArrayOutputStream();
  DeflaterOutputStream deflateOut = new DeflaterOutputStream(compressedContentBuffer, deflater);
  deflateOut.write(CONTENT);
  deflateOut.finish();
  deflateOut.close();
  deflater.end();
  compressedContent = compressedContentBuffer.toByteArray();
  compressedContentIn = new ByteArrayInputStream(compressedContent);

  // Now expect wrapped content in the uncompressor, and uncompressing should "just work".
  uncompressor.setNowrap(false);
  uncompressor.uncompress(compressedContentIn, uncompressedContentOut);
  assertTrue(Arrays.equals(CONTENT, uncompressedContentOut.toByteArray()));
}
项目:letv    文件:j.java   
public static byte[] a(byte[] bArr) {
    if (bArr == null) {
        return null;
    }
    OutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream);
    try {
        deflaterOutputStream.write(bArr, 0, bArr.length);
        deflaterOutputStream.finish();
        deflaterOutputStream.flush();
        deflaterOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    } catch (Exception e) {
        return null;
    }
}
项目:s-store    文件:ScriptWriterZipped.java   
protected void openFile() {

        try {
            FileAccess           fa  = database.getFileAccess();
            java.io.OutputStream fos = fa.openOutputStreamElement(outFile);

            outDescriptor = fa.getFileSync(fos);
            fileStreamOut = new DeflaterOutputStream(fos,
                    new Deflater(Deflater.DEFAULT_COMPRESSION), bufferSize);
        } catch (IOException e) {
            throw Error.error(ErrorCode.FILE_IO_ERROR,
                              ErrorCode.M_Message_Pair, new Object[] {
                e.toString(), outFile
            });
        }
    }
项目:lams    文件:HTTPRedirectDeflateEncoder.java   
/**
 * DEFLATE (RFC1951) compresses the given SAML message.
 * 
 * @param message SAML message
 * 
 * @return DEFLATE compressed message
 * 
 * @throws MessageEncodingException thrown if there is a problem compressing the message
 */
protected String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException {
    log.debug("Deflating and Base64 encoding SAML message");
    try {
        String messageStr = XMLHelper.nodeToString(marshallMessage(message));

        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
        deflaterStream.write(messageStr.getBytes("UTF-8"));
        deflaterStream.finish();

        return Base64.encodeBytes(bytesOut.toByteArray(), Base64.DONT_BREAK_LINES);
    } catch (IOException e) {
        throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e);
    }
}
项目:BHBot    文件:HTTPServer.java   
/**
 * Returns an output stream into which the response body can be written.
 * The stream applies encodings (e.g. compression) according to the sent headers.
 * This method must be called after response headers have been sent
 * that indicate there is a body. Normally, the content should be
 * prepared (not sent) even before the headers are sent, so that any
 * errors during processing can be caught and a proper error response returned -
 * after the headers are sent, it's too late to change the status into an error.
 *
 * @return an output stream into which the response body can be written,
 *         or null if the body should not be written (e.g. it is discarded)
 * @throws IOException if an error occurs
 */
public OutputStream getBody() throws IOException {
    if (encoders[0] != null || discardBody)
        return encoders[0]; // return the existing stream (or null)
    // set up chain of encoding streams according to headers
    List<String> te = Arrays.asList(splitElements(headers.get("Transfer-Encoding"), true));
    List<String> ce = Arrays.asList(splitElements(headers.get("Content-Encoding"), true));
    int i = encoders.length - 1;
    encoders[i] = new FilterOutputStream(out) {
        @Override
        public void close() {} // keep underlying connection stream open for now
        @Override // override the very inefficient default implementation
        public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); }
    };
    if (te.contains("chunked"))
        encoders[--i] = new ChunkedOutputStream(encoders[i + 1]);
    if (ce.contains("gzip") || te.contains("gzip"))
        encoders[--i] = new GZIPOutputStream(encoders[i + 1], 4096);
    else if (ce.contains("deflate") || te.contains("deflate"))
        encoders[--i] = new DeflaterOutputStream(encoders[i + 1]);
    encoders[0] = encoders[i];
    encoders[i] = null; // prevent duplicate reference
    return encoders[0]; // returned stream is always first
}
项目:dubbox-hystrix    文件:BenchmarkRunner.java   
private static byte[] compressDeflate(byte[] data)
{
    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream(500);
        DeflaterOutputStream compresser = new DeflaterOutputStream(bout);
        compresser.write(data, 0, data.length);
        compresser.finish();
        compresser.flush();
        return bout.toByteArray();
    }
    catch (IOException ex) {
        AssertionError ae = new AssertionError("IOException while writing to ByteArrayOutputStream!");
        ae.initCause(ex);
        throw ae;
    }
}
项目:dubbox-hystrix    文件:Bytes.java   
/**
 * zip.
 * 
 * @param bytes source.
 * @return compressed byte array.
 * @throws IOException.
 */
public static byte[] zip(byte[] bytes) throws IOException
{
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    OutputStream os = new DeflaterOutputStream(bos);
    try
    {
        os.write(bytes);
    }
    finally
    {
        os.close();
        bos.close();
    }
    return bos.toByteArray();
}
项目:parabuild-ci    文件:ScriptWriterZipped.java   
protected void openFile() throws HsqlException {

        try {
            FileAccess           fa  = database.getFileAccess();
            java.io.OutputStream fos = fa.openOutputStreamElement(outFile);

            outDescriptor = fa.getFileSync(fos);
            fileStreamOut = new DeflaterOutputStream(fos,
                    new Deflater(Deflater.DEFAULT_COMPRESSION), bufferSize);
        } catch (IOException e) {
            throw Trace.error(Trace.FILE_IO_ERROR, Trace.Message_Pair,
                              new Object[] {
                e.toString(), outFile
            });
        }
    }
项目:parabuild-ci    文件:ScriptWriterZipped.java   
protected void openFile() throws HsqlException {

        try {
            FileAccess           fa  = database.getFileAccess();
            java.io.OutputStream fos = fa.openOutputStreamElement(outFile);

            outDescriptor = fa.getFileSync(fos);
            fileStreamOut = new DeflaterOutputStream(fos,
                    new Deflater(Deflater.DEFAULT_COMPRESSION), bufferSize);
        } catch (IOException e) {
            throw Trace.error(Trace.FILE_IO_ERROR, Trace.Message_Pair,
                              new Object[] {
                e.toString(), outFile
            });
        }
    }
项目:parabuild-ci    文件:ScriptWriterZipped.java   
protected void openFile() throws HsqlException {

        try {
            FileAccess           fa  = database.getFileAccess();
            java.io.OutputStream fos = fa.openOutputStreamElement(outFile);

            outDescriptor = fa.getFileSync(fos);
            fileStreamOut = new DeflaterOutputStream(fos,
                    new Deflater(Deflater.DEFAULT_COMPRESSION), bufferSize);
        } catch (IOException e) {
            throw Trace.error(Trace.FILE_IO_ERROR, Trace.Message_Pair,
                              new Object[] {
                e.toString(), outFile
            });
        }
    }
项目:RakNetty    文件:GameWrapperPacket.java   
@Override
public void write(RakNetByteBuf out) {
    super.write(out);

    RakNetOutputStream os = new RakNetOutputStream(new BufferedOutputStream(new DeflaterOutputStream(new ByteBufOutputStream(out))));
    RakNetByteBuf payload = RakNetByteBuf.buffer();
    body.write(payload);
    try {
        int bodySize = payload.readableBytes();
        byte[] bytes = new byte[bodySize];
        payload.readBytes(bytes);
        os.writeUnsignedVarInt(bodySize);
        os.write(bytes);
    } catch (Exception ignored) {
    } finally {
        payload.release();
    }
}
项目:Much-Assembly-Required    文件:Memory.java   
@Override
public BasicDBObject mongoSerialise() {

    BasicDBObject dbObject = new BasicDBObject();

    try {
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        Deflater compressor = new Deflater(Deflater.BEST_SPEED, true);
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(stream, compressor);
        deflaterOutputStream.write(getBytes());
        deflaterOutputStream.close();
        byte[] compressedBytes = stream.toByteArray();

        dbObject.put("zipBytes", new String(Base64.getEncoder().encode(compressedBytes)));

    } catch (IOException e) {
        e.printStackTrace();
    }

    return dbObject;
}
项目:feeyo-redisproxy    文件:Util.java   
public static byte[] compress(final byte[] src, final int level) {
    byte[] result = src;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
    java.util.zip.Deflater defeater = new java.util.zip.Deflater(level);
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, defeater);
    try {
        deflaterOutputStream.write(src);
        deflaterOutputStream.finish();
        deflaterOutputStream.close();
        result = byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        defeater.end();
        e.printStackTrace();
    } finally {
        try {
            byteArrayOutputStream.close();
        } catch (IOException ignored) {
        }

        defeater.end();
    }

    return result;
}
项目:BiglyBT    文件:IDATChunk.java   
@Override
public byte[] getContentPayload() {
    byte[] payload = new byte[(width+1)*height];
    for(int i = 0; i<height ; i++) {
        int offset = i * (width+1);
        //NO filter on this line
        payload[offset++] = 0;
        for(int j = 0 ; j<width ; j++) {
            payload[offset+j] = (byte)(127);
        }
    }

    Deflater deflater = new Deflater( Deflater.DEFAULT_COMPRESSION );
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream((width+1)*height);

    DeflaterOutputStream compBytes = new DeflaterOutputStream( outBytes, deflater );
    try {
        compBytes.write(payload);
        compBytes.close();
    } catch(Exception e) {
        e.printStackTrace();
    }
    byte[] compPayload = outBytes.toByteArray();

    return compPayload;
}
项目:rmq4note    文件:UtilAll.java   
public static byte[] compress(final byte[] src, final int level) throws IOException {
    byte[] result = src;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
    java.util.zip.Deflater defeater = new java.util.zip.Deflater(level);
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, defeater);
    try {
        deflaterOutputStream.write(src);
        deflaterOutputStream.finish();
        deflaterOutputStream.close();
        result = byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        defeater.end();
        throw e;
    } finally {
        try {
            byteArrayOutputStream.close();
        } catch (IOException ignored) {
        }

        defeater.end();
    }

    return result;
}
项目:zookeeper-sandbox    文件:Bytes.java   
/**
 * zip.
 * 
 * @param bytes source.
 * @return compressed byte array.
 * @throws IOException.
 */
public static byte[] zip(byte[] bytes) throws IOException
{
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    OutputStream os = new DeflaterOutputStream(bos);
    try
    {
        os.write(bytes);
    }
    finally
    {
        os.close();
        bos.close();
    }
    return bos.toByteArray();
}
项目:pac4j-plus    文件:Pac4jHTTPRedirectDeflateEncoder.java   
/**
 * DEFLATE (RFC1951) compresses the given SAML message.
 *
 * @param message SAML message
 *
 * @return DEFLATE compressed message
 *
 * @throws MessageEncodingException thrown if there is a problem compressing the message
 */
protected String deflateAndBase64Encode(SAMLObject message) throws MessageEncodingException {
    log.debug("Deflating and Base64 encoding SAML message");
    try {
        String messageStr = SerializeSupport.nodeToString(marshallMessage(message));

        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
        deflaterStream.write(messageStr.getBytes("UTF-8"));
        deflaterStream.finish();

        return Base64Support.encode(bytesOut.toByteArray(), Base64Support.UNCHUNKED);
    } catch (IOException e) {
        throw new MessageEncodingException("Unable to DEFLATE and Base64 encode SAML message", e);
    }
}
项目:dubbocloud    文件:Bytes.java   
/**
 * zip.
 * 
 * @param bytes source.
 * @return compressed byte array.
 * @throws IOException.
 */
public static byte[] zip(byte[] bytes) throws IOException
{
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    OutputStream os = new DeflaterOutputStream(bos);
    try
    {
        os.write(bytes);
    }
    finally
    {
        os.close();
        bos.close();
    }
    return bos.toByteArray();
}
项目:RLibrary    文件:DeflateCompressor.java   
public static byte[] compress(byte[] input) throws IOException
{
    // Destination where compressed data will be stored.
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Create a compressor.
    Deflater deflater = createDeflater();
    DeflaterOutputStream dos = new DeflaterOutputStream(baos, deflater);

    // Compress the data.
    //
    // Some other implementations such as Jetty and Tyrus use
    // Deflater.deflate(byte[], int, int, int) with Deflate.SYNC_FLUSH,
    // but this implementation does not do it intentionally because the
    // method and the constant value are not available before Java 7.
    dos.write(input, 0, input.length);
    dos.close();

    // Release the resources held by the compressor.
    deflater.end();

    // Retrieve the compressed data.
    return baos.toByteArray();
}
项目:jahhan    文件:Bytes.java   
/**
 * zip.
 * 
 * @param bytes source.
 * @return compressed byte array.
 * @throws IOException.
 */
public static byte[] zip(byte[] bytes) throws IOException
{
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    OutputStream os = new DeflaterOutputStream(bos);
    try
    {
        os.write(bytes);
    }
    finally
    {
        os.close();
        bos.close();
    }
    return bos.toByteArray();
}
项目:itext2    文件:PRStream.java   
/**
 * Sets the data associated with the stream, either compressed or
 * uncompressed. Note that the data will never be compressed if
 * Document.compress is set to false.
 * 
 * @param data raw data, decrypted and uncompressed.
 * @param compress true if you want the stream to be compressed.
 * @param compressionLevel  a value between -1 and 9 (ignored if compress == false)
 * @since   iText 2.1.3
 */
public void setData(byte[] data, boolean compress, int compressionLevel) {
    remove(PdfName.FILTER);
    this.offset = -1;
    if (Document.compress && compress) {
        try {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            Deflater deflater = new Deflater(compressionLevel);
            DeflaterOutputStream zip = new DeflaterOutputStream(stream, deflater);
            zip.write(data);
            zip.close();
            deflater.end();
            bytes = stream.toByteArray();
            this.compressionLevel = compressionLevel;
        }
        catch (IOException ioe) {
            throw new ExceptionConverter(ioe);
        }
        put(PdfName.FILTER, PdfName.FLATEDECODE);
    }
    else
        bytes = data;
    setLength(bytes.length);
}
项目:intellij-ce-playground    文件:RefCountingStorage.java   
private void zipAndWrite(ByteSequence bytes, int record, boolean fixedSize) throws IOException {
  BufferExposingByteArrayOutputStream s = new BufferExposingByteArrayOutputStream();
  DeflaterOutputStream out = new DeflaterOutputStream(s);
  try {
    out.write(bytes.getBytes(), bytes.getOffset(), bytes.getLength());
  }
  finally {
    out.close();
  }

  synchronized (myLock) {
    doWrite(record, fixedSize, s);
    myPendingWriteRequestsSize -= bytes.getLength();
    myPendingWriteRequests.remove(record);
  }
}
项目:Mastering-Mesos    文件:ThriftBinaryCodec.java   
/**
 * Encodes a thrift object into a DEFLATE-compressed binary array.
 *
 * @param tBase Object to encode.
 * @return Deflated, encoded object.
 * @throws CodingException If the object could not be encoded.
 */
public static byte[] deflateNonNull(TBase<?, ?> tBase) throws CodingException {
  requireNonNull(tBase);

  // NOTE: Buffering is needed here for performance.
  // There are actually 2 buffers in play here - the BufferedOutputStream prevents thrift from
  // causing a call to deflate() on every encoded primitive. The DeflaterOutputStream buffer
  // allows the underlying Deflater to operate on a larger chunk at a time without stopping to
  // copy the intermediate compressed output to outBytes.
  // See http://bugs.java.com/bugdatabase/view_bug.do?bug_id=4986239
  ByteArrayOutputStream outBytes = new ByteArrayOutputStream();
  TTransport transport = new TIOStreamTransport(
      new BufferedOutputStream(
          new DeflaterOutputStream(outBytes, new Deflater(DEFLATE_LEVEL), DEFLATER_BUFFER_SIZE),
          DEFLATER_BUFFER_SIZE));
  try {
    TProtocol protocol = PROTOCOL_FACTORY.getProtocol(transport);
    tBase.write(protocol);
    transport.close(); // calls finish() on the underlying stream, completing the compression
    return outBytes.toByteArray();
  } catch (TException e) {
    throw new CodingException("Failed to serialize: " + tBase, e);
  } finally {
    transport.close();
  }
}
项目:mpush    文件:IOUtils.java   
public static byte[] compress(byte[] data) {

        Profiler.enter("time cost on [compress]");

        ByteArrayOutputStream out = new ByteArrayOutputStream(data.length / 4);
        DeflaterOutputStream zipOut = new DeflaterOutputStream(out);
        try {
            zipOut.write(data);
            zipOut.finish();
            zipOut.close();
        } catch (IOException e) {
            LOGGER.error("compress ex", e);
            return Constants.EMPTY_BYTES;
        } finally {
            close(zipOut);
            Profiler.release();
        }
        return out.toByteArray();
    }
项目:dubbos    文件:BenchmarkRunner.java   
private static byte[] compressDeflate(byte[] data)
{
    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream(500);
        DeflaterOutputStream compresser = new DeflaterOutputStream(bout);
        compresser.write(data, 0, data.length);
        compresser.finish();
        compresser.flush();
        return bout.toByteArray();
    }
    catch (IOException ex) {
        AssertionError ae = new AssertionError("IOException while writing to ByteArrayOutputStream!");
        ae.initCause(ex);
        throw ae;
    }
}
项目:dubbos    文件:Bytes.java   
/**
 * zip.
 * 
 * @param bytes source.
 * @return compressed byte array.
 * @throws IOException.
 */
public static byte[] zip(byte[] bytes) throws IOException
{
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    OutputStream os = new DeflaterOutputStream(bos);
    try
    {
        os.write(bytes);
    }
    finally
    {
        os.close();
        bos.close();
    }
    return bos.toByteArray();
}
项目:Head-First-Distributed-Infrastructure    文件:ByteArrayUtil.java   
/**
 * Description 压缩某个字节数组
 *
 * @param src
 * @param level
 * @return
 * @throws IOException
 */
public static byte[] compress(final byte[] src, final int level) throws IOException {
    byte[] result = src;
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(src.length);
    java.util.zip.Deflater defeater = new java.util.zip.Deflater(level);
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, defeater);
    try {
        deflaterOutputStream.write(src);
        deflaterOutputStream.finish();
        deflaterOutputStream.close();
        result = byteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        defeater.end();
        throw e;
    } finally {
        try {
            byteArrayOutputStream.close();
        } catch (IOException ignored) {
        }

        defeater.end();
    }

    return result;
}
项目:dubbo-comments    文件:BenchmarkRunner.java   
private static byte[] compressDeflate(byte[] data)
{
    try {
        ByteArrayOutputStream bout = new ByteArrayOutputStream(500);
        DeflaterOutputStream compresser = new DeflaterOutputStream(bout);
        compresser.write(data, 0, data.length);
        compresser.finish();
        compresser.flush();
        return bout.toByteArray();
    }
    catch (IOException ex) {
        AssertionError ae = new AssertionError("IOException while writing to ByteArrayOutputStream!");
        ae.initCause(ex);
        throw ae;
    }
}
项目:dubbo-comments    文件:Bytes.java   
/**
 * zip.
 * 
 * @param bytes source.
 * @return compressed byte array.
 * @throws IOException.
 */
public static byte[] zip(byte[] bytes) throws IOException
{
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    OutputStream os = new DeflaterOutputStream(bos);
    try
    {
        os.write(bytes);
    }
    finally
    {
        os.close();
        bos.close();
    }
    return bos.toByteArray();
}