java.util.zip.Inflater

Here are the examples of the java api class java.util.zip.Inflater taken from open source projects.

1. FrontChannelLogoutActionTests#verifyLogoutOneLogoutRequestNotAttempted()

View license
@Test
public void verifyLogoutOneLogoutRequestNotAttempted() throws Exception {
    final LogoutRequest logoutRequest = new DefaultLogoutRequest(TICKET_ID, new SimpleWebApplicationServiceImpl(TEST_URL), new URL(TEST_URL));
    final Event event = getLogoutEvent(Arrays.asList(logoutRequest));
    assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
    final List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, list.size());
    final String url = (String) event.getAttributes().get(FrontChannelLogoutAction.DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL);
    assertTrue(url.startsWith(TEST_URL + "?" + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + "="));
    final byte[] samlMessage = CompressionUtils.decodeBase64ToByteArray(URLDecoder.decode(StringUtils.substringAfter(url, "?" + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + "="), "UTF-8"));
    final Inflater decompresser = new Inflater();
    decompresser.setInput(samlMessage);
    final byte[] result = new byte[1000];
    decompresser.inflate(result);
    decompresser.end();
    final String message = new String(result);
    assertTrue(message.startsWith("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""));
    assertTrue(message.contains("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>"));
}

2. DeflateCompressor#uncompress()

View license
public int uncompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset) throws IOException {
    Inflater inf = inflater.get();
    inf.reset();
    inf.setInput(input, inputOffset, inputLength);
    if (inf.needsInput())
        return 0;
    // We assume output is big enough
    try {
        return inf.inflate(output, outputOffset, output.length - outputOffset);
    } catch (DataFormatException e) {
        throw new IOException(e);
    }
}

3. CompressDeflate#expand()

Project: ThriftyPaxos
Source File: CompressDeflate.java
View license
@Override
public void expand(byte[] in, int inPos, int inLen, byte[] out, int outPos, int outLen) {
    Inflater decompresser = new Inflater();
    decompresser.setInput(in, inPos, inLen);
    decompresser.finished();
    try {
        int len = decompresser.inflate(out, outPos, outLen);
        if (len != outLen) {
            throw new DataFormatException(len + " " + outLen);
        }
    } catch (DataFormatException e) {
        throw DbException.get(ErrorCode.COMPRESSION_ERROR, e);
    }
    decompresser.end();
}

4. FrontChannelLogoutActionTests#verifyLogoutOneLogoutRequestNotAttempted()

View license
@Test
public void verifyLogoutOneLogoutRequestNotAttempted() throws Exception {
    final SingleLogoutService service = new WebApplicationServiceFactory().createService(TEST_URL, SingleLogoutService.class);
    final LogoutRequest logoutRequest = new DefaultLogoutRequest(TICKET_ID, service, new URL(TEST_URL));
    final Event event = getLogoutEvent(Arrays.asList(logoutRequest));
    assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
    final List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, list.size());
    final String url = (String) event.getAttributes().get(FrontChannelLogoutAction.DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL);
    assertTrue(url.startsWith(TEST_URL + '?' + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + '='));
    final byte[] samlMessage = EncodingUtils.decodeBase64(URLDecoder.decode(StringUtils.substringAfter(url, '?' + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + '='), "UTF-8"));
    final Inflater decompresser = new Inflater();
    decompresser.setInput(samlMessage);
    final byte[] result = new byte[1000];
    decompresser.inflate(result);
    decompresser.end();
    final String message = new String(result);
    assertTrue(message.startsWith("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""));
    assertTrue(message.contains("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>"));
}

5. FrontChannelLogoutActionTests#verifyLogoutOneLogoutRequestNotAttempted()

View license
@Test
public void verifyLogoutOneLogoutRequestNotAttempted() throws Exception {
    final SingleLogoutService service = new WebApplicationServiceFactory().createService(TEST_URL, SingleLogoutService.class);
    final LogoutRequest logoutRequest = new DefaultLogoutRequest(TICKET_ID, service, new URL(TEST_URL));
    final Event event = getLogoutEvent(Arrays.asList(logoutRequest));
    assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
    final List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, list.size());
    final String url = (String) event.getAttributes().get(FrontChannelLogoutAction.DEFAULT_FLOW_ATTRIBUTE_LOGOUT_URL);
    assertTrue(url.startsWith(TEST_URL + '?' + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + '='));
    final byte[] samlMessage = EncodingUtils.decodeBase64(URLDecoder.decode(StringUtils.substringAfter(url, '?' + FrontChannelLogoutAction.DEFAULT_LOGOUT_PARAMETER + '='), "UTF-8"));
    final Inflater decompresser = new Inflater();
    decompresser.setInput(samlMessage);
    final byte[] result = new byte[1000];
    decompresser.inflate(result);
    decompresser.end();
    final String message = new String(result);
    assertTrue(message.startsWith("<samlp:LogoutRequest xmlns:samlp=\"urn:oasis:names:tc:SAML:2.0:protocol\" ID=\""));
    assertTrue(message.contains("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>"));
}

6. DeflateCompressor#uncompress()

Project: cassandra
Source File: DeflateCompressor.java
View license
public int uncompress(byte[] input, int inputOffset, int inputLength, byte[] output, int outputOffset, int maxOutputLength) throws IOException {
    Inflater inf = inflater.get();
    inf.reset();
    inf.setInput(input, inputOffset, inputLength);
    if (inf.needsInput())
        return 0;
    // We assume output is big enough
    try {
        return inf.inflate(output, outputOffset, maxOutputLength);
    } catch (DataFormatException e) {
        throw new IOException(e);
    }
}

7. ZipDecompressor#decompress()

Project: openjdk
Source File: ZipDecompressor.java
View license
static byte[] decompress(byte[] bytesIn, int offset) throws Exception {
    Inflater inflater = new Inflater();
    inflater.setInput(bytesIn, offset, bytesIn.length - offset);
    ByteArrayOutputStream stream = new ByteArrayOutputStream(bytesIn.length - offset);
    byte[] buffer = new byte[1024];
    while (!inflater.finished()) {
        int count = inflater.inflate(buffer);
        stream.write(buffer, 0, count);
    }
    stream.close();
    byte[] bytesOut = stream.toByteArray();
    inflater.end();
    return bytesOut;
}

8. ZipFileIndex#inflate()

Project: error-prone-javac
Source File: ZipFileIndex.java
View license
private int inflate(byte[] src, byte[] dest) {
    Inflater inflater = (inflaterRef == null ? null : inflaterRef.get());
    // construct the inflater object or reuse an existing one
    if (inflater == null)
        inflaterRef = new SoftReference<>(inflater = new Inflater(true));
    inflater.reset();
    inflater.setInput(src);
    try {
        return inflater.inflate(dest);
    } catch (DataFormatException ex) {
        return -1;
    }
}

9. Zlib#inflate()

Project: Nukkit
Source File: Zlib.java
View license
public static byte[] inflate(byte[] data) throws DataFormatException, IOException {
    Inflater inflater = new Inflater();
    inflater.setInput(data);
    ByteArrayOutputStream o = new ByteArrayOutputStream(data.length);
    byte[] buf = new byte[1024];
    while (!inflater.finished()) {
        int i = inflater.inflate(buf);
        o.write(buf, 0, i);
    }
    inflater.end();
    return o.toByteArray();
}

10. ZipFileIndex#inflate()

Project: ceylon-compiler
Source File: ZipFileIndex.java
View license
private int inflate(byte[] src, byte[] dest) {
    Inflater inflater = (inflaterRef == null ? null : inflaterRef.get());
    // construct the inflater object or reuse an existing one
    if (inflater == null)
        inflaterRef = new SoftReference<Inflater>(inflater = new Inflater(true));
    inflater.reset();
    inflater.setInput(src);
    try {
        return inflater.inflate(dest);
    } catch (DataFormatException ex) {
        return -1;
    }
}

