Example usage for java.util.zip Inflater Inflater

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

Introduction

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

Prototype

public Inflater() 

Source Link

Document

Creates a new decompressor.

Usage

From source file:org.getspout.spoutapi.packet.PacketAddonData.java

@Override
public void decompress() {
    if (compressed) {
        Inflater decompressor = new Inflater();
        decompressor.setInput(data);/*from w w  w. j a v  a2  s. com*/

        ByteArrayOutputStream bos = new ByteArrayOutputStream(data.length);

        byte[] buf = new byte[1024];
        while (!decompressor.finished()) {
            try {
                int count = decompressor.inflate(buf);
                bos.write(buf, 0, count);
            } catch (DataFormatException e) {
            }
        }
        try {
            bos.close();
        } catch (IOException e) {
        }

        data = bos.toByteArray();
        compressed = false;
    }
}

From source file:org.ow2.proactive.utils.ObjectByteConverter.java

/**
 * Convert the given byte array into the corresponding object.
 * <p>//from  w w  w. j  av  a2  s.  c o m
 * The given byteArray can be uncompressed if it has been compressed before.
 * 
 * @param input the byteArray to be convert as an object.
 * @param uncompress true if the given byteArray must be also uncompressed, false if no compression was made on it.
 * @return the object corresponding to the given byteArray.
 * @throws IOException if an I/O exception occurs when writing the returned object
 * @throws ClassNotFoundException if class represented by given byteArray is not found.
 */
public static Object byteArrayToObject(byte[] input, boolean uncompress)
        throws IOException, ClassNotFoundException {
    if (input == null) {
        return null;
    }
    if (uncompress) {
        // Uncompress the bytes
        Inflater decompressor = new Inflater();
        decompressor.setInput(input);

        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 (!decompressor.finished()) {
                int count = decompressor.inflate(buf);
                bos.write(buf, 0, count);
            }
            decompressor.end();
            // set the UNCOMPRESSED data
            input = bos.toByteArray();
        } catch (DataFormatException dfe) {
            //convert into io exception to fit previous behavior
            throw new IOException("Compressed data format is invalid : " + dfe.getMessage(), dfe);
        } finally {
            if (bos != null) {
                bos.close();
            }
        }
    }
    //here, input byteArray is uncompressed if needed
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    try {
        bais = new ByteArrayInputStream(input);
        ois = new ObjectInputStream(bais);
        return ois.readObject();
    } finally {
        if (ois != null) {
            ois.close();
        }
        if (bais != null) {
            bais.close();
        }
    }
}

From source file:org.mcxiaoke.commons.http.impl.DeflateDecompressingEntity.java

/**
 * Returns the non-null InputStream that should be returned to by all
 * requests to {@link #getContent()}.//  w  w w  .  java  2  s  . com
 * 
 * @return a non-null InputStream
 * @throws IOException
 *             if there was a problem
 */
@Override
InputStream getDecompressingInputStream(final InputStream wrapped) throws IOException {
    /*
     * A zlib stream will have a header.
     * 
     * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 |
     * 
     * * CMF is one byte.
     * 
     * * FLG is one byte.
     * 
     * * DICTID is four bytes, and only present if FLG.FDICT is set.
     * 
     * Sniff the content. Does it look like a zlib stream, with a CMF, etc?
     * c.f. RFC1950, section 2.2. http://tools.ietf.org/html/rfc1950#page-4
     * 
     * We need to see if it looks like a proper zlib stream, or whether it
     * is just a deflate stream. RFC2616 calls zlib streams deflate.
     * Confusing, isn't it? That's why some servers implement deflate
     * Content-Encoding using deflate streams, rather than zlib streams.
     * 
     * We could start looking at the bytes, but to be honest, someone else
     * has already read the RFCs and implemented that for us. So we'll just
     * use the JDK libraries and exception handling to do this. If that
     * proves slow, then we could potentially change this to check the first
     * byte - does it look like a CMF? What about the second byte - does it
     * look like a FLG, etc.
     */

    /* We read a small buffer to sniff the content. */
    byte[] peeked = new byte[6];

    PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length);

    int headerLength = pushback.read(peeked);

    if (headerLength == -1) {
        throw new IOException("Unable to read the response");
    }

    /* We try to read the first uncompressed byte. */
    byte[] dummy = new byte[1];

    Inflater inf = new Inflater();

    try {
        int n;
        while ((n = inf.inflate(dummy)) == 0) {
            if (inf.finished()) {

                /* Not expecting this, so fail loudly. */
                throw new IOException("Unable to read the response");
            }

            if (inf.needsDictionary()) {

                /*
                 * Need dictionary - then it must be zlib stream with DICTID
                 * part?
                 */
                break;
            }

            if (inf.needsInput()) {
                inf.setInput(peeked);
            }
        }

        if (n == -1) {
            throw new IOException("Unable to read the response");
        }

        /*
         * We read something without a problem, so it's a valid zlib stream.
         * Just need to reset and return an unused InputStream now.
         */
        pushback.unread(peeked, 0, headerLength);
        return new InflaterInputStream(pushback);
    } catch (DataFormatException e) {

        /*
         * Presume that it's an RFC1951 deflate stream rather than RFC1950
         * zlib stream and try again.
         */
        pushback.unread(peeked, 0, headerLength);
        return new InflaterInputStream(pushback, new Inflater(true));
    }
}

