Example usage for java.util.zip Inflater inflate

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

Introduction

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

Prototype

public int inflate(ByteBuffer output) throws DataFormatException 

Source Link

Document

Uncompresses bytes into specified buffer.

Usage

From source file:org.ajax4jsf.resource.ResourceBuilderImpl.java

protected byte[] decrypt(byte[] src) {
    try {//from   w ww .  j  a  v a 2  s. c  o  m
        byte[] zipsrc = codec.decode(src);
        Inflater decompressor = new Inflater();
        byte[] uncompressed = new byte[zipsrc.length * 5];
        decompressor.setInput(zipsrc);
        int totalOut = decompressor.inflate(uncompressed);
        byte[] out = new byte[totalOut];
        System.arraycopy(uncompressed, 0, out, 0, totalOut);
        decompressor.end();
        return out;
    } catch (Exception e) {
        throw new FacesException("Error decode resource data", e);
    }
}

From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java

private ICC_Profile tryToExctractICCProfileFromPNGMetadataNode(Element pngNode) {
    ICC_Profile iccProf = null;//  ww w. j a  v a 2s .  c o m
    Element iccpNode = ImageIOUtil.getChild(pngNode, "iCCP");
    if (iccpNode instanceof IIOMetadataNode) {
        IIOMetadataNode imn = (IIOMetadataNode) iccpNode;
        byte[] prof = (byte[]) imn.getUserObject();
        String comp = imn.getAttribute("compressionMethod");
        if ("deflate".equalsIgnoreCase(comp)) {
            Inflater decompresser = new Inflater();
            decompresser.setInput(prof);
            byte[] result = new byte[100];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            boolean failed = false;
            while (!decompresser.finished() && !failed) {
                try {
                    int resultLength = decompresser.inflate(result);
                    bos.write(result, 0, resultLength);
                    if (resultLength == 0) {
                        // this means more data or an external dictionary is
                        // needed. Both of which are not available, so we
                        // fail.
                        log.debug("Failed to deflate ICC Profile");
                        failed = true;
                    }
                } catch (DataFormatException e) {
                    log.debug("Failed to deflate ICC Profile", e);
                    failed = true;
                }
            }
            decompresser.end();
            try {
                iccProf = ICC_Profile.getInstance(bos.toByteArray());
            } catch (IllegalArgumentException e) {
                log.debug("Failed to interpret embedded ICC Profile", e);
                iccProf = null;
            }
        }
    }
    return iccProf;
}

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 {/* www.ja  va 2s .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:org.apache.hadoop.mapred.TestConcatenatedCompressedInput.java

/**
 * Test using the raw Inflater codec for reading gzip files.
 *//*from w ww  .  j  a  v  a 2 s  .  c  o  m*/
@Test
public void testPrototypeInflaterGzip() throws IOException {
    CompressionCodec gzip = new GzipCodec(); // used only for file extension
    localFs.delete(workDir, true); // localFs = FileSystem instance

    System.out.println(COLOR_BR_BLUE + "testPrototypeInflaterGzip() using "
            + "non-native/Java Inflater and manual gzip header/trailer parsing" + COLOR_NORMAL);

    // copy prebuilt (correct!) version of concat.gz to HDFS
    final String fn = "concat" + gzip.getDefaultExtension();
    Path fnLocal = new Path(System.getProperty("test.concat.data", "/tmp"), fn);
    Path fnHDFS = new Path(workDir, fn);
    localFs.copyFromLocalFile(fnLocal, fnHDFS);

    final FileInputStream in = new FileInputStream(fnLocal.toString());
    assertEquals("concat bytes available", 148, in.available());

    // should wrap all of this header-reading stuff in a running-CRC wrapper
    // (did so in BuiltInGzipDecompressor; see below)

    byte[] compressedBuf = new byte[256];
    int numBytesRead = in.read(compressedBuf, 0, 10);
    assertEquals("header bytes read", 10, numBytesRead);
    assertEquals("1st byte", 0x1f, compressedBuf[0] & 0xff);
    assertEquals("2nd byte", 0x8b, compressedBuf[1] & 0xff);
    assertEquals("3rd byte (compression method)", 8, compressedBuf[2] & 0xff);

    byte flags = (byte) (compressedBuf[3] & 0xff);
    if ((flags & 0x04) != 0) { // FEXTRA
        numBytesRead = in.read(compressedBuf, 0, 2);
        assertEquals("XLEN bytes read", 2, numBytesRead);
        int xlen = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
        in.skip(xlen);
    }
    if ((flags & 0x08) != 0) { // FNAME
        while ((numBytesRead = in.read()) != 0) {
            assertFalse("unexpected end-of-file while reading filename", numBytesRead == -1);
        }
    }
    if ((flags & 0x10) != 0) { // FCOMMENT
        while ((numBytesRead = in.read()) != 0) {
            assertFalse("unexpected end-of-file while reading comment", numBytesRead == -1);
        }
    }
    if ((flags & 0xe0) != 0) { // reserved
        assertTrue("reserved bits are set??", (flags & 0xe0) == 0);
    }
    if ((flags & 0x02) != 0) { // FHCRC
        numBytesRead = in.read(compressedBuf, 0, 2);
        assertEquals("CRC16 bytes read", 2, numBytesRead);
        int crc16 = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
    }

    // ready to go!  next bytes should be start of deflated stream, suitable
    // for Inflater
    numBytesRead = in.read(compressedBuf);

    // Inflater docs refer to a "dummy byte":  no clue what that's about;
    // appears to work fine without one
    byte[] uncompressedBuf = new byte[256];
    Inflater inflater = new Inflater(true);

    inflater.setInput(compressedBuf, 0, numBytesRead);
    try {
        int numBytesUncompressed = inflater.inflate(uncompressedBuf);
        String outString = new String(uncompressedBuf, 0, numBytesUncompressed, "UTF-8");
        System.out.println("uncompressed data of first gzip member = [" + outString + "]");
    } catch (java.util.zip.DataFormatException ex) {
        throw new IOException(ex.getMessage());
    }

    in.close();
}

From source file:de.tudarmstadt.ukp.wikipedia.revisionmachine.difftool.data.codec.RevisionDecoder.java

/**
 * Inflates the zipped input.//  ww w .j  a  v a  2  s.  c  o  m
 * 
 * @param zipinput
 *            zipped input
 * @param start
 *            start position
 * @return inflated input
 */
private byte[] inflateInput(final byte[] zipinput, final int start) {
    ByteArrayOutputStream stream;
    try {
        byte[] compressedInput = zipinput;
        Inflater decompresser = new Inflater();
        decompresser.setInput(compressedInput, start, compressedInput.length - start);

        byte[] output = new byte[1000];
        stream = new ByteArrayOutputStream();

        int cLength;
        do {
            cLength = decompresser.inflate(output);
            stream.write(output, 0, cLength);
        } while (cLength == 1000);

    } catch (DataFormatException e) {
        throw new RuntimeException(e);
    }

    return stream.toByteArray();
}

From source file:org.barcelonamedia.uima.reader.DBXMIReader.DBXMICollectionReader.java

public void getNext(CAS aCAS) throws IOException, CollectionException {

    try {/*from   w w  w.  ja v  a2  s . com*/

        if (this.do_decompression) {

            //Create the decompressor and give it the data to compress
            Inflater decompressor = new Inflater();
            byte[] documentDataByteArray = IOUtils.toByteArray(this.documentData);

            decompressor.setInput(documentDataByteArray);

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

            //Decompress the data
            byte[] buf = new byte[1024];

            while (!decompressor.finished()) {

                try {

                    int count = decompressor.inflate(buf);
                    bos.write(buf, 0, count);
                } catch (DataFormatException e) {

                    System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
                    throw new IOException();
                }
            }

            try {

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

                System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
                throw new IOException();
            }

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

            XmiCasDeserializer.deserialize(new ByteArrayInputStream(decompressedData), aCAS,
                    !this.mFailOnUnknownType);
        } else {

            XmiCasDeserializer.deserialize(this.documentData, aCAS, !this.mFailOnUnknownType);
        }

        this.currentIndex += 1;
    } catch (SAXException e) {

        System.err.println("ERROR in Collection Reader " + e.getClass() + ": " + e.getMessage());
        throw new CollectionException(e);
    }
}

From source file:org.opentestsystem.authoring.testspecbank.service.impl.TestSpecificationServiceImpl.java

private final byte[] decompress(final byte[] testSpecificationXml) {
    final Inflater inflater = new Inflater();
    inflater.setInput(testSpecificationXml);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(testSpecificationXml.length);

    byte[] outBytes = null;

    try {//w  ww  .  java 2s . com
        final byte[] buffer = new byte[BUFFER_SIZE];
        while (!inflater.finished()) {
            final int count = inflater.inflate(buffer);
            baos.write(buffer, 0, count);
        }
        baos.close();
        outBytes = baos.toByteArray();

    } catch (final IOException | DataFormatException e) {
        throw new LocalizedException("testspec.xml.compress.error", e);
    }

    return outBytes;
}

From source file:PNGDecoder.java

/**
 * Decodes image from an input stream passed into constructor.
 * @return a BufferedImage object//  www .java 2s  .  com
 * @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);
}

From source file:net.dv8tion.jda.core.requests.WebSocketClient.java

@Override
public void onBinaryMessage(WebSocket websocket, byte[] binary)
        throws UnsupportedEncodingException, DataFormatException {
    //Thanks to ShadowLordAlpha for code and debugging.
    //Get the compressed message and inflate it
    StringBuilder builder = new StringBuilder();
    Inflater decompresser = new Inflater();
    decompresser.setInput(binary, 0, binary.length);
    byte[] result = new byte[128];
    while (!decompresser.finished()) {
        int resultLength = decompresser.inflate(result);
        builder.append(new String(result, 0, resultLength, "UTF-8"));
    }/*from  ww  w .  ja  v  a  2  s .co m*/
    decompresser.end();

    // send the inflated message to the TextMessage method
    onTextMessage(websocket, builder.toString());
}

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

/**
  * /* w w w  . j a  v a2  s. c  om*/
  * 
  * @param in
  *            ?
  * @return 
  */
 public static String unZip_Str(byte[] in) {
     Inflater decompresser = new Inflater();
     decompresser.setInput(in);
     ArrayList<Byte> al = new ArrayList<Byte>();
     byte[] result;
     int count = 0;
     for (; !decompresser.finished();) {
         result = new byte[100];
         try {
             count += decompresser.inflate(result);
         } catch (DataFormatException e) {
             e.printStackTrace();
         }
         for (int i = 0; i < result.length; i++) {
             al.add(new Byte(result[i]));
         }
     }
     result = new byte[al.size()];
     for (int i = 0; i < al.size(); i++) {
         result[i] = (al.get(i)).byteValue();
     }
     decompresser.end();

     try {
         return new String(result, 0, count, "UTF-8");
     } catch (UnsupportedEncodingException e) {
         return "";
     }
 }