11. ZipFileIndex#inflate()

Project: ceylon
Source File: ZipFileIndex.java
View license
private int inflate(byte[] src, byte[] dest) {
    Inflater inflater = (inflaterRef == null ? null : inflaterRef.get());
    // construct the inflater object or reuse an existing one
    if (inflater == null)
        inflaterRef = new SoftReference<Inflater>(inflater = new Inflater(true));
    inflater.reset();
    inflater.setInput(src);
    try {
        return inflater.inflate(dest);
    } catch (DataFormatException ex) {
        return -1;
    }
}

12. DeflaterUtils#inflate()

View license
public static byte[] inflate(byte[] inputBytes) throws DataFormatException {
    // Inflate the content, assuming the size won't increase more than 10 times
    byte[] inflatedBytes = new byte[inputBytes.length * 10];
    /*
		 * As we are using the 'nowrap' option,  it is necessary to provide an extra "dummy" byte as input.
		 * Seems to be working even without this extra dummy byte. But javadoc recommends to add a dummy byte.
		 * Adding 0 add the dummy byte at the end of the input byte array.
		 */
    byte[] inputWithDummyByteAdded = Arrays.copyOf(inputBytes, inputBytes.length + 1);
    // Set nowrap to true, to ignore the ZLIB headers
    Inflater inflater = new Inflater(true);
    inflater.setInput(inputWithDummyByteAdded);
    int number_inflated_bytes = inflater.inflate(inflatedBytes);
    inflater.end();
    return Arrays.copyOf(inflatedBytes, number_inflated_bytes);
}

13. HttpConnection#decompressBuffer()

Project: Orchid
Source File: HttpConnection.java
View license
private byte[] decompressBuffer(byte[] buffer) throws IOException {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    final Inflater decompressor = new Inflater();
    final byte[] decompressBuffer = new byte[4096];
    decompressor.setInput(buffer);
    int n;
    try {
        while ((n = decompressor.inflate(decompressBuffer)) != 0) {
            output.write(decompressBuffer, 0, n);
        }
        return output.toByteArray();
    } catch (DataFormatException e) {
        throw new IOException("Error decompressing http body: " + e);
    }
}

14. TezUtilsInternal#uncompressBytesInflateDeflate()

Project: tez
Source File: TezUtilsInternal.java
View license
private static byte[] uncompressBytesInflateDeflate(byte[] inBytes) throws IOException {
    Inflater inflater = new Inflater();
    inflater.setInput(inBytes);
    ByteArrayOutputStream bos = new ByteArrayOutputStream(inBytes.length);
    byte[] buffer = new byte[1024 * 8];
    while (!inflater.finished()) {
        int count;
        try {
            count = inflater.inflate(buffer);
        } catch (DataFormatException e) {
            throw new IOException(e);
        }
        bos.write(buffer, 0, count);
    }
    byte[] output = bos.toByteArray();
    return output;
}

15. CompressionUtils#decompress()

Project: kylin
Source File: CompressionUtils.java
View license
public static byte[] decompress(byte[] data) throws IOException, DataFormatException {
    long startTime = System.currentTimeMillis();
    Inflater inflater = new Inflater();
    inflater.setInput(data);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
    byte[] buffer = new byte[1024];
    while (!inflater.finished()) {
        int count = inflater.inflate(buffer);
        outputStream.write(buffer, 0, count);
    }
    outputStream.close();
    byte[] output = outputStream.toByteArray();
    logger.debug("Original: " + data.length + " bytes. " + "Decompressed: " + output.length + " bytes. Time: " + (System.currentTimeMillis() - startTime));
    return output;
}

16. TezUtils#uncompressBytesInflateDeflate()

Project: incubator-tez
Source File: TezUtils.java
View license
private static byte[] uncompressBytesInflateDeflate(byte[] inBytes) throws IOException {
    Inflater inflater = new Inflater();
    inflater.setInput(inBytes);
    ByteArrayOutputStream bos = new ByteArrayOutputStream(inBytes.length);
    byte[] buffer = new byte[1024 * 8];
    while (!inflater.finished()) {
        int count;
        try {
            count = inflater.inflate(buffer);
        } catch (DataFormatException e) {
            throw new IOException(e);
        }
        bos.write(buffer, 0, count);
    }
    byte[] output = bos.toByteArray();
    return output;
}

17. HttpConnection#decompressBuffer()

Project: bitcoinj
Source File: HttpConnection.java
View license
private byte[] decompressBuffer(byte[] buffer) throws IOException {
    final ByteArrayOutputStream output = new ByteArrayOutputStream();
    final Inflater decompressor = new Inflater();
    final byte[] decompressBuffer = new byte[4096];
    decompressor.setInput(buffer);
    int n;
    try {
        while ((n = decompressor.inflate(decompressBuffer)) != 0) {
            output.write(decompressBuffer, 0, n);
        }
        return output.toByteArray();
    } catch (DataFormatException e) {
        throw new IOException("Error decompressing http body: " + e);
    }
}

18. ArchiveTool#extract()

Project: ThriftyPaxos
Source File: ArchiveTool.java
View license
private static void extract(String fromFile, String toDir) throws IOException {
    long start = System.currentTimeMillis();
    long size = new File(fromFile).length();
    System.out.println("Extracting " + size / MB + " MB");
    InputStream in = new BufferedInputStream(new FileInputStream(fromFile), 1024 * 1024);
    String temp = fromFile + ".temp";
    Inflater inflater = new Inflater();
    in = new InflaterInputStream(in, inflater, 1024 * 1024);
    OutputStream out = getDirectoryOutputStream(toDir);
    combine(in, out, temp);
    inflater.end();
    in.close();
    out.close();
    System.out.println();
    System.out.println("Extracted in " + (System.currentTimeMillis() - start) / 1000 + " seconds");
}

19. MinimalPerfectHash#expand()

View license
/**
     * Decompress the hash description using a Huffman coding.
     *
     * @param d the data
     * @return the decompressed data
     */
