Example usage for java.util.zip Inflater inflate

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

Introduction

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

Prototype

public int inflate(ByteBuffer output) throws DataFormatException 

Source Link

Document

Uncompresses bytes into specified buffer.

Usage

From source file:nl.nn.adapterframework.util.Misc.java

public static byte[] decompress(byte[] input) throws DataFormatException, IOException {
    // Create the decompressor and give it the data to compress
    Inflater decompressor = new Inflater();
    decompressor.setInput(input);/*  www .jav  a 2  s .  c  om*/

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

    // Decompress the data
    byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        int count = decompressor.inflate(buf);
        bos.write(buf, 0, count);
    }
    bos.close();

    // Get the decompressed data
    return bos.toByteArray();
}

From source file:org.jasig.cas.web.flow.FrontChannelLogoutActionTests.java

@Test
public void verifyLogoutOneLogoutRequestNotAttempted() throws Exception {
    final String fakeUrl = "http://url";
    final LogoutRequest logoutRequest = new LogoutRequest(TICKET_ID,
            new SimpleWebApplicationServiceImpl(fakeUrl));
    WebUtils.putLogoutRequests(this.requestContext, Arrays.asList(logoutRequest));
    this.requestContext.getFlowScope().put(FrontChannelLogoutAction.LOGOUT_INDEX, 0);
    final Event event = this.frontChannelLogoutAction.doExecute(this.requestContext);
    assertEquals(FrontChannelLogoutAction.REDIRECT_APP_EVENT, event.getId());
    final List<LogoutRequest> list = WebUtils.getLogoutRequests(this.requestContext);
    assertEquals(1, list.size());//from ww  w. ja  v a  2s  .  c  o m
    final String url = (String) event.getAttributes().get("logoutUrl");
    assertTrue(url.startsWith(fakeUrl + "?SAMLRequest="));
    final byte[] samlMessage = CompressionUtils.decodeBase64ToByteArray(
            URLDecoder.decode(StringUtils.substringAfter(url, "?SAMLRequest="), "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.indexOf("<samlp:SessionIndex>" + TICKET_ID + "</samlp:SessionIndex>") >= 0);
}

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  w  ww  . j  a v a 2  s  .  c  om
 *
 * @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()}./*w w  w .j a v  a2s  .  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: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  .j  av a 2s. 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.openteufel.file.mpq.MPQFileSector.java

public int getDecompressed(ByteBuffer out) throws DataFormatException, IOException {
    // If the file is encrypted, each sector (after compression/implosion, if applicable) is encrypted with the file's key.
    // Each sector is encrypted using the key + the 0-based index of the sector in the file.
    // NOTE compression type byte (if existing) is encrypted as well!
    ByteBuffer dataDecrypted;//w w w.  jav a  2s .  c  o  m
    if (this.encryptionSeed != null)
        dataDecrypted = MPQEncryptionUtils.decrypt(dataRaw, encryptionSeed);
    else
        dataDecrypted = dataRaw;
    dataDecrypted.rewind();

    switch (compression) {
    case Uncompressed: {
        out.put(dataDecrypted);
        return dataDecrypted.capacity();
    }
    case Imploded: {
        byte[] buf = new byte[sizeUncompressed];
        int numDecompressed = Exploder.pkexplode(dataDecrypted.array(), buf);
        if (numDecompressed != this.sizeUncompressed)
            throw new IllegalStateException();
        out.put(buf, 0, sizeUncompressed);
        return sizeUncompressed;
    }
    case ZLib: {
        int numDecompressed = 0;
        byte[] buf = new byte[1024];
        Inflater inflater = new Inflater();
        inflater.setInput(dataDecrypted.array());
        while (!inflater.finished()) {
            int decompressedBytes = inflater.inflate(buf);
            numDecompressed += decompressedBytes;
            out.put(buf, 0, decompressedBytes);
        }
        inflater.end();
        if (numDecompressed != this.sizeUncompressed)
            throw new IllegalStateException();
        return numDecompressed;
    }
    case BZip2: {
        int numDecompressed = 0;
        byte[] buf = new byte[1024];
        InputStream inputStream = new ByteArrayInputStream(dataDecrypted.array());
        BZip2CompressorInputStream uncompressStream = new BZip2CompressorInputStream(inputStream);
        while (true) {
            int decompressedBytes = uncompressStream.read(buf);
            if (decompressedBytes < 0)
                break;
            numDecompressed += decompressedBytes;
            out.put(buf, 0, decompressedBytes);
        }
        uncompressStream.close();
        inputStream.close();
        if (numDecompressed != sizeUncompressed)
            throw new IllegalStateException();
        return numDecompressed;
    }
    default:
        throw new IllegalStateException("Unknown Compression");
    }
}

From source file:com.nary.Debug.java

public static Object loadClass(InputStream _inStream, boolean _uncompress) {
    ObjectInputStream ois;/*from w ww .j ava2  s .  c o  m*/
    try {
        if (_uncompress) {
            // we need to get the input as a byte [] so we can decompress (inflate) it.  
            Inflater inflater = new Inflater();
            ByteArrayOutputStream bos;
            int bytesAvail = _inStream.available();
            if (bytesAvail > 0) {
                bos = new ByteArrayOutputStream(bytesAvail);
            } else {
                bos = new ByteArrayOutputStream();
            }

            byte[] buffer = new byte[1024];
            int read = _inStream.read(buffer);
            while (read > 0) {
                bos.write(buffer, 0, read);
                read = _inStream.read(buffer);
            }
            bos.flush();
            inflater.setInput(bos.toByteArray());

            bos.reset();
            buffer = new byte[1024];
            int inflated = inflater.inflate(buffer);
            while (inflated > 0) {
                bos.write(buffer, 0, inflated);
                inflated = inflater.inflate(buffer);
            }

            bos.flush();
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());

            ois = new ObjectInputStream(bis);

        } else {
            ois = new ObjectInputStream(_inStream);
        }

        return ois.readObject();
    } catch (Exception E) {
        return null;
    } finally {
        try {
            _inStream.close();
        } catch (Exception ioe) {
        }
    }
}

