Example usage for java.util.zip Deflater Deflater

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

Introduction

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

Prototype

public Deflater() 

Source Link

Document

Creates a new compressor with the default compression level.

Usage

From source file:se.kth.infosys.lumberjack.protocol.LumberjackClient.java

public int sendCompressedFrame(List<Map<String, byte[]>> keyValuesList) throws IOException {
    output.writeByte(PROTOCOL_VERSION);//from  w  w  w . j  a  va2  s  .c om
    output.writeByte(FRAME_COMPRESSED);

    ByteArrayOutputStream uncompressedBytes = new ByteArrayOutputStream();
    DataOutputStream uncompressedOutput = new DataOutputStream(uncompressedBytes);
    for (Map<String, byte[]> keyValues : keyValuesList) {
        logger.trace("Adding data frame");
        sendDataFrame(uncompressedOutput, keyValues);
    }
    uncompressedOutput.close();
    Deflater compressor = new Deflater();
    byte[] uncompressedData = uncompressedBytes.toByteArray();
    logger.trace("Deflating data: {} bytes", uncompressedData.length);
    if (logger.isTraceEnabled()) {
        HexDump.dump(uncompressedData, 0, System.out, 0);
    }
    compressor.setInput(uncompressedData);
    compressor.finish();

    ByteArrayOutputStream compressedBytes = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    while (!compressor.finished()) {
        int count = compressor.deflate(buffer);
        compressedBytes.write(buffer, 0, count);
    }
    compressedBytes.close();
    byte[] compressedData = compressedBytes.toByteArray();
    logger.trace("Deflated data: {} bytes", compressor.getTotalOut());
    if (logger.isTraceEnabled()) {
        HexDump.dump(compressedData, 0, System.out, 0);
    }

    output.writeInt(compressor.getTotalOut());
    output.write(compressedData);
    output.flush();

    logger.trace("Sending compressed frame: {} frames", keyValuesList.size());
    return 6 + compressor.getTotalOut();
}

From source file:net.fenyo.mail4hotspot.dns.Msg.java

private byte[] process(final AdvancedServices advancedServices, final Inet4Address address)
        throws GeneralException {
    // log.debug("processing message of type " + input_buffer[0]);
    // for (byte b : input_buffer) log.debug("received byte: [" + b + "]");

    if (input_buffer.length == 0)
        throw new GeneralException("invalid size");
    if (input_buffer[0] == 0) {
        // UTF-8 message type

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer.length - 1);
        bb.put(input_buffer, 1, input_buffer.length - 1);
        bb.position(0);//from w  w w  . j  av a 2 s.  c  o m
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        // log.debug("RECEIVED query: [" + query + "]");

        final String reply = advancedServices.processQueryFromClient(query, address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill output_buffer
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply);
        ob.get(output_buffer = new byte[ob.limit()]);

        output_size = output_buffer.length;

    } else {
        // binary message type
        // log.debug("processing binary message");

        final ByteBuffer bb = ByteBuffer.allocate(input_buffer[0]);
        bb.put(input_buffer, 1, input_buffer[0]);
        bb.position(0);
        final String query = Charset.forName("UTF-8").decode(bb).toString();
        //      log.debug("RECEIVED query: [" + query + "]");

        final BinaryMessageReply reply = advancedServices.processBinaryQueryFromClient(query,
                Arrays.copyOfRange(input_buffer, input_buffer[0] + 1, input_buffer.length), address);

        // this buffer may not be backed by an accessible byte array, so we do not use Charset.forName("UTF-8").encode(reply).array() to fill string_part
        final ByteBuffer ob = Charset.forName("UTF-8").encode(reply.reply_string);
        final byte[] string_part = new byte[ob.limit()];
        ob.get(string_part);

        if (string_part.length > 255)
            throw new GeneralException("string_part too long");
        output_buffer = new byte[string_part.length + reply.reply_data.length + 1];
        output_buffer[0] = (byte) string_part.length;
        for (int i = 0; i < string_part.length; i++)
            output_buffer[i + 1] = string_part[i];
        for (int i = 0; i < reply.reply_data.length; i++)
            output_buffer[string_part.length + i + 1] = reply.reply_data[i];
        output_size = output_buffer.length;
    }

    synchronized (compressed) {
        // http://docs.oracle.com/javase/7/docs/api/java/util/zip/Deflater.html#deflate(byte[])
        // log.debug("processing binary message: length before compressing: " + output_buffer.length);
        final Deflater compresser = new Deflater();
        compresser.setInput(output_buffer);
        compresser.finish();
        final int nbytes = compresser.deflate(compressed);
        //         log.debug("RET: " + nbytes);
        //         log.debug("COMPRESSED: " + compressed.length);
        // log.debug("processing binary message: length after compressing: " + nbytes);
        if (compressed.length == nbytes) {
            log.error("compressed buffer too small...");
            throw new GeneralException("compressed buffer too small...");
        }
        output_buffer = Arrays.copyOf(compressed, nbytes);
        output_size = output_buffer.length;
    }

    synchronized (is_processed) {
        is_processed = true;
    }

    return new byte[] { 'E', 0 }; // 'E'rror 0 == OK
}

From source file:com.newrelic.agent.android.harvest.HarvestConnection.java

private byte[] deflate(String str) {
    Deflater deflater = new Deflater();
    deflater.setInput(str.getBytes());/*from  ww  w .j a va  2  s . c o  m*/
    deflater.finish();
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    byte[] bArr = new byte[AccessibilityNodeInfoCompat.ACTION_SCROLL_BACKWARD];
    while (!deflater.finished()) {
        int deflate = deflater.deflate(bArr);
        if (deflate <= 0) {
            this.log.error("HTTP request contains an incomplete payload");
        }
        byteArrayOutputStream.write(bArr, 0, deflate);
    }
    deflater.end();
    return byteArrayOutputStream.toByteArray();
}