private static byte[] expand(byte[] d) {
    Inflater inflater = new Inflater();
    inflater.setInput(d);
    ByteArrayOutputStream out = new ByteArrayOutputStream(d.length);
    byte[] buffer = new byte[1024];
    try {
        while (!inflater.finished()) {
            int count = inflater.inflate(buffer);
            out.write(buffer, 0, count);
        }
        inflater.end();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
    return out.toByteArray();
}

20. PerfectHash#expand()

Project: ThriftyPaxos
Source File: PerfectHash.java
View license
/**
     * Decompress the hash description using a Huffman coding.
     *
     * @param d the data
     * @return the decompressed data
     */
private static byte[] expand(byte[] d) {
    Inflater inflater = new Inflater();
    inflater.setInput(d);
    ByteArrayOutputStream out = new ByteArrayOutputStream(d.length);
    byte[] buffer = new byte[1024];
    try {
        while (!inflater.finished()) {
            int count = inflater.inflate(buffer);
            out.write(buffer, 0, count);
        }
        inflater.end();
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
    return out.toByteArray();
}

21. Utils#decompress()

Project: bitsquare
Source File: Utils.java
View license
private static byte[] decompress(byte[] compressedData, int length) {
    Inflater inflater = new Inflater();
    inflater.setInput(compressedData, 0, length);
    ByteArrayOutputStream bos = new ByteArrayOutputStream(length);
    byte[] buf = new byte[8192];
    while (!inflater.finished()) {
        try {
            int count = inflater.inflate(buf);
            bos.write(buf, 0, count);
        } catch (DataFormatException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    try {
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    return bos.toByteArray();
}

22. ZipkinHttpCollector#gunzip()

Project: zipkin
Source File: ZipkinHttpCollector.java
View license
static byte[] gunzip(byte[] input) throws IOException {
    Inflater inflater = new Inflater();
    inflater.setInput(input);
    try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream(input.length)) {
        while (!inflater.finished()) {
            int count = inflater.inflate(GZIP_BUFFER.get());
            outputStream.write(GZIP_BUFFER.get(), 0, count);
        }
        return outputStream.toByteArray();
    } catch (DataFormatException e) {
        throw new IOException(e.getMessage(), e);
    }
}

23. SerializerCompressionDeflateWrapper#deserialize()

View license
@Override
public E deserialize(DataInput2 in, int available) throws IOException {
    final int unpackedSize = in.unpackInt() - 1;
    if (unpackedSize == -1) {
        //was not compressed
        return serializer.deserialize(in, available > 0 ? available - 1 : available);
    }
    Inflater inflater = new Inflater();
    if (dictionary != null) {
        inflater.setDictionary(dictionary);
    }
    InflaterInputStream in4 = new InflaterInputStream(new DataInput2.DataInputToStream(in), inflater);
    byte[] unpacked = new byte[unpackedSize];
    in4.read(unpacked, 0, unpackedSize);
    DataInput2.ByteArray in2 = new DataInput2.ByteArray(unpacked);
    E ret = serializer.deserialize(in2, unpackedSize);
    if (CC.ASSERT && !(in2.pos == unpackedSize))
        throw new DBException.DataCorruption("data were not fully read");
    return ret;
}

24. DeflaterSinkTest#inflate()

Project: okio
Source File: DeflaterSinkTest.java
View license
/**
   * Uses streaming decompression to inflate {@code deflated}. The input must
   * either be finished or have a trailing sync flush.
   */
private Buffer inflate(Buffer deflated) throws IOException {
    InputStream deflatedIn = deflated.inputStream();
    Inflater inflater = new Inflater();
    InputStream inflatedIn = new InflaterInputStream(deflatedIn, inflater);
    Buffer result = new Buffer();
    byte[] buffer = new byte[8192];
    while (!inflater.needsInput() || deflated.size() > 0 || deflatedIn.available() > 0) {
        int count = inflatedIn.read(buffer, 0, buffer.length);
        if (count != -1) {
            result.write(buffer, 0, count);
        }
    }
    return result;
}

25. CompressedArray#decompress()

Project: graphhopper
Source File: CompressedArray.java
View license
/**
     * Decompress the byte array previously returned by compress
     */
public static byte[] decompress(byte[] value) throws DataFormatException {
    // Create an expandable byte array to hold the decompressed data
    ByteArrayOutputStream bos = new ByteArrayOutputStream(value.length);
    Inflater decompressor = new Inflater();
    try {
        decompressor.setInput(value);
        final byte[] buf = new byte[1024];
        while (!decompressor.finished()) {
            int count = decompressor.inflate(buf);
            bos.write(buf, 0, count);
        }
    } finally {
        decompressor.end();
    }
    return bos.toByteArray();
}

26. RedirectSAML2ClientTests#getInflatedAuthnRequest()

Project: pac4j
Source File: RedirectSAML2ClientTests.java
View license
private String getInflatedAuthnRequest(final String location) throws Exception {
    final List<NameValuePair> pairs = URLEncodedUtils.parse(java.net.URI.create(location), "UTF-8");
    final Inflater inflater = new Inflater(true);
    final byte[] decodedRequest = Base64.getDecoder().decode(pairs.get(0).getValue());
    final ByteArrayInputStream is = new ByteArrayInputStream(decodedRequest);
    final InflaterInputStream inputStream = new InflaterInputStream(is, inflater);
    final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, HttpConstants.UTF8_ENCODING));
    String line;
    final StringBuilder bldr = new StringBuilder();
    while ((line = reader.readLine()) != null) {
        bldr.append(line);
    }
    return bldr.toString();
}

27. OldAndroidDeflateTest#bigTest()

Project: j2objc
Source File: OldAndroidDeflateTest.java
View license
/*
     * "step" determines how compressible the data is.
     *
     * Note we must set "nowrap" to false, or the Adler-32 doesn't get
     * computed.
     */
private void bigTest(int step, int expectedAdler) throws UnsupportedEncodingException, DataFormatException {
    byte[] input = new byte[128 * 1024];
    byte[] comp = new byte[128 * 1024 + 512];
    byte[] output = new byte[128 * 1024 + 512];
    Inflater inflater = new Inflater(false);
    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION, false);
    createSample(input, step);
    compress(deflater, input, comp);
    expand(inflater, comp, (int) deflater.getBytesWritten(), output);
    assertEquals(inflater.getBytesWritten(), input.length);
    assertEquals(deflater.getAdler(), inflater.getAdler());
    assertEquals(deflater.getAdler(), expectedAdler);
}

28. DeflaterTest#testDeflate()

Project: j2objc
Source File: DeflaterTest.java
View license
public void testDeflate() throws DataFormatException {
    deflater.setInput(new byte[] { 1, 2, 3 });
    deflateInflate(Deflater.NO_FLUSH);
    assertTrue(totalInflated < 3);
    // the 3rd byte shouldn't have been flushed yet
    assertEquals(0, decompressed[2]);
    deflater.setInput(new byte[] { 4, 5, 6 });
    deflateInflate(Deflater.SYNC_FLUSH);
    assertEquals(6, totalInflated);
    assertDecompressed(1, 2, 3, 4, 5, 6);
    assertEquals(0, inflater.inflate(decompressed));
    deflater.setInput(new byte[] { 7, 8, 9 });
    deflateInflate(Deflater.FULL_FLUSH);
    assertEquals(9, totalInflated);
    assertDecompressed(1, 2, 3, 4, 5, 6, 7, 8, 9);
    assertEquals(0, inflater.inflate(decompressed));
    // safe because we did a FULL_FLUSH
    inflater = new Inflater(true);
    deflater.setInput(new byte[] { 10, 11, 12 });
    deflateInflate(Deflater.SYNC_FLUSH);
    assertEquals(12, totalInflated);
    assertDecompressed(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
    assertEquals(0, inflater.inflate(decompressed));
}

29. BiDiGzipHandler#buildInflater()

Project: dropwizard
Source File: BiDiGzipHandler.java
View license
private Inflater buildInflater() {
    final Inflater inflater = localInflater.get();
    if (inflater != null) {
        // The request could fail in the middle of decompressing, so potentially we can get
        // a broken inflater in the thread local storage. That's why we need to clear the storage.
        localInflater.set(null);
        // Reuse the inflater from the thread local storage
        inflater.reset();
        return inflater;
    } else {
        return new Inflater(inflateNoWrap);
    }
}

30. BinaryCasSerDes6#closeDataInputs()

Project: uima-uimaj
Source File: BinaryCasSerDes6.java
View license
private void closeDataInputs() {
    for (DataInputStream is : dataInputs) {
        if (null != is) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }
    }
    // release any space inflater holding on to
    for (Inflater inflater : inflaters) {
        if (null != inflater) {
            inflater.end();
        }
    }
}

31. Compresser#inflate()

Project: zstack
Source File: Compresser.java
View license
public static byte[] inflate(byte[] input, int bufferSize) throws IOException {
    ByteArrayInputStream in = new ByteArrayInputStream(input);
    Inflater inf = new Inflater();
    InflaterInputStream iis = new InflaterInputStream(in, inf, bufferSize);
    ByteArrayOutputStream out = new ByteArrayOutputStream(input.length * 5);
    for (int c = iis.read(); c != -1; c = iis.read()) {
        out.write(c);
    }
    in.close();
    iis.close();
    byte[] ret = out.toByteArray();
    out.close();
    return ret;
}

32. OpenWireBytesMessage#doDecompress()

View license
@Override
protected Buffer doDecompress() throws IOException {
    Buffer compressed = getContent();
    Inflater inflater = new Inflater();
    DataByteArrayOutputStream decompressed = new DataByteArrayOutputStream();
    try {
        // Copy to avoid race on concurrent reads of compressed message payload.
        compressed = new Buffer(compressed);
        DataByteArrayInputStream compressedIn = new DataByteArrayInputStream(compressed);
        int length = compressedIn.readInt();
        compressedIn.close();
        byte[] data = Arrays.copyOfRange(compressed.getData(), 4, compressed.getLength());
        inflater.setInput(data);
        byte[] buffer = new byte[length];
        int count = inflater.inflate(buffer);
        decompressed.write(buffer, 0, count);
        return decompressed.toBuffer();
    } catch (Exception e) {
        throw new IOException(e);
    } finally {
        inflater.end();
        decompressed.close();
    }
}

33. InflaterTest#testInflaterCounts()

Project: j2objc
Source File: InflaterTest.java
View license
public void testInflaterCounts() throws Exception {
    Inflater inflater = new Inflater();
    byte[] decompressed = new byte[32];
    byte[] compressed = deflate(new byte[] { 1, 2, 3 }, null);
    assertEquals(11, compressed.length);
    // Feed in bytes [0, 5) to the first iteration.
    inflater.setInput(compressed, 0, 5);
    inflater.inflate(decompressed, 0, decompressed.length);
    assertEquals(5, inflater.getBytesRead());
    assertEquals(5, inflater.getTotalIn());
    assertEquals(2, inflater.getBytesWritten());
    assertEquals(2, inflater.getTotalOut());
    // Feed in bytes [5, 11) to the second iteration.
    assertEquals(true, inflater.needsInput());
    inflater.setInput(compressed, 5, 6);
    assertEquals(1, inflater.inflate(decompressed, 0, decompressed.length));
    assertEquals(11, inflater.getBytesRead());
    assertEquals(11, inflater.getTotalIn());
    assertEquals(3, inflater.getBytesWritten());
    assertEquals(3, inflater.getTotalOut());
    inflater.reset();
    assertEquals(0, inflater.getBytesRead());
    assertEquals(0, inflater.getTotalIn());
    assertEquals(0, inflater.getBytesWritten());
    assertEquals(0, inflater.getTotalOut());
}

34. OldAndroidDeflateTest#simpleTest()

Project: j2objc
Source File: OldAndroidDeflateTest.java
View license
/*
     * Simple inflate/deflate test, taken from the reference docs for the
     * Inflater/Deflater classes.
     */
private void simpleTest() throws UnsupportedEncodingException, DataFormatException {
    // Encode a String into bytes
    String inputString = "blahblahblah??";
    byte[] input = inputString.getBytes("UTF-8");
    // Compress the bytes
    byte[] output = new byte[100];
    Deflater compresser = new Deflater();
    compresser.setInput(input);
    compresser.finish();
    int compressedDataLength = compresser.deflate(output);
    // Decompress the bytes
    Inflater decompresser = new Inflater();
    decompresser.setInput(output, 0, compressedDataLength);
    byte[] result = new byte[100];
    int resultLength = decompresser.inflate(result);
    // Decode the bytes into a String
    String outputString = new String(result, 0, resultLength, "UTF-8");
    assertEquals(inputString, outputString);
    assertEquals(compresser.getAdler(), decompresser.getAdler());
    decompresser.end();
}

35. InflaterTest#assertRoundTrip()

Project: j2objc
Source File: InflaterTest.java
View license
private static void assertRoundTrip(byte[] dictionary) throws Exception {
    // Construct a nice long input byte sequence.
    String expected = makeString();
    byte[] expectedBytes = expected.getBytes("UTF-8");
    // Compress the bytes, using the passed-in dictionary (or no dictionary).
    byte[] deflatedBytes = deflate(expectedBytes, dictionary);
    // Get ready to decompress deflatedBytes back to the original bytes ...
    Inflater inflater = new Inflater();
    // We'll only supply the input a little bit at a time, so that zlib has to ask for more.
    final int CHUNK_SIZE = 16;
    int offset = 0;
    inflater.setInput(deflatedBytes, offset, CHUNK_SIZE);
    offset += CHUNK_SIZE;
    // If we used a dictionary to compress, check that we're asked for that same dictionary.
    if (dictionary != null) {
        // 1. there's no data available immediately...
        assertEquals(0, inflater.inflate(new byte[8]));
        // 2. ...because you need a dictionary.
        assertTrue(inflater.needsDictionary());
        // 3. ...and that dictionary has the same Adler32 as the dictionary we used.
        assertEquals(adler32(dictionary), inflater.getAdler());
        inflater.setDictionary(dictionary);
    }
    // Do the actual decompression, now the dictionary's set up appropriately...
    // We use a tiny output buffer to ensure that we call inflate multiple times, and
    // a tiny input buffer to ensure that zlib has to ask for more input.
    ByteArrayOutputStream inflatedBytes = new ByteArrayOutputStream();
    byte[] buf = new byte[8];
    while (inflatedBytes.size() != expectedBytes.length) {
        if (inflater.needsInput()) {
            int nextChunkByteCount = Math.min(CHUNK_SIZE, deflatedBytes.length - offset);
            inflater.setInput(deflatedBytes, offset, nextChunkByteCount);
            offset += nextChunkByteCount;
        } else {
            int inflatedByteCount = inflater.inflate(buf);
            if (inflatedByteCount > 0) {
                inflatedBytes.write(buf, 0, inflatedByteCount);
            }
        }
    }
    inflater.end();
    assertEquals(expected, new String(inflatedBytes.toByteArray(), "UTF-8"));
}

36. CompressUtil#decompress()

Project: Mycat-Server
Source File: CompressUtil.java
View license
/**
	 * ???mysql???????zlib??
	 *
	 * @param data  ??
	 * @param off   ???
	 * @param len   ??
	 * @return
	 */
public static byte[] decompress(byte[] data, int off, int len) {
    byte[] output = null;
    Inflater decompresser = new Inflater();
    decompresser.reset();
    decompresser.setInput(data, off, len);
    ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
    try {
        byte[] result = new byte[1024];
        while (!decompresser.finished()) {
            int i = decompresser.inflate(result);
            out.write(result, 0, i);
        }
        output = out.toByteArray();
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        try {
            out.close();
        } catch (Exception e) {
        }
        decompresser.end();
    }
    return output;
}

37. CompressionUtil#decompressByteArray()

Project: commons-jcs
Source File: CompressionUtil.java
View license
/**
     * Decompress the byte array passed
     * <p>
     * @param input compressed byte array webservice response
     * @param bufferLength buffer length
     * @return uncompressed byte array
     */
public static byte[] decompressByteArray(final byte[] input, final int bufferLength) {
    if (null == input) {
        throw new IllegalArgumentException("Input was null");
    }
    // Create the decompressor and give it the data to compress
    final Inflater decompressor = new Inflater();
    decompressor.setInput(input);
    // Create an expandable byte array to hold the decompressed data
    final ByteArrayOutputStream baos = new ByteArrayOutputStream(input.length);
    // Decompress the data
    final byte[] buf = new byte[bufferLength];
    try {
        while (!decompressor.finished()) {
            int count = decompressor.inflate(buf);
            baos.write(buf, 0, count);
        }
    } catch (DataFormatException ex) {
        log.error("Problem decompressing.", ex);
    }
    decompressor.end();
    try {
        baos.close();
    } catch (IOException ex) {
        log.error("Problem closing stream.", ex);
    }
    return baos.toByteArray();
}

38. HarmonyFixInflater#checkHarmoniousRepose()

Project: agit
Source File: HarmonyFixInflater.java
View license
public static boolean checkHarmoniousRepose() {
    Inflater inflater = new Inflater();
    try {
        inflater.setInput(demoDeflatedZeroBytes());
        inflater.inflate(new byte[0], 0, 0);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return inflater.finished();
}

39. Packet56MapChunks#readPacketData()

Project: Spoutcraft
Source File: Packet56MapChunks.java
View license
/**
	 * Abstract. Reads the raw packet data from the data stream.
	 */
public void readPacketData(DataInput par1DataInput) throws IOException {
    short var2 = par1DataInput.readShort();
    this.dataLength = par1DataInput.readInt();
    this.skyLightSent = par1DataInput.readBoolean();
    this.chunkPostX = new int[var2];
    this.chunkPosZ = new int[var2];
    this.field_73590_a = new int[var2];
    this.field_73588_b = new int[var2];
    this.field_73584_f = new byte[var2][];
    if (chunkDataNotCompressed.length < this.dataLength) {
        chunkDataNotCompressed = new byte[this.dataLength];
    }
    par1DataInput.readFully(chunkDataNotCompressed, 0, this.dataLength);
    byte[] var3 = new byte[196864 * var2];
    Inflater var4 = new Inflater();
    var4.setInput(chunkDataNotCompressed, 0, this.dataLength);
    try {
        var4.inflate(var3);
    } catch (DataFormatException var12) {
        throw new IOException("Bad compressed data format");
    } finally {
        var4.end();
    }
    int var5 = 0;
    for (int var6 = 0; var6 < var2; ++var6) {
        this.chunkPostX[var6] = par1DataInput.readInt();
        this.chunkPosZ[var6] = par1DataInput.readInt();
        this.field_73590_a[var6] = par1DataInput.readShort();
        this.field_73588_b[var6] = par1DataInput.readShort();
        int var7 = 0;
        int var8 = 0;
        int var9;
        for (var9 = 0; var9 < 16; ++var9) {
            var7 += this.field_73590_a[var6] >> var9 & 1;
            var8 += this.field_73588_b[var6] >> var9 & 1;
        }
        var9 = 2048 * 4 * var7 + 256;
        var9 += 2048 * var8;
        if (this.skyLightSent) {
            var9 += 2048 * var7;
        }
        this.field_73584_f[var6] = new byte[var9];
        System.arraycopy(var3, var5, this.field_73584_f[var6], 0, var9);
        var5 += var9;
    }
}

40. Packet51MapChunk#readPacketData()

Project: Spoutcraft
Source File: Packet51MapChunk.java
View license
// Spout End
/**
	 * Abstract. Reads the raw packet data from the data stream.
	 */
public void readPacketData(DataInput par1DataInput) throws IOException {
    this.xCh = par1DataInput.readInt();
    this.zCh = par1DataInput.readInt();
    this.includeInitialize = par1DataInput.readBoolean();
    this.yChMin = par1DataInput.readShort();
    this.yChMax = par1DataInput.readShort();
    this.tempLength = par1DataInput.readInt();
    if (temp.length < this.tempLength) {
        temp = new byte[this.tempLength];
    }
    par1DataInput.readFully(temp, 0, this.tempLength);
    int var2 = 0;
    int var3;
    for (var3 = 0; var3 < 16; ++var3) {
        var2 += this.yChMin >> var3 & 1;
    }
    var3 = 12288 * var2;
    if (this.includeInitialize) {
        var3 += 256;
    }
    this.compressedChunkData = new byte[var3];
    Inflater var4 = new Inflater();
    var4.setInput(temp, 0, this.tempLength);
    try {
        var4.inflate(this.compressedChunkData);
    } catch (DataFormatException var9) {
        throw new IOException("Bad compressed data format");
    } finally {
        var4.end();
    }
    SpoutClient.getInstance().getPacketManager().sendSpoutPacket(new PacketCustomBlockChunkOverride(xCh, zCh));
// Spout End
}

41. Utils#uncompress()

Project: TomP2P
Source File: Utils.java
View license
public static byte[] uncompress(byte[] compressedData, int offset, int length) {
    // Create the decompressor and give it the data to compress
    Inflater decompressor = new Inflater();
    decompressor.setInput(compressedData, offset, length);
    // Create an expandable byte array to hold the decompressed data
    ByteArrayOutputStream bos = new ByteArrayOutputStream(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) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    try {
        bos.close();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    // Get the decompressed data
    return bos.toByteArray();
}

42. CompressionUtils#inflate()

Project: passport
Source File: CompressionUtils.java
View license
/**
     * Inflate the given byte array by {@link #INFLATED_ARRAY_LENGTH}.
     *
     * @param bytes the bytes
     * @return the array as a string with {@code UTF-8} encoding
     */
public static String inflate(final byte[] bytes) {
    final Inflater inflater = new Inflater(true);
    final byte[] xmlMessageBytes = new byte[INFLATED_ARRAY_LENGTH];
    final byte[] extendedBytes = new byte[bytes.length + 1];
    System.arraycopy(bytes, 0, extendedBytes, 0, bytes.length);
    extendedBytes[bytes.length] = 0;
    inflater.setInput(extendedBytes);
    try {
        final int resultLength = inflater.inflate(xmlMessageBytes);
        inflater.end();
        if (!inflater.finished()) {
            throw new RuntimeException("buffer not large enough.");
        }
        inflater.end();
        return new String(xmlMessageBytes, 0, resultLength, "UTF-8");
    } catch (final DataFormatException e) {
        return null;
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Cannot find encoding: UTF-8", e);
    }
}

43. AbstractHistogram#decodeFromCompressedByteBuffer()

Project: voltdb
Source File: AbstractHistogram.java
View license
static <T extends AbstractHistogram> T decodeFromCompressedByteBuffer(final ByteBuffer buffer, final Class<T> histogramClass, final long minBarForHighestTrackableValue) throws DataFormatException {
    int initialTargetPosition = buffer.position();
    final int cookie = buffer.getInt();
    final int headerSize;
    if ((getCookieBase(cookie) == compressedEncodingCookieBase) || (getCookieBase(cookie) == V1CompressedEncodingCookieBase)) {
        headerSize = ENCODING_HEADER_SIZE;
    } else if (getCookieBase(cookie) == V0CompressedEncodingCookieBase) {
        headerSize = V0_ENCODING_HEADER_SIZE;
    } else {
        throw new IllegalArgumentException("The buffer does not contain a compressed Histogram");
    }
    final int lengthOfCompressedContents = buffer.getInt();
    final Inflater decompressor = new Inflater();
    if (buffer.hasArray()) {
        decompressor.setInput(buffer.array(), initialTargetPosition + 8, lengthOfCompressedContents);
    } else {
        byte[] compressedContents = new byte[lengthOfCompressedContents];
        buffer.get(compressedContents);
        decompressor.setInput(compressedContents);
    }
    final ByteBuffer headerBuffer = ByteBuffer.allocate(headerSize).order(BIG_ENDIAN);
    decompressor.inflate(headerBuffer.array());
    T histogram = decodeFromByteBuffer(headerBuffer, histogramClass, minBarForHighestTrackableValue, decompressor);
    return histogram;
}

44. PNGDecoder#decode()

Project: openjdk
Source File: PNGDecoder.java
View license
/**
     * Decodes image from an input stream passed into constructor.
     *
     * @return a BufferedImage object
     * @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 JemmyException("Format error"));
    }
    //!!crc
    readInt();
    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 = 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 JemmyException("ZIP error", e));
    }
    //!!crc
    readInt();
    //0
    readInt();
    byte[] iend = read(4);
    checkEquality(iend, "IEND".getBytes());
    //!!crc
    readInt();
    in.close();
    return result;
}

45. CompressionUtils#inflate()

Project: passport
Source File: CompressionUtils.java
View license
/**
     * Inflate the given byte array by {@link #INFLATED_ARRAY_LENGTH}.
     *
     * @param bytes the bytes
     * @return the array as a string with <code>UTF-8</code> encoding
     */
public static String inflate(final byte[] bytes) {
    final Inflater inflater = new Inflater(true);
    final byte[] xmlMessageBytes = new byte[INFLATED_ARRAY_LENGTH];
    final byte[] extendedBytes = new byte[bytes.length + 1];
    System.arraycopy(bytes, 0, extendedBytes, 0, bytes.length);
    extendedBytes[bytes.length] = 0;
    inflater.setInput(extendedBytes);
    try {
        final int resultLength = inflater.inflate(xmlMessageBytes);
        inflater.end();
        if (!inflater.finished()) {
            throw new RuntimeException("buffer not large enough.");
        }
        inflater.end();
        return new String(xmlMessageBytes, 0, resultLength, "UTF-8");
    } catch (final DataFormatException e) {
        return null;
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Cannot find encoding: UTF-8", e);
    }
}

46. CompressionUtils#inflate()

Project: cas
Source File: CompressionUtils.java
View license
/**
     * Inflate the given byte array by {@link #INFLATED_ARRAY_LENGTH}.
     *
     * @param bytes the bytes
     * @return the array as a string with {@code UTF-8} encoding
     */
public static String inflate(final byte[] bytes) {
    final Inflater inflater = new Inflater(true);
    final byte[] xmlMessageBytes = new byte[INFLATED_ARRAY_LENGTH];
    final byte[] extendedBytes = new byte[bytes.length + 1];
    System.arraycopy(bytes, 0, extendedBytes, 0, bytes.length);
    extendedBytes[bytes.length] = 0;
    inflater.setInput(extendedBytes);
    try {
        final int resultLength = inflater.inflate(xmlMessageBytes);
        inflater.end();
        if (!inflater.finished()) {
            throw new RuntimeException("buffer not large enough.");
        }
        inflater.end();
        return new String(xmlMessageBytes, 0, resultLength, "UTF-8");
    } catch (final DataFormatException e) {
        return null;
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Cannot find encoding: UTF-8", e);
    }
}

47. TiffImage#inflate()

Project: clj-pdf
Source File: TiffImage.java
View license
public static void inflate(byte[] deflated, byte[] inflated) {
    Inflater inflater = new Inflater();
    inflater.setInput(deflated);
    try {
        inflater.inflate(inflated);
    } catch (DataFormatException dfe) {
        throw new ExceptionConverter(dfe);
    }
}

48. InflaterTest#testEmptyFileAndEmptyBuffer()

Project: j2objc
Source File: InflaterTest.java
View license
/**
     * http://code.google.com/p/android/issues/detail?id=11755
     */
public void testEmptyFileAndEmptyBuffer() throws Exception {
    byte[] emptyInput = deflate(new byte[0], null);
    Inflater inflater = new Inflater();
    inflater.setInput(emptyInput);
    assertFalse(inflater.finished());
    assertEquals(0, inflater.inflate(new byte[0], 0, 0));
    assertTrue(inflater.finished());
}

49. DeflateUtils#inflateBestEffort()

Project: anthelion
Source File: DeflateUtils.java
View license
/**
   * Returns an inflated copy of the input array, truncated to
   * <code>sizeLimit</code> bytes, if necessary.  If the deflated input
   * has been truncated or corrupted, a best-effort attempt is made to
   * inflate as much as possible.  If no data can be extracted
   * <code>null</code> is returned.
   */
public static final byte[] inflateBestEffort(byte[] in, int sizeLimit) {
    // decompress using InflaterInputStream 
    ByteArrayOutputStream outStream = new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);
    // "true" because HTTP does not provide zlib headers
    Inflater inflater = new Inflater(true);
    InflaterInputStream inStream = new InflaterInputStream(new ByteArrayInputStream(in), inflater);
    byte[] buf = new byte[BUF_SIZE];
    int written = 0;
    while (true) {
        try {
            int size = inStream.read(buf);
            if (size <= 0)
                break;
            if ((written + size) > sizeLimit) {
                outStream.write(buf, 0, sizeLimit - written);
                break;
            }
            outStream.write(buf, 0, size);
            written += size;
        } catch (Exception e) {
            LOG.info("Caught Exception in inflateBestEffort", e);
            break;
        }
    }
    try {
        outStream.close();
    } catch (IOException e) {
    }
    return outStream.toByteArray();
}

50. PNGDecoder#decode()

Project: XM-File-Format
Source File: PNGDecoder.java
View license
/**
	 * Decodes the image into the specified buffer. The first line is placed at
	 * the current position. After decode the buffer position is at the end of
	 * the last line.
	 *
	 * @param buffer
	 *            the buffer
	 * @param stride
	 *            the stride in bytes from start of a line to start of the next
	 *            line, can be negative.
	 * @param fmt
	 *            the target format into which the image should be decoded.
	 * @throws IOException
	 *             if a read or data error occurred
	 * @throws IllegalArgumentException
	 *             if the start position of a line falls outside the buffer
	 * @throws UnsupportedOperationException
	 *             if the image can't be decoded into the desired format
	 */
public void decode(ByteBuffer buffer, int stride) throws IOException {
    final int offset = buffer.position();
    final int lineSize = ((width * bitdepth + 7) / 8) * bytesPerPixel;
    byte[] curLine = new byte[lineSize + 1];
    byte[] prevLine = new byte[lineSize + 1];
    byte[] palLine = (bitdepth < 8) ? new byte[width + 1] : null;
    final Inflater inflater = new Inflater();
    try {
        for (int y = 0; y < height; y++) {
            readChunkUnzip(inflater, curLine, 0, curLine.length);
            unfilter(curLine, prevLine);
            buffer.position(offset + y * stride);
            switch(colorType) {
                case COLOR_TRUECOLOR:
                    switch(format) {
                        case ABGR:
                            copyRGBtoABGR(buffer, curLine);
                            break;
                        case RGBA:
                            copyRGBtoRGBA(buffer, curLine);
                            break;
                        case BGRA:
                            copyRGBtoBGRA(buffer, curLine);
                            break;
                        case RGB:
                            copy(buffer, curLine);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported format for this image");
                    }
                    break;
                case COLOR_TRUEALPHA:
                    switch(format) {
                        case ABGR:
                            copyRGBAtoABGR(buffer, curLine);
                            break;
                        case RGBA:
                            copy(buffer, curLine);
                            break;
                        case BGRA:
                            copyRGBAtoBGRA(buffer, curLine);
                            break;
                        case RGB:
                            copyRGBAtoRGB(buffer, curLine);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported format for this image");
                    }
                    break;
                case COLOR_GREYSCALE:
                    switch(format) {
                        case LUMINANCE:
                        case ALPHA:
                            copy(buffer, curLine);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported format for this image");
                    }
                    break;
                case COLOR_GREYALPHA:
                    switch(format) {
                        case LUMINANCE_ALPHA:
                            copy(buffer, curLine);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported format for this image");
                    }
                    break;
                case COLOR_INDEXED:
                    switch(bitdepth) {
                        case 8:
                            palLine = curLine;
                            break;
                        case 4:
                            expand4(curLine, palLine);
                            break;
                        case 2:
                            expand2(curLine, palLine);
                            break;
                        case 1:
                            expand1(curLine, palLine);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported bitdepth for this image");
                    }
                    switch(format) {
                        case ABGR:
                            copyPALtoABGR(buffer, palLine);
                            break;
                        case RGBA:
                            copyPALtoRGBA(buffer, palLine);
                            break;
                        case BGRA:
                            copyPALtoBGRA(buffer, palLine);
                            break;
                        default:
                            throw new UnsupportedOperationException("Unsupported format for this image");
                    }
                    break;
                default:
                    throw new UnsupportedOperationException("Not yet implemented");
            }
            byte[] tmp = curLine;
            curLine = prevLine;
            prevLine = tmp;
        }
    } finally {
        inflater.end();
    }
}

51. CompressionUtilsTest#setup()

Project: undertow
Source File: CompressionUtilsTest.java
View license
@Before
public void setup() throws Exception {
    compress = new Deflater(Deflater.BEST_SPEED, true);
    decompress = new Inflater(true);
}

52. SevenZNativeHeapTest#testEndInflaterOnCloseStream()

View license
@Test
public void testEndInflaterOnCloseStream() throws Exception {
    final Inflater inflater = PowerMockito.spy(new Inflater());
    PowerMockito.whenNew(Inflater.class).withAnyArguments().thenReturn(inflater);
    final InputStream inputStream = deflateDecoder.decode("dummy", new ByteArrayInputStream(new byte[0]), 0, null, null);
    inputStream.close();
    Mockito.verify(inflater).end();
}

53. BinaryCasSerDes6#setupReadStream()

Project: uima-uimaj
Source File: BinaryCasSerDes6.java
View license
private void setupReadStream(int slotIndex, int bytesCompr, int bytesOrig) throws IOException {
    byte[] b = new byte[bytesCompr + 1];
    // this leaves 1 extra 0 byte at the end
    deserIn.readFully(b, 0, bytesCompr);
    // which may be required by Inflater with nowrap option - see Inflater javadoc
    // testing inflate speed
    //      long startTime = System.currentTimeMillis();
    //      inflater.reset();
    //      inflater.setInput(b);
    //      byte[] uncompressed = new byte[bytesOrig];
    //      int uncompressedLength = 0;
    //      try {
    //        uncompressedLength = inflater.inflate(uncompressed);
    //      } catch (DataFormatException e) {
    //        throw new RuntimeException(e);
    //      }
    //      if (uncompressedLength != bytesOrig) {
    //        throw new RuntimeException();
    //      }
    //      System.out.format("Decompress %s took %,d ms%n", 
    //          SlotKind.values()[slotIndex], System.currentTimeMillis() - startTime); 
    //      
    //      dataInputs[slotIndex] = new DataInputStream(new ByteArrayInputStream(uncompressed));
    Inflater inflater = new Inflater(true);
    // save to be able to call end() when done. 
    inflaters[slotIndex] = inflater;
    ByteArrayInputStream baiStream = new ByteArrayInputStream(b);
    // 32768 == 1<< 15.  Tuned by trials on 2015 intel i7
    int zipBufSize = Math.max(1 << 10, bytesCompr);
    // caches: L1 = 128KB    L2 = 1M     L3 = 6M
    // increasing the max causes cache dumping on this machine, and things slow down
    InflaterInputStream iis = new InflaterInputStream(baiStream, inflater, zipBufSize);
    // increasing the following buffer stream buffer size also seems to slow things down
    dataInputs[slotIndex] = new DataInputStream(new BufferedInputStream(iis, zipBufSize * 1));
}

54. SpdyReader#newNameValueBlockStream()

View license
private DataInputStream newNameValueBlockStream() {
    // Limit the inflater input stream to only those bytes in the Name/Value block.
    final InputStream throttleStream = new InputStream() {

        @Override
        public int read() throws IOException {
            return Util.readSingleByte(this);
        }

        @Override
        public int read(byte[] buffer, int offset, int byteCount) throws IOException {
            byteCount = Math.min(byteCount, compressedLimit);
            int consumed = in.read(buffer, offset, byteCount);
            compressedLimit -= consumed;
            return consumed;
        }

        @Override
        public void close() throws IOException {
            in.close();
        }
    };
    // Subclass inflater to install a dictionary when it's needed.
    Inflater inflater = new Inflater() {

        @Override
        public int inflate(byte[] buffer, int offset, int count) throws DataFormatException {
            int result = super.inflate(buffer, offset, count);
            if (result == 0 && needsDictionary()) {
                setDictionary(DICTIONARY);
                result = super.inflate(buffer, offset, count);
            }
            return result;
        }
    };
    return new DataInputStream(new InflaterInputStream(throttleStream, inflater));
}

55. BiDiGzipHandler#wrapDeflatedRequest()

Project: dropwizard
Source File: BiDiGzipHandler.java
View license
private WrappedServletRequest wrapDeflatedRequest(HttpServletRequest request) throws IOException {
    final Inflater inflater = buildInflater();
    final InflaterInputStream input = new InflaterInputStream(request.getInputStream(), inflater, inputBufferSize) {

        @Override
        public void close() throws IOException {
            super.close();
            localInflater.set(inflater);
        }
    };
    return new WrappedServletRequest(request, input);
}

56. DeflateCompressor#streamInput()

Project: elassandra
Source File: DeflateCompressor.java
View license
@Override
public StreamInput streamInput(StreamInput in) throws IOException {
    final byte[] headerBytes = new byte[HEADER.length];
    int len = 0;
    while (len < headerBytes.length) {
        final int read = in.read(headerBytes, len, headerBytes.length - len);
        if (read == -1) {
            break;
        }
        len += read;
    }
    if (len != HEADER.length || Arrays.equals(headerBytes, HEADER) == false) {
        throw new IllegalArgumentException("Input stream is not compressed with DEFLATE!");
    }
    final boolean nowrap = true;
    final Inflater inflater = new Inflater(nowrap);
    InputStream decompressedIn = new InflaterInputStream(in, inflater, BUFFER_SIZE);
    decompressedIn = new BufferedInputStream(decompressedIn, BUFFER_SIZE);
    return new InputStreamStreamInput(decompressedIn) {

        private boolean closed = false;

        public void close() throws IOException {
            try {
                super.close();
            } finally {
                if (closed == false) {
                    // important to release native memory
                    inflater.end();
                    closed = true;
                }
            }
        }
    };
}

57. DeflateCompressor#streamInput()

View license
@Override
public StreamInput streamInput(StreamInput in) throws IOException {
    final byte[] headerBytes = new byte[HEADER.length];
    int len = 0;
    while (len < headerBytes.length) {
        final int read = in.read(headerBytes, len, headerBytes.length - len);
        if (read == -1) {
            break;
        }
        len += read;
    }
    if (len != HEADER.length || Arrays.equals(headerBytes, HEADER) == false) {
        throw new IllegalArgumentException("Input stream is not compressed with DEFLATE!");
    }
    final boolean nowrap = true;
    final Inflater inflater = new Inflater(nowrap);
    InputStream decompressedIn = new InflaterInputStream(in, inflater, BUFFER_SIZE);
    decompressedIn = new BufferedInputStream(decompressedIn, BUFFER_SIZE);
    return new InputStreamStreamInput(decompressedIn) {

        final AtomicBoolean closed = new AtomicBoolean(false);

        public void close() throws IOException {
            try {
                super.close();
            } finally {
                if (closed.compareAndSet(false, true)) {
                    // important to release native memory
                    inflater.end();
                }
            }
        }
    };
}

58. DeflateDecompressingEntity#getDecompressingInputStream()

View license
/**
     * Returns the non-null InputStream that should be returned to by all
     * requests to {@link #getContent()}.
     * 
     * @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) {
        pushback.unread(peeked, 0, headerLength);
        return new InflaterInputStream(pushback, new Inflater(true));
    }
}

59. EventCompressorTests#setup()

View license
@Before
public void setup() {
    eventCompressor = new EventCompressor(new CustomLogger());
    inflater = new Inflater(true);
}

60. PNGImageReader#readImage()

Project: jdk7u-jdk
Source File: PNGImageReader.java
View license
private void readImage(ImageReadParam param) throws IIOException {
    readMetadata();
    int width = metadata.IHDR_width;
    int height = metadata.IHDR_height;
    // Init default values
    sourceXSubsampling = 1;
    sourceYSubsampling = 1;
    sourceMinProgressivePass = 0;
    sourceMaxProgressivePass = 6;
    sourceBands = null;
    destinationBands = null;
    destinationOffset = new Point(0, 0);
    // If an ImageReadParam is available, get values from it
    if (param != null) {
        sourceXSubsampling = param.getSourceXSubsampling();
        sourceYSubsampling = param.getSourceYSubsampling();
        sourceMinProgressivePass = Math.max(param.getSourceMinProgressivePass(), 0);
        sourceMaxProgressivePass = Math.min(param.getSourceMaxProgressivePass(), 6);
        sourceBands = param.getSourceBands();
        destinationBands = param.getDestinationBands();
        destinationOffset = param.getDestinationOffset();
    }
    Inflater inf = null;
    try {
        stream.seek(imageStartPosition);
        Enumeration<InputStream> e = new PNGImageDataEnumeration(stream);
        InputStream is = new SequenceInputStream(e);
        /* InflaterInputStream uses an Inflater instance which consumes
            * native (non-GC visible) resources. This is normally implicitly
            * freed when the stream is closed. However since the
            * InflaterInputStream wraps a client-supplied input stream,
            * we cannot close it.
            * But the app may depend on GC finalization to close the stream.
            * Therefore to ensure timely freeing of native resources we
            * explicitly create the Inflater instance and free its resources
            * when we are done with the InflaterInputStream by calling
            * inf.end();
            */
        inf = new Inflater();
        is = new InflaterInputStream(is, inf);
        is = new BufferedInputStream(is);
        this.pixelStream = new DataInputStream(is);
        theImage = getDestination(param, getImageTypes(0), width, height);
        Rectangle destRegion = new Rectangle(0, 0, 0, 0);
        sourceRegion = new Rectangle(0, 0, 0, 0);
        computeRegions(param, width, height, theImage, sourceRegion, destRegion);
        destinationOffset.setLocation(destRegion.getLocation());
        // At this point the header has been read and we know
        // how many bands are in the image, so perform checking
        // of the read param.
        int colorType = metadata.IHDR_colorType;
        checkReadParamBandSettings(param, inputBandsForColorType[colorType], theImage.getSampleModel().getNumBands());
        processImageStarted(0);
        decodeImage();
        if (abortRequested()) {
            processReadAborted();
        } else {
            processImageComplete();
        }
    } catch (IOException e) {
        throw new IIOException("Error reading PNG image data", e);
    } finally {
        if (inf != null) {
            inf.end();
        }
    }
}

