Java Code Examples for java.util.zip.InflaterInputStream

The following examples show how to use java.util.zip.InflaterInputStream. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: anthelion   Source File: DeflateUtils.java    License: Apache License 2.0 7 votes vote down vote up
/**
 * Returns an inflated copy of the input array.  
 * @throws IOException if the input cannot be properly decompressed
 */
public static final byte[] inflate(byte[] in) throws IOException {
  // decompress using InflaterInputStream 
  ByteArrayOutputStream outStream = 
    new ByteArrayOutputStream(EXPECTED_COMPRESSION_RATIO * in.length);

  InflaterInputStream inStream = 
    new InflaterInputStream ( new ByteArrayInputStream(in) );

  byte[] buf = new byte[BUF_SIZE];
  while (true) {
    int size = inStream.read(buf);
    if (size <= 0) 
      break;
    outStream.write(buf, 0, size);
  }
  outStream.close();

  return outStream.toByteArray();
}
 
Example 2
Source Project: FastAsyncWorldedit   Source File: MCAFile.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void streamChunk(byte[] data, RunnableVal<NBTStreamer> withStream) throws IOException {
    if (data != null) {
        try {
            FastByteArrayInputStream nbtIn = new FastByteArrayInputStream(data);
            FastByteArrayInputStream bais = new FastByteArrayInputStream(data);
            InflaterInputStream iis = new InflaterInputStream(bais, new Inflater(), 1);
            fieldBuf2.set(iis, byteStore2.get());
            BufferedInputStream bis = new BufferedInputStream(iis);
            NBTInputStream nis = new NBTInputStream(bis);
            fieldBuf3.set(nis, byteStore3.get());
            NBTStreamer streamer = new NBTStreamer(nis);
            withStream.run(streamer);
            streamer.readQuick();
        } catch (IllegalAccessException unlikely) {
            unlikely.printStackTrace();
        }
    }
}
 
Example 3
@Override
synchronized public byte[] inflate(InputStream stream) throws IOException {
    InflaterInputStream inputStream = new InflaterInputStream(stream);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(BUFFER_SIZE);
    byte[] bufferOut;
    int length;

    try {
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
    } finally {
        outputStream.flush();
        bufferOut = outputStream.toByteArray();
        outputStream.close();
        inputStream.close();
    }

    return bufferOut;
}
 
Example 4
private InputStream urlToInputStream(URL url) throws IOException {
	URLConnection conn = url.openConnection();
	// pretend to be IE6
	conn.setRequestProperty("User-Agent", IE);
	// allow both GZip and Deflate (ZLib) encodings
	conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
	conn.connect();
	String encoding = conn.getContentEncoding();
	if ((encoding != null) && encoding.equalsIgnoreCase("gzip"))
		return new GZIPInputStream(conn.getInputStream());
	else if ((encoding != null) && encoding.equalsIgnoreCase("deflate"))
		return new InflaterInputStream(conn.getInputStream(), new Inflater(
			true));
	else
		return conn.getInputStream();
}
 
Example 5
Source Project: sc2gears   Source File: S2gsParser.java    License: Apache License 2.0 6 votes vote down vote up
private static byte[] extractS2gsData( final File s2gsFile ) throws IOException {
	final byte[] inBuffer = new byte[ 16 ];
	
	try ( final FileInputStream fis = new FileInputStream( s2gsFile ) ) {
		fis.read( inBuffer );
		
		final ByteBuffer header = ByteBuffer.wrap( inBuffer ).order( ByteOrder.LITTLE_ENDIAN );
		header.getInt();                   // Magic word: "ZmpC" ("CmpZ" backward meaning: compressed with Zlib)
		header.getInt();                   // Zeros (reserved? version?)
		final int size = header.getInt() ; // uncompressed data size
		header.getInt();                   // Zeros (reserved? version?)
		
		try ( final InflaterInputStream compressedInputStream = new InflaterInputStream( fis ) ) {
			final byte[] decompressed = new byte[ size ];
			int pos = 0;
			while ( pos < size )
				pos += compressedInputStream.read( decompressed, pos, size - pos );
			
			return decompressed;
		}
	}
}
 
Example 6
Source Project: dubbox   Source File: Bytes.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * unzip.
 * 
 * @param bytes compressed byte array.
 * @return byte uncompressed array.
 * @throws IOException
 */