From source file:com.kactech.otj.Utils.java

public static byte[] zlibCompress(byte[] data) {
    Deflater deflater = new Deflater();
    deflater.setInput(data);/* w  ww  .  j  a va2s .  c o m*/

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);

    deflater.finish();
    byte[] buffer = new byte[1024];
    while (!deflater.finished()) {
        int count = deflater.deflate(buffer);
        outputStream.write(buffer, 0, count);
    }
    try {
        outputStream.close();
    } catch (IOException e) {
        // don't be silly
        throw new RuntimeException(e);
    }
    return outputStream.toByteArray();
}

From source file:edu.stanford.junction.addon.JSONObjWrapper.java

private static String compressString(String str) {
    byte[] input;
    try {/*from   ww w  .ja v a2s.  com*/
        input = str.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
        input = str.getBytes();
    }
    // Create the compressor with highest level of compression 
    Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);
    // Give the compressor the data to compress 
    compressor.setInput(input);
    compressor.finish();

    // Create an expandable byte array to hold the compressed data. 
    // You cannot use an array that's the same size as the orginal because 
    // there is no guarantee that the compressed data will be smaller than 
    // the uncompressed data. 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(input.length);
    // Compress the data 
    byte[] buf = new byte[1024];
    while (!compressor.finished()) {
        int count = compressor.deflate(buf);
        bos.write(buf, 0, count);
    }
    try {
        bos.close();
    } catch (IOException e) {
    }
    // Get the compressed data 
    byte[] compressedData = bos.toByteArray();
    return Base64.encodeBytes(compressedData);
}

From source file:com.eryansky.common.utils.SysUtils.java

/**
  * /*from w w w.  j  a  v a  2 s . c  o m*/
  * 
  * @param in_str
  *            
  * @return ?
  */
 public static byte[] zip_Str(String in_str) {
     byte[] input = new byte[0];
     try {
         input = in_str.getBytes("UTF-8");
     } catch (UnsupportedEncodingException e) {
         e.printStackTrace();
     }
     ArrayList<Byte> al = new ArrayList<Byte>();

     byte[] output;
     Deflater compresser = new Deflater();
     compresser.setInput(input);
     compresser.finish();
     for (; !compresser.finished();) {
         output = new byte[100];
         compresser.deflate(output);
         for (int i = 0; i < output.length; i++) {
             al.add(new Byte(output[i]));
         }
     }
     output = new byte[al.size()];
     for (int i = 0; i < al.size(); i++) {
         output[i] = (al.get(i)).byteValue();
     }
     return output;
 }

From source file:acp.sdk.SecureUtil.java

/**
 * ./*w ww.  ja va 2 s . c o  m*/
 * 
 * @param inputByte
 *            ?byte[]
 * @return ??
 * @throws IOException
 */
public static byte[] deflater(final byte[] inputByte) throws IOException {
    int compressedDataLength = 0;
    Deflater compresser = new Deflater();
    compresser.setInput(inputByte);
    compresser.finish();
    ByteArrayOutputStream o = new ByteArrayOutputStream(inputByte.length);
    byte[] result = new byte[1024];
    try {
        while (!compresser.finished()) {
            compressedDataLength = compresser.deflate(result);
            o.write(result, 0, compressedDataLength);
        }
    } finally {
        o.close();
    }
    compresser.end();
    return o.toByteArray();
}

From source file:com.bigdata.dastor.utils.FBUtilities.java

public static void compressToStream(byte[] input, ByteArrayOutputStream bos) throws IOException {
    // Create the compressor with highest level of compression
    Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);

    // Give the compressor the data to compress
    compressor.setInput(input);/* w  w w. j ava 2  s .c o m*/
    compressor.finish();

    // Write the compressed data to the stream
    byte[] buf = new byte[1024];
    while (!compressor.finished()) {
        int count = compressor.deflate(buf);
        bos.write(buf, 0, count);
    }
}

From source file:gov.niem.ws.util.SecurityUtil.java

/**
 * Encode data with DEFLATE and then Base64 without chunking, so it can
 * safely be placed in an HTTP header./* w  w  w . j a  v  a  2  s .c o m*/
 * 
 * @param data
 * @return the compressed, b64 encoded data
 * @throws DataFormatException
 */
public static String encodeHeader(byte[] data) throws DataFormatException {
    // TODO: length limit on encoded?      
    ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
    Deflater deflater = new Deflater();
    deflater.setInput(data);
    deflater.finish();
    byte[] buffer = new byte[1024];
    while (!deflater.finished()) {
        int count = deflater.deflate(buffer);
        if (count == 0)
            break;
        out.write(buffer, 0, count);
    }

    try {
        deflater.end();
        out.close();
    } catch (IOException e) {
    }

    return new String(Base64.encodeBase64(out.toByteArray(), false));
}

From source file:de.triology.cas.logout.LogoutUriEnabledLogoutManagerImpl.java

/**
 * Create a logout message for front channel logout.
 *
 * @param logoutRequest the logout request.
 * @return a front SAML logout message.//from  w  w  w  .ja  v a 2  s .c  o m
 */
public String createFrontChannelLogoutMessage(final LogoutRequest logoutRequest) {
    final String logoutMessage = this.logoutMessageBuilder.create(logoutRequest);
    final Deflater deflater = new Deflater();
    deflater.setInput(logoutMessage.getBytes(ASCII));
    deflater.finish();
    final byte[] buffer = new byte[logoutMessage.length()];
    final int resultSize = deflater.deflate(buffer);
    final byte[] output = new byte[resultSize];
    System.arraycopy(buffer, 0, output, 0, resultSize);
    return Base64.encodeBase64String(output);
}