61. SerializerCompressionDeflateWrapper#valueArrayDeserialize()

View license
@Override
public Object valueArrayDeserialize(DataInput2 in, int size) throws IOException {
    if (size == 0) {
        return serializer.valueArrayEmpty();
    }
    //decompress all values in single blob, it has better compressibility
    final int unpackedSize = in.unpackInt() - 1;
    if (unpackedSize == -1) {
        //was not compressed
        return serializer.valueArrayDeserialize(in, size);
    }
    Inflater inflater = new Inflater();
    if (dictionary != null) {
        inflater.setDictionary(dictionary);
    }
    InflaterInputStream in4 = new InflaterInputStream(new DataInput2.DataInputToStream(in), inflater);
    byte[] unpacked = new byte[unpackedSize];
    in4.read(unpacked, 0, unpackedSize);
    //now got data unpacked, so use serializer to deal with it
    DataInput2.ByteArray in2 = new DataInput2.ByteArray(unpacked);
    Object ret = serializer.valueArrayDeserialize(in2, size);
    if (CC.ASSERT && !(in2.pos == unpackedSize))
        throw new DBException.DataCorruption("data were not fully read");
    return ret;
}

62. CompressionZlib#init()

Project: mina-sshd
Source File: CompressionZlib.java
View license
@Override
public void init(Type type, int level) {
    compresser = new Deflater(level);
    decompresser = new Inflater();
}

