Example usage for java.util.zip Inflater setInput

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

Introduction

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

Prototype

public void setInput(ByteBuffer input) 

Source Link

Document

Sets input data for decompression.

Usage

From source file:io.gomint.server.network.packet.PacketLogin.java

@Override
public void deserialize(PacketBuffer buffer) {
    this.protocol = buffer.readInt();

    // Decompress inner data (i don't know why you compress inside of a Batched Packet but hey)
    byte[] compressed = new byte[buffer.readInt()];
    buffer.readBytes(compressed);/*ww  w  . j  a v  a  2s.c o m*/

    Inflater inflater = new Inflater();
    inflater.setInput(compressed);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    try {
        byte[] comBuffer = new byte[1024];
        while (!inflater.finished()) {
            int read = inflater.inflate(comBuffer);
            bout.write(comBuffer, 0, read);
        }
    } catch (DataFormatException e) {
        System.out.println("Failed to decompress batch packet" + e);
        return;
    }

    // More data please
    ByteBuffer byteBuffer = ByteBuffer.wrap(bout.toByteArray());
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byte[] stringBuffer = new byte[byteBuffer.getInt()];
    byteBuffer.get(stringBuffer);

    // Decode the json stuff
    try {
        JSONObject jsonObject = (JSONObject) new JSONParser().parse(new String(stringBuffer));
        JSONArray chainArray = (JSONArray) jsonObject.get("chain");
        if (chainArray != null) {
            this.validationKey = parseBae64JSON((String) chainArray.get(chainArray.size() - 1)); // First key in chain is last response in chain #brainfuck :D
            for (Object chainObj : chainArray) {
                decodeBase64JSON((String) chainObj);
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // Skin comes next
    this.skin = new byte[byteBuffer.getInt()];
    byteBuffer.get(this.skin);
}

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

@Override
public void decode() {
    try {//from  w w  w . j a v  a 2s. 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.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil.java

/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq/*from ww  w  .j  ava 2s  .  c om*/
 * @return decoded AuthReq
 */
public static String decode(String encodedStr) throws IdentityException {
    try {
        org.apache.commons.codec.binary.Base64 base64Decoder = new org.apache.commons.codec.binary.Base64();
        byte[] xmlBytes = encodedStr.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        try {
            Inflater inflater = new Inflater(true);
            inflater.setInput(base64DecodedByteArray);
            byte[] xmlMessageBytes = new byte[5000];
            int resultLength = inflater.inflate(xmlMessageBytes);

            if (inflater.getRemaining() > 0) {
                throw new RuntimeException("didn't allocate enough space to hold " + "decompressed data");
            }

            inflater.end();
            String decodedString = new String(xmlMessageBytes, 0, resultLength, "UTF-8");
            if (log.isDebugEnabled()) {
                log.debug("Request message " + decodedString);
            }
            return decodedString;

        } catch (DataFormatException e) {
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(base64DecodedByteArray);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            InflaterInputStream iis = new InflaterInputStream(byteArrayInputStream);
            byte[] buf = new byte[1024];
            int count = iis.read(buf);
            while (count != -1) {
                byteArrayOutputStream.write(buf, 0, count);
                count = iis.read(buf);
            }
            iis.close();
            String decodedStr = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.UTF_8);
            if (log.isDebugEnabled()) {
                log.debug("Request message " + decodedStr, e);
            }
            return decodedStr;
        }
    } catch (IOException e) {
        throw new IdentityException("Error when decoding the SAML Request.", e);
    }

}

From source file:MSUmpire.SpectrumParser.mzXMLReadUnit.java

public byte[] ZlibUncompressBuffer(byte[] compressed) throws IOException, DataFormatException {

    Inflater decompressor = new Inflater();
    decompressor.setInput(compressed);

    ByteArrayOutputStream bos = null;
    try {//from   w  ww .  j  a v a 2 s .c  o m

        bos = new ByteArrayOutputStream(compressed.length);

        // Decompress the data
        byte[] buf = new byte[decompressor.getRemaining() * 2];
        while (decompressor.getRemaining() > 0) {
            int count = decompressor.inflate(buf);
            bos.write(buf, 0, count);
        }

    } finally {
        try {
            bos.close();
        } catch (Exception nope) {
            /* This exception doesn't matter */ }
    }
    decompressor.end();
    compressed = null;
    decompressor = null;
    byte[] result = bos.toByteArray();
    bos = null;
    return result;
}

From source file:servlets.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {//from  www. j av a 2s . com
        // URL decode
        // No need to URL decode: auto decoded by request.getParameter() method

        // Base64 decode
        Base64 base64Decoder = new Base64();
        byte[] xmlBytes = encodedRequestXmlString.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        //Uncompress the AuthnRequest data
        //First attempt to unzip the byte array according to DEFLATE (rfc 1951)
        try {

            Inflater inflater = new Inflater(true);
            inflater.setInput(base64DecodedByteArray);
            // since we are decompressing, it's impossible to know how much space we
            // might need; hopefully this number is suitably big
            byte[] xmlMessageBytes = new byte[5000];
            int resultLength = inflater.inflate(xmlMessageBytes);

            if (!inflater.finished()) {
                throw new RuntimeException("didn't allocate enough space to hold " + "decompressed data");
            }

            inflater.end();
            return new String(xmlMessageBytes, 0, resultLength, "UTF-8");

        } catch (DataFormatException e) {

            // if DEFLATE fails, then attempt to unzip the byte array according to
            // zlib (rfc 1950)      
            ByteArrayInputStream bais = new ByteArrayInputStream(base64DecodedByteArray);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InflaterInputStream iis = new InflaterInputStream(bais);
            byte[] buf = new byte[1024];
            int count = iis.read(buf);
            while (count != -1) {
                baos.write(buf, 0, count);
                count = iis.read(buf);
            }
            iis.close();
            return new String(baos.toByteArray());
        }

    } catch (UnsupportedEncodingException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    } catch (IOException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    }
}

From source file:org.apache.xmlgraphics.image.loader.impl.imageio.ImageLoaderImageIO.java

private ICC_Profile tryToExctractICCProfileFromPNGMetadataNode(Element pngNode) {
    ICC_Profile iccProf = null;//  www  . j ava2s .  c  o m
    Element iccpNode = ImageIOUtil.getChild(pngNode, "iCCP");
    if (iccpNode instanceof IIOMetadataNode) {
        IIOMetadataNode imn = (IIOMetadataNode) iccpNode;
        byte[] prof = (byte[]) imn.getUserObject();
        String comp = imn.getAttribute("compressionMethod");
        if ("deflate".equalsIgnoreCase(comp)) {
            Inflater decompresser = new Inflater();
            decompresser.setInput(prof);
            byte[] result = new byte[100];
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            boolean failed = false;
            while (!decompresser.finished() && !failed) {
                try {
                    int resultLength = decompresser.inflate(result);
                    bos.write(result, 0, resultLength);
                    if (resultLength == 0) {
                        // this means more data or an external dictionary is
                        // needed. Both of which are not available, so we
                        // fail.
                        log.debug("Failed to deflate ICC Profile");
                        failed = true;
                    }
                } catch (DataFormatException e) {
                    log.debug("Failed to deflate ICC Profile", e);
                    failed = true;
                }
            }
            decompresser.end();
            try {
                iccProf = ICC_Profile.getInstance(bos.toByteArray());
            } catch (IllegalArgumentException e) {
                log.debug("Failed to interpret embedded ICC Profile", e);
                iccProf = null;
            }
        }
    }
    return iccProf;
}

From source file:org.jwebsocket.util.Tools.java

/**
 * Inflate a byte array with Zip compression
 *
 * @param aCompressedData//  ww w . j  a  v a 2  s. c o m
 * @return
 * @throws Exception
 */
public static byte[] inflate(byte[] aCompressedData) throws Exception {
    Inflater lInflater = new Inflater();
    lInflater.setInput(aCompressedData);
    byte[] lOut = new byte[1024 * 1000 * 5];
    int lWritten = lInflater.inflate(lOut);
    byte[] lResult = new byte[lWritten];

    System.arraycopy(lOut, 0, lResult, 0, lWritten);

    return lResult;
}

From source file:auth.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {//  www.  j av a 2s  . c o  m
        // URL decode
        // No need to URL decode: auto decoded by request.getParameter() method

        // Base64 decode
        Base64 base64Decoder = new Base64();
        byte[] xmlBytes = encodedRequestXmlString.getBytes("UTF-8");
        byte[] base64DecodedByteArray = base64Decoder.decode(xmlBytes);

        //Uncompress the AuthnRequest data
        //First attempt to unzip the byte array according to DEFLATE (rfc 1951)
        try {

            Inflater inflater = new Inflater(true);
            inflater.setInput(base64DecodedByteArray);
            // since we are decompressing, it's impossible to know how much space we
            // might need; hopefully this number is suitably big
            byte[] xmlMessageBytes = new byte[5000];
            int resultLength = inflater.inflate(xmlMessageBytes);

            if (!inflater.finished()) {
                throw new RuntimeException("didn't allocate enough space to hold " + "decompressed data");
            }

            inflater.end();
            return new String(xmlMessageBytes, 0, resultLength, "UTF-8");

        } catch (DataFormatException e) {

            // if DEFLATE fails, then attempt to unzip the byte array according to
            // zlib (rfc 1950)
            ByteArrayInputStream bais = new ByteArrayInputStream(base64DecodedByteArray);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            InflaterInputStream iis = new InflaterInputStream(bais);
            byte[] buf = new byte[1024];
            int count = iis.read(buf);
            while (count != -1) {
                baos.write(buf, 0, count);
                count = iis.read(buf);
            }
            iis.close();
            return new String(baos.toByteArray());
        }

    } catch (UnsupportedEncodingException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    } catch (IOException e) {
        throw new SamlException("Error decoding AuthnRequest: " + "Check decoding scheme - " + e.getMessage());
    }
}

From source file:org.jasig.cas.client.session.SingleSignOutHandler.java

/**
 * Uncompress a logout message (base64 + deflate).
 * //w  w w .  j  a v a  2 s.com
 * @param originalMessage the original logout message.
 * @return the uncompressed logout message.
 */
private String uncompressLogoutMessage(final String originalMessage) {
    final byte[] binaryMessage = Base64.decodeBase64(originalMessage);

    Inflater decompresser = null;
    try {
        // decompress the bytes
        decompresser = new Inflater();
        decompresser.setInput(binaryMessage);
        final byte[] result = new byte[binaryMessage.length * DECOMPRESSION_FACTOR];

        final int resultLength = decompresser.inflate(result);

        // decode the bytes into a String
        return new String(result, 0, resultLength, "UTF-8");
    } catch (final Exception e) {
        logger.error("Unable to decompress logout message", e);
        throw new RuntimeException(e);
    } finally {
        if (decompresser != null) {
            decompresser.end();
        }
    }
}

From source file:de.btobastian.javacord.utils.DiscordWebsocketAdapter.java

@Override
public void onBinaryMessage(WebSocket websocket, byte[] binary) throws Exception {
    Inflater decompressor = new Inflater();
    decompressor.setInput(binary);
    ByteArrayOutputStream bos = new ByteArrayOutputStream(binary.length);
    byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        int count;
        try {//from  w ww  .j  av a  2  s .c o m
            count = decompressor.inflate(buf);
        } catch (DataFormatException e) {
            logger.warn("An error occurred while decompressing data", e);
            return;
        }
        bos.write(buf, 0, count);
    }
    try {
        bos.close();
    } catch (IOException ignored) {
    }
    byte[] decompressedData = bos.toByteArray();
    try {
        onTextMessage(websocket, new String(decompressedData, "UTF-8"));
    } catch (UnsupportedEncodingException e) {
        logger.warn("An error occurred while decompressing data", e);
    }
}