public static ExpandedResult processGzipEncoded(byte[] compressed, int sizeLimit) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(EXPECTED_GZIP_COMPRESSION_RATIO * compressed.length); GZIPInputStream inStream = new GZIPInputStream(new ByteArrayInputStream(compressed)); boolean isTruncated = false; byte[] buf = new byte[BUF_SIZE]; int written = 0; while (true) { try { int size = inStream.read(buf); if (size == -1) { break; } if ((written + size) > sizeLimit) { isTruncated = true; outStream.write(buf, 0, sizeLimit - written); break; } outStream.write(buf, 0, size); written += size; } catch (Exception e) { LOGGER.trace("Exception unzipping content", e); break; } } IoUtils.safeClose(outStream); return new ExpandedResult(outStream.toByteArray(), isTruncated); }
public static byte[] processDeflateEncoded(byte[] compressed, int sizeLimit) throws IOException { ByteArrayOutputStream outStream = new ByteArrayOutputStream(EXPECTED_DEFLATE_COMPRESSION_RATIO * compressed.length); // "true" because HTTP does not provide zlib headers Inflater inflater = new Inflater(true); InflaterInputStream inStream = new InflaterInputStream(new ByteArrayInputStream(compressed), 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) { LOGGER.trace("Exception inflating content", e); break; } } IoUtils.safeClose(outStream); return outStream.toByteArray(); }