Example usage for java.util.zip Inflater needsInput

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

Introduction

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

Prototype

public boolean needsInput() 

Source Link

Document

Returns true if no data remains in the input buffer.

Usage

From source file:Main.java

public static InputStream inflate(byte[] deflatedToken, boolean nowrap) throws DataFormatException {
    Inflater inflater = new Inflater(nowrap);
    inflater.setInput(deflatedToken);// ww w.java 2 s. c  o  m

    byte[] input = new byte[deflatedToken.length * 2];
    int inflatedLen = 0;
    int inputLen = 0;
    byte[] inflatedToken = input;
    while (!inflater.finished()) {
        inputLen = inflater.inflate(input);
        if (!inflater.finished()) {

            if (inputLen == 0) {
                if (inflater.needsInput()) {
                    throw new DataFormatException("Inflater can not inflate all the token bytes");
                } else {
                    break;
                }
            }

            inflatedToken = new byte[input.length + inflatedLen];
            System.arraycopy(input, 0, inflatedToken, inflatedLen, inputLen);
            inflatedLen += inputLen;
        }
    }
    InputStream is = new ByteArrayInputStream(input, 0, inputLen);
    if (inflatedToken != input) {
        is = new SequenceInputStream(new ByteArrayInputStream(inflatedToken, 0, inflatedLen), is);
    }
    return is;
}

From source file:edu.umn.msi.tropix.proteomics.conversion.impl.ConversionUtils.java

public static byte[] decompress(byte[] compressedData) {
    byte[] decompressedData;

    // using a ByteArrayOutputStream to not having to define the result array size beforehand
    Inflater decompressor = new Inflater();

    decompressor.setInput(compressedData);
    // Create an expandable byte array to hold the decompressed data
    ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);
    byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        try {//from   w ww  .ja v  a 2s  . c om
            int count = decompressor.inflate(buf);
            if (count == 0 && decompressor.needsInput()) {
                break;
            }
            bos.write(buf, 0, count);
        } catch (DataFormatException e) {
            throw new IllegalStateException(
                    "Encountered wrong data format " + "while trying to decompress binary data!", e);
        }
    }
    try {
        bos.close();
    } catch (IOException e) {
        // ToDo: add logging
        e.printStackTrace();
    }
    // Get the decompressed data
    decompressedData = bos.toByteArray();

    if (decompressedData == null) {
        throw new IllegalStateException("Decompression of binary data produced no result (null)!");
    }
    return decompressedData;
}

From source file:com.ctriposs.r2.filter.compression.DeflateCompressor.java

@Override
public byte[] inflate(InputStream data) throws CompressionException {
    byte[] input;
    try {//from   w w  w  . j a va  2  s. c o m
        input = IOUtils.toByteArray(data);
    } catch (IOException e) {
        throw new CompressionException(CompressionConstants.DECODING_ERROR + CompressionConstants.BAD_STREAM,
                e);
    }

    Inflater zlib = new Inflater();
    zlib.setInput(input);

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] temp = new byte[CompressionConstants.BUFFER_SIZE];

    int bytesRead;
    while (!zlib.finished()) {
        try {
            bytesRead = zlib.inflate(temp);
        } catch (DataFormatException e) {
            throw new CompressionException(CompressionConstants.DECODING_ERROR + getContentEncodingName(), e);
        }
        if (bytesRead == 0) {
            if (!zlib.needsInput()) {
                throw new CompressionException(CompressionConstants.DECODING_ERROR + getContentEncodingName());
            } else {
                break;
            }
        }

        if (bytesRead > 0) {
            output.write(temp, 0, bytesRead);
        }
    }

    zlib.end();
    return output.toByteArray();
}

