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: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);/*from w w w .  ja v  a2s  .  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.eclipsetrader.directa.internal.core.connector.BackfillConnector.java

protected void parseIntradayStream(BufferedInputStream in, List<OHLC> list) throws Exception {
    Calendar cal = Calendar.getInstance();

    int startTime = 9 * 60;
    int endTime = 17 * 60 + 25;
    ;//  w w w.  j a  va  2 s  .c  om

    byte[] buffer = new byte[1];
    while (in.read(buffer) == 1) {
        if (buffer[0] == '<') {
            StringBuilder sb = new StringBuilder();
            while (in.read(buffer) == 1) {
                if (buffer[0] == '>') {
                    break;
                }
                sb.append(new String(buffer));
            }
            String line = sb.toString();
            if (line.startsWith("GRA")) { //$NON-NLS-1$
                int s = line.indexOf("L=") + 2; //$NON-NLS-1$
                int e = line.indexOf(" ", s); //$NON-NLS-1$
                int uncompressLen = Integer.parseInt(line.substring(s, e));

                byte[] output = new byte[uncompressLen];
                boolean compressed = line.indexOf("LC=") != -1; //$NON-NLS-1$

                if (compressed) {
                    s = line.indexOf("LC=") + 3; //$NON-NLS-1$
                    e = line.indexOf(" ", s); //$NON-NLS-1$
                    int compressLen = Integer.parseInt(line.substring(s, e));

                    while (in.read(buffer) == 1) {
                        if (buffer[0] == 0x78) {
                            break;
                        }
                    }
                    if (buffer[0] != 0x78) {
                        break;
                    }

                    int readed = 1, len;
                    byte[] input = new byte[compressLen];
                    input[0] = buffer[0];
                    do {
                        len = in.read(input, readed, input.length - readed);
                        readed += len;
                    } while (len > 0 && readed < input.length);

                    Inflater infl = new Inflater();
                    infl.setInput(input, 0, readed);
                    infl.inflate(output);
                    infl.end();
                } else {
                    in.read(buffer);

                    int readed = 0, len;
                    do {
                        len = in.read(output, readed, output.length - readed);
                        readed += len;
                    } while (len > 0 && readed < output.length);
                }

                for (int i = 0; i < output.length; i += 28) {
                    Date date = getDate(output, i);
                    cal.setTime(date);
                    int time = cal.get(Calendar.HOUR_OF_DAY) * 60 + cal.get(Calendar.MINUTE);
                    if (time >= startTime && time <= endTime) {
                        float low = getFloat(output, i + 8);
                        float high = getFloat(output, i + 12);
                        float close = getFloat(output, i + 16);
                        float volume = getFloat(output, i + 20);
                        float open = getFloat(output, i + 24);
                        list.add(new OHLC(date, (double) open, (double) high, (double) low, (double) close,
                                (long) volume));
                    }
                }
            }
        }
    }
}

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

public static String getBlobAsString(Blob blob, String column, String charset, boolean xmlEncode,
        boolean blobIsCompressed, boolean blobSmartGet, boolean encodeBlobBase64)
        throws IOException, JdbcException, SQLException, JMSException {
    if (encodeBlobBase64) {
        InputStream blobStream = JdbcUtil.getBlobInputStream(blob, column, blobIsCompressed);
        return Misc.streamToString(new Base64InputStream(blobStream, true), null, false);
    }//w  w  w  . j ava2  s.c  o  m
    if (blobSmartGet) {
        if (blob == null) {
            log.debug("no blob found in column [" + column + "]");
            return null;
        }
        int bl = (int) blob.length();

        InputStream is = blob.getBinaryStream();
        byte[] buf = new byte[bl];
        int bl1 = is.read(buf);

        Inflater decompressor = new Inflater();
        decompressor.setInput(buf);
        ByteArrayOutputStream bos = new ByteArrayOutputStream(buf.length);
        byte[] bufDecomp = new byte[1024];
        boolean decompresOK = true;
        while (!decompressor.finished()) {
            try {
                int count = decompressor.inflate(bufDecomp);
                if (count == 0) {
                    break;
                }
                bos.write(bufDecomp, 0, count);
            } catch (DataFormatException e) {
                log.debug("message in column [" + column + "] is not compressed");
                decompresOK = false;
                break;
            }
        }
        bos.close();
        if (decompresOK)
            buf = bos.toByteArray();

        Object result = null;
        ObjectInputStream ois = null;
        boolean objectOK = true;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(buf);
            ois = new ObjectInputStream(bis);
            result = ois.readObject();
        } catch (Exception e) {
            log.debug("message in column [" + column + "] is probably not a serialized object: "
                    + e.getClass().getName());
            objectOK = false;
        }
        if (ois != null)
            ois.close();

        String rawMessage;
        if (objectOK) {
            if (result instanceof IMessageWrapper) {
                rawMessage = ((IMessageWrapper) result).getText();
            } else if (result instanceof TextMessage) {
                rawMessage = ((TextMessage) result).getText();
            } else {
                rawMessage = (String) result;
            }
        } else {
            rawMessage = new String(buf, charset);
        }

        String message = XmlUtils.encodeCdataString(rawMessage);
        return message;
    }
    return Misc.readerToString(getBlobReader(blob, column, charset, blobIsCompressed), null, xmlEncode);
}

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

/**
 * Uncompress a logout message (base64 + deflate).
 * /*w w  w  . j ava 2s. co  m*/
 * @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:org.esupportail.publisher.security.CustomSingleSignOutHandler.java

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

    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:MSUmpire.SpectrumParser.mzXMLReadUnit.java

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

    Inflater decompressor = new Inflater();
    decompressor.setInput(compressed);//from w  w  w  .  j  a  v  a  2 s.  co m

    ByteArrayOutputStream bos = null;
    try {

        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: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 .j av a  2s.c  om*/

    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);
    }
}

From source file:servlets.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {/*ww  w  .  j a  va 2  s . 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:de.btobastian.javacord.utils.DiscordWebsocketAdapter.java

@Override
public void onBinaryMessage(WebSocket websocket, byte[] binary) throws Exception {
    Inflater decompressor = new Inflater();
    decompressor.setInput(binary);//from   w  w  w  .ja v a 2 s  .  c om
    ByteArrayOutputStream bos = new ByteArrayOutputStream(binary.length);
    byte[] buf = new byte[1024];
    while (!decompressor.finished()) {
        int count;
        try {
            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);
    }
}

From source file:auth.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {/*  ww  w.  ja v  a2s .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());
    }
}