63. OrcInputStream#decompressZip()

Project: presto
Source File: OrcInputStream.java
View license
// This comes from the Apache Hive ORC code
private int decompressZip(Slice in) throws IOException {
    Inflater inflater = new Inflater(true);
    try {
        inflater.setInput((byte[]) in.getBase(), (int) (in.getAddress() - ARRAY_BYTE_BASE_OFFSET), in.length());
        allocateOrGrowBuffer(in.length() * EXPECTED_COMPRESSION_RATIO, false);
        int uncompressedLength = 0;
        while (true) {
            uncompressedLength += inflater.inflate(buffer, uncompressedLength, buffer.length - uncompressedLength);
            if (inflater.finished() || buffer.length >= maxBufferSize) {
                break;
            }
            int oldBufferSize = buffer.length;
            allocateOrGrowBuffer(buffer.length * 2, true);
            if (buffer.length <= oldBufferSize) {
                throw new IllegalStateException(String.format("Buffer failed to grow. Old size %d, current size %d", oldBufferSize, buffer.length));
            }
        }
        if (!inflater.finished()) {
            throw new OrcCorruptionException("Could not decompress all input (output buffer too small?)");
        }
        return uncompressedLength;
    } catch (DataFormatException e) {
        throw new OrcCorruptionException(e, "Invalid compressed stream");
    } finally {
        inflater.end();
    }
}