From source file:org.fastcatsearch.ir.document.DocumentReader.java

public Document readDocument(int docNo, boolean[] fieldSelectOption, boolean indexable) throws IOException {
    // if(docNo < baseDocNo) throw new
    // IOException("Request docNo cannot less than baseDocNo! docNo = "+docNo+", baseDocNo = "+baseDocNo);

    // baseDocNo?    .
    // docNo -= baseDocNo;

    DataInput bai = null;//from  ww w  . ja  va  2  s .c  o  m

    if (docNo != lastDocNo) {
        long positionOffset = docNo * IOUtil.SIZE_OF_LONG;
        if (positionOffset >= positionLimit) {
            //.
            return null;
        }
        positionInput.seek(positionOffset);
        long pos = positionInput.readLong();
        // find a document block
        docInput.seek(pos);
        int len = docInput.readInt();

        //2014-11-26 ?  working ?   ? ? GC ?? OOM ? ?.
        // Stream  .
        InflaterInputStream decompressInputStream = null;
        inflaterOutput.reset();
        int count = -1;
        try {
            BoundedInputStream boundedInputStream = new BoundedInputStream(docInput, len);
            boundedInputStream.setPropagateClose(false);// docInput  .
            decompressInputStream = new InflaterInputStream(boundedInputStream, new Inflater(), 512);
            while ((count = decompressInputStream.read(workingBuffer)) != -1) {
                inflaterOutput.write(workingBuffer, 0, count);
            }
        } finally {
            decompressInputStream.close();
        }

        BytesRef bytesRef = inflaterOutput.getBytesRef();
        bai = new BytesDataInput(bytesRef.bytes, 0, bytesRef.length);

        lastDocNo = docNo;
        lastBai = bai;
    } else {
        lastBai.reset();
        bai = lastBai;
    }

    Document document = new Document(fields.size());
    for (int i = 0; i < fields.size(); i++) {
        FieldSetting fs = fields.get(i);
        Field f = null;
        boolean hasValue = bai.readBoolean();
        //         logger.debug("read hasValue={}, select={}, fs={} ", hasValue, fieldSelectOption, fs);
        if (hasValue) {
            //1. fieldSelectOption ?  ? ??.
            //2. ? , true? ? ?.
            if (fieldSelectOption == null || (fieldSelectOption != null && fieldSelectOption[i])) {
                f = fs.createEmptyField();
                f.readRawFrom(bai);
            } else {
                bai.skipVIntData();
            }
            //            logger.debug("fill {} >> {}", i, f);
        } else {
            //?  ?   .
            f = fs.createEmptyField();
            //            logger.debug("fill {} >> empty", i);
        }
        if (f != null && indexable) {
            String multiValueDelimiter = fs.getMultiValueDelimiter();
            try {
                f.parseIndexable(multiValueDelimiter);
            } catch (FieldDataParseException e) {
                throw new IOException(e);
            }
        }
        document.set(i, f);
    }

    document.setDocId(docNo + baseDocNo);

    return document;
}

From source file:com.fanfou.app.opensource.http.support.DeflateDecompressingEntity.java

/**
 * Returns the non-null InputStream that should be returned to by all
 * requests to {@link #getContent()}./*from   w  w w  .  j  a  va2s .com*/
 * 
 * @return a non-null InputStream
 * @throws IOException
 *             if there was a problem
 */