public static byte[] unzip(byte[] bytes) throws IOException
{
	UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(bytes);
	UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
	InputStream is = new InflaterInputStream(bis);
	try
	{
		IOUtils.write(is, bos);
		return bos.toByteArray();
	}
	finally
	{
		is.close();
		bis.close();
		bos.close();
	}
}
 
Example 7
Source Project: armeria   Source File: HttpServerTest.java    License: Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@ArgumentsSource(ClientAndProtocolProvider.class)
void testStrings_acceptEncodingDeflate(WebClient client) throws Exception {
    final RequestHeaders req = RequestHeaders.of(HttpMethod.GET, "/strings",
                                                 HttpHeaderNames.ACCEPT_ENCODING, "deflate");
    final CompletableFuture<AggregatedHttpResponse> f = client.execute(req).aggregate();

    final AggregatedHttpResponse res = f.get();

    assertThat(res.status()).isEqualTo(HttpStatus.OK);
    assertThat(res.headers().get(HttpHeaderNames.CONTENT_ENCODING)).isEqualTo("deflate");
    assertThat(res.headers().get(HttpHeaderNames.VARY)).isEqualTo("accept-encoding");

    final byte[] decoded;
    try (InflaterInputStream unzipper =
                 new InflaterInputStream(new ByteArrayInputStream(res.content().array()))) {
        decoded = ByteStreams.toByteArray(unzipper);
    }
    assertThat(new String(decoded, StandardCharsets.UTF_8)).isEqualTo("Armeria is awesome!");
}
 
Example 8
Source Project: springboot-shiro-cas-mybatis   Source File: CompressionUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Decode the byte[] in base64 to a string.
 *
 * @param bytes the data to encode
 * @return the new string in {@link #UTF8_ENCODING}.
 */
public static String decodeByteArrayToString(final byte[] bytes) {
    final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final byte[] buf = new byte[bytes.length];
    try (final InflaterInputStream iis = new InflaterInputStream(bais)) {
        int count = iis.read(buf);
        while (count != -1) {
            baos.write(buf, 0, count);
            count = iis.read(buf);
        }
        return new String(baos.toByteArray(), Charset.forName(UTF8_ENCODING));
    } catch (final Exception e) {
        LOGGER.error("Base64 decoding failed", e);
        return null;
    }
}
 
Example 9
Source Project: centraldogma   Source File: ContentCompressionTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
void http() throws Exception {
    final WebClient client =
            WebClient.builder("http://127.0.0.1:" + dogma.serverAddress().getPort())
                     .setHttpHeader(HttpHeaderNames.AUTHORIZATION, "Bearer " + CsrfToken.ANONYMOUS)
                     .setHttpHeader(HttpHeaderNames.ACCEPT_ENCODING, "deflate")
                     .build();

    final String contentPath = HttpApiV1Constants.PROJECTS_PREFIX + '/' + PROJ +
                               HttpApiV1Constants.REPOS + '/' + REPO +
                               "/contents" + PATH;

    final AggregatedHttpResponse compressedResponse = client.get(contentPath).aggregate().join();
    assertThat(compressedResponse.status()).isEqualTo(HttpStatus.OK);

    final HttpData content = compressedResponse.content();
    try (Reader in = new InputStreamReader(new InflaterInputStream(new ByteArrayInputStream(
            content.array(), 0, content.length())), StandardCharsets.UTF_8)) {

        assertThat(CharStreams.toString(in)).contains(CONTENT);
    }
}
 
Example 10
private static String zlibDeflate(final byte[] bytes) {
    final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final InflaterInputStream iis = new InflaterInputStream(bais);
    final byte[] buf = new byte[1024];

    try {
        int count = iis.read(buf);
        while (count != -1) {
            baos.write(buf, 0, count);
            count = iis.read(buf);
        }
        return new String(baos.toByteArray());
    } catch (final Exception e) {
        return null;
    } finally {
        IOUtils.closeQuietly(iis);
    }
}
 
Example 11
/**
 * Base64 decodes the SAML message and then decompresses the message.
 * 
 * @param message Base64 encoded, DEFALTE compressed, SAML message
 * 
 * @return the SAML message
 * 
 * @throws MessageDecodingException thrown if the message can not be decoded
 */
protected InputStream decodeMessage(String message) throws MessageDecodingException {
    log.debug("Base64 decoding and inflating SAML message");

    byte[] decodedBytes = Base64.decode(message);
    if(decodedBytes == null){
        log.error("Unable to Base64 decode incoming message");
        throw new MessageDecodingException("Unable to Base64 decode incoming message");
    }
    
    try {
        ByteArrayInputStream bytesIn = new ByteArrayInputStream(decodedBytes);
        InflaterInputStream inflater = new InflaterInputStream(bytesIn, new Inflater(true));
        return inflater;
    } catch (Exception e) {
        log.error("Unable to Base64 decode and inflate SAML message", e);
        throw new MessageDecodingException("Unable to Base64 decode and inflate SAML message", e);
    }
}
 
Example 12
Source Project: lams   Source File: EscherPictBlip.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decompresses the provided data, returning the inflated result.
 *
 * @param data the deflated picture data.
 * @return the inflated picture data.
 */
private static byte[] inflatePictureData(byte[] data) {
    try {
        InflaterInputStream in = new InflaterInputStream(new ByteArrayInputStream(data));
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int readBytes;
        while ((readBytes = in.read(buf)) > 0) {
            out.write(buf, 0, readBytes);
        }
        return out.toByteArray();
    } catch (IOException e) {
        log.log(POILogger.INFO, "Possibly corrupt compression or non-compressed data", e);
        return data;
    }
}
 
Example 13
Source Project: lams   Source File: EscherMetafileBlip.java    License: GNU General Public License v2.0 6 votes vote down vote up
/**
 * Decompresses the provided data, returning the inflated result.
 *
 * @param data the deflated picture data.
 * @return the inflated picture data.
 */
private static byte[] inflatePictureData(byte[] data) {
    try {
        InflaterInputStream in = new InflaterInputStream(
            new ByteArrayInputStream( data ) );
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buf = new byte[4096];
        int readBytes;
        while ((readBytes = in.read(buf)) > 0) {
            out.write(buf, 0, readBytes);
        }
        return out.toByteArray();
    } catch (IOException e) {
        log.log(POILogger.WARN, "Possibly corrupt compression or non-compressed data", e);
        return data;
    }
}
 
Example 14
Source Project: Jupiter   Source File: Zlib.java    License: GNU General Public License v3.0 6 votes vote down vote up
public static byte[] inflate(InputStream stream) throws IOException {
    InflaterInputStream inputStream = new InflaterInputStream(stream);
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];
    int length;

    try {
        while ((length = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, length);
        }
    } finally {
        buffer = outputStream.toByteArray();
        outputStream.flush();
        outputStream.close();
        inputStream.close();
    }

    return buffer;
}
 