From source file:org.dragonet.proxy.protocol.packet.LoginPacket.java

@Override
public void decode() {
    try {/*ww  w  .  j av  a 2  s  .  c  om*/
        PEBinaryReader reader = new PEBinaryReader(new ByteArrayInputStream(this.getData()));
        reader.readByte(); //PID
        this.protocol = reader.readInt();
        this.gameEdition = reader.readByte();

        byte[] buff = new byte[40960];
        int len = reader.readUnsignedVarInt();
        Inflater inf = new Inflater();
        inf.setInput(reader.read(len));
        int out = inf.inflate(buff);
        inf.end();
        buff = ArrayUtils.subarray(buff, 0, out);
        String strJsonData;
        String strMetaData;
        {
            PEBinaryReader readerPayload = new PEBinaryReader(new ByteArrayInputStream(buff));
            readerPayload.switchEndianness();
            int jsonLen = readerPayload.readInt();
            readerPayload.switchEndianness();
            strJsonData = new String(readerPayload.read(jsonLen), "UTF-8");
            readerPayload.switchEndianness();
            int restLen = readerPayload.readInt();
            readerPayload.switchEndianness();
            strMetaData = new String(readerPayload.read(restLen), "UTF-8");
        }

        // Decode basic info
        {
            JSONObject data = new JSONObject(strJsonData);
            if (data.length() <= 0 || !data.has("chain") || data.optJSONArray("chain") == null) {
                return;
            }
            String[] chains = decodeJsonStringArray(data.getJSONArray("chain"));
            //System.out.println("Chain count: " + chains.length);
            for (String token : chains) {
                //System.out.println(" -- processing chain: " + token);
                JSONObject map = decodeToken(token);

                if (map == null || map.length() == 0) {
                    continue;
                }

                if (map.has("extraData")) {
                    JSONObject extras = map.getJSONObject("extraData");
                    if (extras.has("displayName")) {
                        username = extras.getString("displayName");
                    }
                    if (extras.has("identity")) {
                        this.clientUuid = UUID.fromString(extras.getString("identity"));
                    }
                }
                if (map.has("identityPublicKey")) {
                    publicKey = map.getString("identityPublicKey");
                }
            }
        }

        // Decode user metadata
        {
            JSONObject map = decodeToken(strMetaData);
            if (map.has("ClientRandomId"))
                clientID = map.getLong("ClientRandomId");
            if (map.has("ServerAddress"))
                serverAddress = map.getString("ServerAddress");
            if (map.has("SkinId"))
                skinName = map.getString("SkinId");
            if (map.has("SkinData"))
                skin = new MCPESkin(map.getString("SkinData"), skinName);
        }
    } catch (IOException | DataFormatException | JSONException e) {
        Logger.getLogger(LoginPacket.class.getName()).log(Level.SEVERE, null, e);
    }
}

From source file:org.hyperic.hq.livedata.agent.commands.LiveData_result.java

private String decompress(String s) throws IOException, DataFormatException {
    Inflater decompressor = new Inflater();
    decompressor.setInput(Base64.decode(s));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        int count = decompressor.inflate(buf);
        bos.write(buf, 0, count);/*from  ww w.j av  a  2s. c  om*/
    }

    bos.close();

    byte[] decompressedData = bos.toByteArray();
    return new String(decompressedData, 0, decompressedData.length, "UTF-8");
}