64. PNGImageReader#readImage()

Project: openjdk
Source File: PNGImageReader.java
View license
private void readImage(ImageReadParam param) throws IIOException {
    readMetadata();
    int width = metadata.IHDR_width;
    int height = metadata.IHDR_height;
    // Init default values
    sourceXSubsampling = 1;
    sourceYSubsampling = 1;
    sourceMinProgressivePass = 0;
    sourceMaxProgressivePass = 6;
    sourceBands = null;
    destinationBands = null;
    destinationOffset = new Point(0, 0);
    // If an ImageReadParam is available, get values from it
    if (param != null) {
        sourceXSubsampling = param.getSourceXSubsampling();
        sourceYSubsampling = param.getSourceYSubsampling();
        sourceMinProgressivePass = Math.max(param.getSourceMinProgressivePass(), 0);
        sourceMaxProgressivePass = Math.min(param.getSourceMaxProgressivePass(), 6);
        sourceBands = param.getSourceBands();
        destinationBands = param.getDestinationBands();
        destinationOffset = param.getDestinationOffset();
    }
    Inflater inf = null;
    try {
        stream.seek(imageStartPosition);
        Enumeration<InputStream> e = new PNGImageDataEnumeration(stream);
        InputStream is = new SequenceInputStream(e);
        /* InflaterInputStream uses an Inflater instance which consumes
            * native (non-GC visible) resources. This is normally implicitly
            * freed when the stream is closed. However since the
            * InflaterInputStream wraps a client-supplied input stream,
            * we cannot close it.
            * But the app may depend on GC finalization to close the stream.
            * Therefore to ensure timely freeing of native resources we
            * explicitly create the Inflater instance and free its resources
            * when we are done with the InflaterInputStream by calling
            * inf.end();
            */
        inf = new Inflater();
        is = new InflaterInputStream(is, inf);
        is = new BufferedInputStream(is);
        this.pixelStream = new DataInputStream(is);
        /*
             * NB: the PNG spec declares that valid range for width
             * and height is [1, 2^31-1], so here we may fail to allocate
             * a buffer for destination image due to memory limitation.
             *
             * However, the recovery strategy for this case should be
             * defined on the level of application, so we will not
             * try to estimate the required amount of the memory and/or
             * handle OOM in any way.
             */
        theImage = getDestination(param, getImageTypes(0), width, height);
        Rectangle destRegion = new Rectangle(0, 0, 0, 0);
        sourceRegion = new Rectangle(0, 0, 0, 0);
        computeRegions(param, width, height, theImage, sourceRegion, destRegion);
        destinationOffset.setLocation(destRegion.getLocation());
        // At this point the header has been read and we know
        // how many bands are in the image, so perform checking
        // of the read param.
        int colorType = metadata.IHDR_colorType;
        checkReadParamBandSettings(param, inputBandsForColorType[colorType], theImage.getSampleModel().getNumBands());
        processImageStarted(0);
        decodeImage();
        if (abortRequested()) {
            processReadAborted();
        } else {
            processImageComplete();
        }
    } catch (IOException e) {
        throw new IIOException("Error reading PNG image data", e);
    } finally {
        if (inf != null) {
            inf.end();
        }
    }
}