From source file:z.hol.net.http.entity.DeflateDecompressingEntity.java

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

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

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

    int headerLength = pushback.read(peeked);

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

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

    Inflater inf = new Inflater();

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

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

            if (inf.needsDictionary()) {

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

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

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

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

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

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

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

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

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

    int headerLength = pushback.read(peeked);

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

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

    Inflater inf = new Inflater();

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

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

            if (inf.needsDictionary()) {

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

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

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

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

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

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

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

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

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

    final int headerLength = pushback.read(peeked);

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

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

    final Inflater inf = new Inflater();

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

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

            if (inf.needsDictionary()) {

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

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

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

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

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

From source file:org.apache.geode.management.internal.cli.CliUtil.java

public static DeflaterInflaterData uncompressBytes(byte[] output, int compressedDataLength)
        throws DataFormatException {
    Inflater decompresser = new Inflater();
    decompresser.setInput(output, 0, compressedDataLength);
    byte[] buffer = new byte[512];
    byte[] result = new byte[0];
    int bytesRead;
    while (!decompresser.needsInput()) {
        bytesRead = decompresser.inflate(buffer);
        byte[] newResult = new byte[result.length + bytesRead];
        System.arraycopy(result, 0, newResult, 0, result.length);
        System.arraycopy(buffer, 0, newResult, result.length, bytesRead);
        result = newResult;//from  w  ww .  j av a  2s.c  om
    }
    decompresser.end();

    return new DeflaterInflaterData(result.length, result);
}

From source file:org.exist.xmldb.RemoteResourceSet.java

@Override
public Resource getMembersAsResource() throws XMLDBException {
    final List<Object> params = new ArrayList<>();
    params.add(Integer.valueOf(handle));
    params.add(outputProperties);/*from   w ww .jav a 2s  . c o m*/

    try {

        final Path tmpfile = TemporaryFileManager.getInstance().getTemporaryFile();
        try (final OutputStream os = Files.newOutputStream(tmpfile)) {

            Map<?, ?> table = (Map<?, ?>) xmlRpcClient.execute("retrieveAllFirstChunk", params);

            long offset = ((Integer) table.get("offset")).intValue();
            byte[] data = (byte[]) table.get("data");
            final boolean isCompressed = "yes"
                    .equals(outputProperties.getProperty(EXistOutputKeys.COMPRESS_OUTPUT, "no"));
            // One for the local cached file
            Inflater dec = null;
            byte[] decResult = null;
            int decLength = 0;
            if (isCompressed) {
                dec = new Inflater();
                decResult = new byte[65536];
                dec.setInput(data);
                do {
                    decLength = dec.inflate(decResult);
                    os.write(decResult, 0, decLength);
                } while (decLength == decResult.length || !dec.needsInput());
            } else {
                os.write(data);
            }
            while (offset > 0) {
                params.clear();
                params.add(table.get("handle"));
                params.add(Long.toString(offset));
                table = (Map<?, ?>) xmlRpcClient.execute("getNextExtendedChunk", params);
                offset = Long.parseLong((String) table.get("offset"));
                data = (byte[]) table.get("data");
                // One for the local cached file
                if (isCompressed) {
                    dec.setInput(data);
                    do {
                        decLength = dec.inflate(decResult);
                        os.write(decResult, 0, decLength);
                    } while (decLength == decResult.length || !dec.needsInput());
                } else {
                    os.write(data);
                }
            }
            if (dec != null) {
                dec.end();
            }

            final RemoteXMLResource res = new RemoteXMLResource(leasableXmlRpcClient.lease(), collection,
                    handle, 0, XmldbURI.EMPTY_URI, Optional.empty());
            res.setContent(tmpfile);
            res.setProperties(outputProperties);
            return res;
        } catch (final XmlRpcException xre) {
            final byte[] data = (byte[]) xmlRpcClient.execute("retrieveAll", params);
            String content;
            try {
                content = new String(data, outputProperties.getProperty(OutputKeys.ENCODING, "UTF-8"));
            } catch (final UnsupportedEncodingException ue) {
                LOG.warn(ue);
                content = new String(data);
            }
            final RemoteXMLResource res = new RemoteXMLResource(leasableXmlRpcClient.lease(), collection,
                    handle, 0, XmldbURI.EMPTY_URI, Optional.empty());
            res.setContent(content);
            res.setProperties(outputProperties);
            return res;
        } catch (final IOException | DataFormatException ioe) {
            throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe);
        }
    } catch (final IOException ioe) {
        throw new XMLDBException(ErrorCodes.VENDOR_ERROR, ioe.getMessage(), ioe);
    } catch (final XmlRpcException xre) {
        throw new XMLDBException(ErrorCodes.INVALID_RESOURCE, xre.getMessage(), xre);
    }
}