Example 15
Source Project: MonitorClient   Source File: ZLibUtil.java    License: Apache License 2.0 6 votes vote down vote up
/** 
 * 解压缩 
 * @param is 输入流        
 * @return byte[] 解压缩后的数据 
 */  
public static byte[] decompress(InputStream is) {  
    InflaterInputStream iis = new InflaterInputStream(is);  
    ByteArrayOutputStream o = new ByteArrayOutputStream(1024);  
    byte[] result = null;
    try {  
        int i = 1024;  
        byte[] buf = new byte[i];  
  
        while ((i = iis.read(buf, 0, i)) > 0) {  
            o.write(buf, 0, i);  
        }  
        result = o.toByteArray();
        o.close();
        iis.close();
    } catch (IOException e) {  
        e.printStackTrace();  
    }  
    return   result;
}
 
Example 16
Source Project: Jose4j   Source File: DeflateRFC1951CompressionAlgorithm.java    License: Apache License 2.0 6 votes vote down vote up
public byte[] decompress(byte[] compressedData) throws JoseException
{
    Inflater inflater = new Inflater(true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

    try (InflaterInputStream iis = new InflaterInputStream(new ByteArrayInputStream(compressedData), inflater))
    {
        int bytesRead;
        byte[] buff = new byte[256];
        while ((bytesRead = iis.read(buff)) != -1)
        {
            byteArrayOutputStream.write(buff, 0, bytesRead);
        }

        return byteArrayOutputStream.toByteArray();
    }
    catch (IOException e)
    {
        throw new JoseException("Problem decompressing data.", e);
    }
}
 
Example 17
Source Project: android-project-wo2b   Source File: ZLibUtils.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 解压缩
 * 
 * @param is 输入流
 * @return byte[] 解压缩后的数据
 */
public static byte[] decompress(InputStream is)
{
	InflaterInputStream iis = new InflaterInputStream(is);
	ByteArrayOutputStream o = new ByteArrayOutputStream(BUFFER_LENGTH);
	try
	{
		byte[] buf = new byte[BUFFER_LENGTH];
		int len = -1;
		while ((len = iis.read(buf)) != -1)
		{
			o.write(buf, 0, len);
		}
	}
	catch (IOException e)
	{
		e.printStackTrace();
	}

	return o.toByteArray();
}
 
Example 18
Source Project: rogue-cloud   Source File: CompressionUtils.java    License: Apache License 2.0 6 votes vote down vote up
private final static String decompressString(byte[] str) {
	
	// If compression is disabled, then the byte array is just a UTF-8 string
	if(!RCRuntime.ENABLE_DEFLATE_COMPRESSION) {
		return new String(str);
	}

	
	InflaterInputStream dis = new InflaterInputStream(new ByteArrayInputStream(str));
	
	try {
		return readIntoString(dis);
	} catch (IOException e) {
		e.printStackTrace();
		log.severe("Error on decompress",  e, null);
		throw new RuntimeException(e);
	}
}
 
Example 19
Source Project: gcs   Source File: PdfReader.java    License: Mozilla Public License 2.0 6 votes vote down vote up
/**
 * A helper to FlateDecode.
 *
 * @param in the input data
 * @param strict <CODE>true</CODE> to read a correct stream. <CODE>false</CODE> to try to read a
 *            corrupted stream
 * @return the decoded data
 */
public static byte[] FlateDecode(byte in[], boolean strict) {
	ByteArrayInputStream stream = new ByteArrayInputStream(in);
	InflaterInputStream zip = new InflaterInputStream(stream);
	ByteArrayOutputStream out = new ByteArrayOutputStream();
	byte b[] = new byte[strict ? 4092 : 1];
	try {
		int n;
		while ((n = zip.read(b)) >= 0) {
			out.write(b, 0, n);
		}
		zip.close();
		out.close();
		return out.toByteArray();
	} catch (Exception e) {
		if (strict) {
			return null;
		}
		return out.toByteArray();
	}
}
 
Example 20
Source Project: itext2   Source File: PdfReader.java    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
/** A helper to FlateDecode.
 * @param in the input data
 * @param strict <CODE>true</CODE> to read a correct stream. <CODE>false</CODE>
 * to try to read a corrupted stream
 * @return the decoded data
 */
public static byte[] FlateDecode(byte in[], boolean strict) {
    ByteArrayInputStream stream = new ByteArrayInputStream(in);
    InflaterInputStream zip = new InflaterInputStream(stream);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte b[] = new byte[strict ? 4092 : 1];
    try {
        int n;
        while ((n = zip.read(b)) >= 0) {
            out.write(b, 0, n);
        }
        zip.close();
        out.close();
        return out.toByteArray();
    }
    catch (Exception e) {
        if (strict)
            return null;
        return out.toByteArray();
    }
}
 
Example 21
Source Project: gama   Source File: DocumentationNode.java    License: GNU General Public License v3.0 5 votes vote down vote up
public static String decompress(final byte[] bytes) throws IOException {
	final InputStream in = new InflaterInputStream(new ByteArrayInputStream(bytes));
	final ByteArrayOutputStream baos = new ByteArrayOutputStream();
	final byte[] buffer = new byte[8192];
	int len;
	while ((len = in.read(buffer)) > 0) {
		baos.write(buffer, 0, len);
	}
	return new String(baos.toByteArray(), "ISO-8859-1");
}
 
Example 22
Source Project: incubator-hivemall   Source File: ObjectUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static void readCompressedObject(@Nonnull final byte[] src, final int offset,
        final int length, @Nonnull final Externalizable dst)
        throws IOException, ClassNotFoundException {
    FastByteArrayInputStream bis = new FastByteArrayInputStream(src, offset, length);
    final InflaterInputStream iis = new InflaterInputStream(bis);
    try {
        readObject(iis, dst);
    } finally {
        IOUtils.closeQuietly(iis);
    }
}
 
Example 23
Source Project: dubbo-2.6.5   Source File: Bytes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * unzip.
 *
 * @param bytes compressed byte array.
 * @return byte uncompressed array.
 * @throws IOException
 */
public static byte[] unzip(byte[] bytes) throws IOException {
    UnsafeByteArrayInputStream bis = new UnsafeByteArrayInputStream(bytes);
    UnsafeByteArrayOutputStream bos = new UnsafeByteArrayOutputStream();
    InputStream is = new InflaterInputStream(bis);
    try {
        IOUtils.write(is, bos);
        return bos.toByteArray();
    } finally {
        is.close();
        bis.close();
        bos.close();
    }
}
 
Example 24
Source Project: jdk1.8-source-analysis   Source File: PNGImageReader.java    License: Apache License 2.0 5 votes vote down vote up
private static byte[] inflate(byte[] b) throws IOException {
    InputStream bais = new ByteArrayInputStream(b);
    InputStream iis = new InflaterInputStream(bais);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    int c;
    try {
        while ((c = iis.read()) != -1) {
            baos.write(c);
        }
    } finally {
        iis.close();
    }
    return baos.toByteArray();
}
 
Example 25
Source Project: android_9.0.0_r45   Source File: BlobBackupHelper.java    License: Apache License 2.0 5 votes vote down vote up
private byte[] inflate(byte[] compressedData) {
    byte[] result = null;
    if (compressedData != null) {
        try {
            ByteArrayInputStream source = new ByteArrayInputStream(compressedData);
            DataInputStream headerIn = new DataInputStream(source);
            int version = headerIn.readInt();
            if (version > mCurrentBlobVersion) {
                Log.w(TAG, "Saved payload from unrecognized version " + version);
                return null;
            }

            InflaterInputStream in = new InflaterInputStream(source);
            ByteArrayOutputStream inflated = new ByteArrayOutputStream();
            byte[] buffer = new byte[4096];
            int nRead;
            while ((nRead = in.read(buffer)) > 0) {
                inflated.write(buffer, 0, nRead);
            }
            in.close();
            inflated.flush();
            result = inflated.toByteArray();
            if (DEBUG) {
                Log.v(TAG, "Inflated " + compressedData.length + " bytes to " + result.length);
            }
        } catch (IOException e) {
            // result is still null here
            Log.w(TAG, "Unable to process restored payload: " + e.getMessage());
        }
    }
    return result;
}
 
Example 26
Source Project: rocketmq-4.3.0   Source File: RegisterBrokerBody.java    License: Apache License 2.0 5 votes vote down vote up
private static byte[] readBytes(InflaterInputStream inflaterInputStream, int length) throws IOException {
    byte[] buffer = new byte[length];
    int bytesRead = 0;
    while (bytesRead < length) {
        int len = inflaterInputStream.read(buffer, bytesRead, length - bytesRead);
        if (len == -1) {
            throw new IOException("End of compressed data has reached");
        } else {
            bytesRead += len;
        }
    }
    return buffer;
}
 
Example 27
public static byte[] zlibDecompress(byte[] input) {
    InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(input));

    try {
        return IOUtils.toByteArray(inflater);
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("Could not decompress");
    }
    return new byte[0];
}
 