@Override
InputStream getDecompressingInputStream(final InputStream wrapped) throws IOException {
    /*
     * A zlib stream will have a header.
     * 
     * CMF | FLG [| DICTID ] | ...compressed data | ADLER32 |
     * 
     * * CMF is one byte.
     * 
     * * FLG is one byte.
     * 
     * * DICTID is four bytes, and only present if FLG.FDICT is set.
     * 
     * Sniff the content. Does it look like a zlib stream, with a CMF, etc?
     * c.f. RFC1950, section 2.2. http://tools.ietf.org/html/rfc1950#page-4
     * 
     * We need to see if it looks like a proper zlib stream, or whether it
     * is just a deflate stream. RFC2616 calls zlib streams deflate.
     * Confusing, isn't it? That's why some servers implement deflate
     * Content-Encoding using deflate streams, rather than zlib streams.
     * 
     * We could start looking at the bytes, but to be honest, someone else
     * has already read the RFCs and implemented that for us. So we'll just
     * use the JDK libraries and exception handling to do this. If that
     * proves slow, then we could potentially change this to check the first
     * byte - does it look like a CMF? What about the second byte - does it
     * look like a FLG, etc.
     */

    /* We read a small buffer to sniff the content. */
    final byte[] peeked = new byte[6];

    final PushbackInputStream pushback = new PushbackInputStream(wrapped, peeked.length);

    final int headerLength = pushback.read(peeked);

    if (headerLength == -1) {
        throw new IOException("Unable to read the response");
    }

    /* We try to read the first uncompressed byte. */
    final byte[] dummy = new byte[1];

    final Inflater inf = new Inflater();

    try {
        int n;
        while ((n = inf.inflate(dummy)) == 0) {
            if (inf.finished()) {

                /* Not expecting this, so fail loudly. */
                throw new IOException("Unable to read the response");
            }

            if (inf.needsDictionary()) {

                /*
                 * Need dictionary - then it must be zlib stream with DICTID
                 * part?
                 */
                break;
            }

            if (inf.needsInput()) {
                inf.setInput(peeked);
            }
        }

        if (n == -1) {
            throw new IOException("Unable to read the response");
        }

        /*
         * We read something without a problem, so it's a valid zlib stream.
         * Just need to reset and return an unused InputStream now.
         */
        pushback.unread(peeked, 0, headerLength);
        return new InflaterInputStream(pushback);
    } catch (final DataFormatException e) {

        /*
         * Presume that it's an RFC1951 deflate stream rather than RFC1950
         * zlib stream and try again.
         */
        pushback.unread(peeked, 0, headerLength);
        return new InflaterInputStream(pushback, new Inflater(true));
    }
}

From source file:org.apache.pdfbox.filter.FlateFilter.java

private ByteArrayOutputStream decompress(InputStream in) throws IOException, DataFormatException {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buf = new byte[2048];
    int read = in.read(buf);
    if (read > 0) {
        Inflater inflater = new Inflater();
        inflater.setInput(buf, 0, read);
        byte[] res = new byte[2048];
        while (true) {
            int resRead = inflater.inflate(res);
            if (resRead != 0) {
                out.write(res, 0, resRead);
                continue;
            }/* w w w. j  a  va  2s.  c o m*/
            if (inflater.finished() || inflater.needsDictionary() || in.available() == 0) {
                break;
            }
            read = in.read(buf);
            inflater.setInput(buf, 0, read);
        }
    }
    out.close();
    return out;
}

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

private static String decompressString(String str) {
    byte[] compressedData = Base64.decode(str);
    // Create the decompressor and give it the data to compress 
    Inflater decompressor = new Inflater();
    decompressor.setInput(compressedData);
    // Create an expandable byte array to hold the decompressed data 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);
    // Decompress the data 
    byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        try {/*from ww w.  ja  v  a  2s . c o  m*/
            int count = decompressor.inflate(buf);
            bos.write(buf, 0, count);
        } catch (DataFormatException e) {
        }
    }

    try {
        bos.close();
    } catch (IOException e) {
    }

    // Get the decompressed data 
    byte[] decompressedData = bos.toByteArray();
    try {
        return new String(decompressedData, "UTF-8");
    } catch (UnsupportedEncodingException e) {
        return new String(decompressedData);
    }
}

From source file:com.itude.mobile.android.util.DataUtil.java