Example 28
Source Project: jvm-sandbox-repeater   Source File: Deflation.java    License: Apache License 2.0 5 votes vote down vote up
DeflateInputStream(Hessian2Input in)
  throws IOException
{
  _in = in;

  int len = in.readInt();

  if (len != 0)
    throw new IOException("expected no headers");
  
  _bodyIn = _in.readInputStream();

  _inflateIn = new InflaterInputStream(_bodyIn);
}
 
Example 29
Source Project: milkman   Source File: DeflatingWrapper.java    License: MIT License 5 votes vote down vote up
private static byte[] inflate(String data) throws Exception {
	byte[] compressed = Base64.getDecoder().decode(data);
	ByteArrayInputStream in = new ByteArrayInputStream(compressed);
	InflaterInputStream inf = new InflaterInputStream(in, new Inflater(true));
	byte[] byteArray = IOUtils.toByteArray(inf);
	return byteArray;
}
 
Example 30
Source Project: rocketmq-read   Source File: RegisterBrokerBody.java    License: Apache License 2.0 5 votes vote down vote up
private static byte[] readBytes(InflaterInputStream inflaterInputStream, int length) throws IOException {
    byte[] buffer = new byte[length];
    int bytesRead = 0;
    while (bytesRead < length) {
        int len = inflaterInputStream.read(buffer, bytesRead, length - bytesRead);
        if (len == -1) {
            throw new IOException("End of compressed data has reached");
        } else {
            bytesRead += len;
        }
    }
    return buffer;
}