public byte[] decompress(byte[] compressed, int bytesToSkip) {
    Inflater decompressor = new Inflater();
    decompressor.setInput(compressed, bytesToSkip, compressed.length - bytesToSkip);

    // Create an expandable byte array to hold the decompressed data 
    ByteArrayOutputStream bos = new ByteArrayOutputStream(compressed.length);

    // Decompress the data 
    byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        try {//from ww  w . ja  v  a  2 s . c  o  m
            int count = decompressor.inflate(buf);
            bos.write(buf, 0, count);
        } catch (DataFormatException e) {
            decompressor.end();
            return null;
        }
    }
    decompressor.end();
    try {
        if (bos != null)
            bos.close();
    } catch (IOException e) {
        MBLog.w(TAG, "Unable to close stream");
    }

    // Get the decompressed data 
    byte[] decompressedData = bos.toByteArray();
    return decompressedData;
}

From source file:com.asual.lesscss.ResourcePackage.java

private static byte[] inflate(byte[] output) throws DataFormatException, IOException {
    Inflater inflater = new Inflater();
    inflater.setInput(output);/*from  w  w w.  j  a  va  2 s . co  m*/
    ByteArrayOutputStream baos = new ByteArrayOutputStream(output.length);
    byte[] buf = new byte[1024];
    while (!inflater.finished()) {
        int count = inflater.inflate(buf);
        baos.write(buf, 0, count);
    }
    baos.close();
    return baos.toByteArray();
}

From source file:PNGDecoder.java

/**
 * Decodes image from an input stream passed into constructor.
 * @return a BufferedImage object// ww w.  j  a v a2 s .c  o  m
 * @throws IOException
 */
public BufferedImage decode() throws IOException {

    byte[] id = read(12);
    checkEquality(id, new byte[] { -119, 80, 78, 71, 13, 10, 26, 10, 0, 0, 0, 13 });

    byte[] ihdr = read(4);
    checkEquality(ihdr, "IHDR".getBytes());

    int width = readInt();
    int height = readInt();

    BufferedImage result = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

    byte[] head = read(5);
    int mode;
    if (compare(head, new byte[] { 1, 0, 0, 0, 0 })) {
        mode = PNGEncoder.BW_MODE;
    } else if (compare(head, new byte[] { 8, 0, 0, 0, 0 })) {
        mode = PNGEncoder.GREYSCALE_MODE;
    } else if (compare(head, new byte[] { 8, 2, 0, 0, 0 })) {
        mode = PNGEncoder.COLOR_MODE;
    } else {
        throw (new RuntimeException("Format error"));
    }

    readInt();//!!crc

    int size = readInt();

    byte[] idat = read(4);
    checkEquality(idat, "IDAT".getBytes());

    byte[] data = read(size);

    Inflater inflater = new Inflater();
    inflater.setInput(data, 0, size);

    int color;

    try {
        switch (mode) {
        case PNGEncoder.BW_MODE: {
            int bytes = (int) (width / 8);
            if ((width % 8) != 0) {
                bytes++;
            }
            byte colorset;
            byte[] row = new byte[bytes];
            for (int y = 0; y < height; y++) {
                inflater.inflate(new byte[1]);
                inflater.inflate(row);
                for (int x = 0; x < bytes; x++) {
                    colorset = row[x];
                    for (int sh = 0; sh < 8; sh++) {
                        if (x * 8 + sh >= width) {
                            break;
                        }
                        if ((colorset & 0x80) == 0x80) {
                            result.setRGB(x * 8 + sh, y, Color.white.getRGB());
                        } else {
                            result.setRGB(x * 8 + sh, y, Color.black.getRGB());
                        }
                        colorset <<= 1;
                    }
                }
            }
        }
            break;
        case PNGEncoder.GREYSCALE_MODE: {
            byte[] row = new byte[width];
            for (int y = 0; y < height; y++) {
                inflater.inflate(new byte[1]);
                inflater.inflate(row);
                for (int x = 0; x < width; x++) {
                    color = row[x];
                    result.setRGB(x, y, (color << 16) + (color << 8) + color);
                }
            }
        }
            break;
        case PNGEncoder.COLOR_MODE: {
            byte[] row = new byte[width * 3];
            for (int y = 0; y < height; y++) {
                inflater.inflate(new byte[1]);
                inflater.inflate(row);
                for (int x = 0; x < width; x++) {
                    result.setRGB(x, y, ((row[x * 3 + 0] & 0xff) << 16) + ((row[x * 3 + 1] & 0xff) << 8)
                            + ((row[x * 3 + 2] & 0xff)));
                }
            }
        }
        }
    } catch (DataFormatException e) {
        throw (new RuntimeException("ZIP error" + e));
    }

    readInt();//!!crc
    readInt();//0

    byte[] iend = read(4);
    checkEquality(iend, "IEND".getBytes());

    readInt();//!!crc
    in.close();

    return (result);
}