Example usage for java.util.zip Inflater end

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

Introduction

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

Prototype

public void end() 

Source Link

Document

Closes the decompressor and discards any unprocessed input.

Usage

From source file:auth.ProcessResponseServlet.java

private String decodeAuthnRequestXML(String encodedRequestXmlString) throws SamlException {
    try {/*from  w ww  . j  a  v  a  2s .  co 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).
 * //from  w w w  .jav  a 2s . c o  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:com.ctriposs.r2.filter.compression.DeflateCompressor.java

@Override
public byte[] inflate(InputStream data) throws CompressionException {
    byte[] input;
    try {/*ww  w. j a  va2  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:org.esupportail.publisher.security.CustomSingleSignOutHandler.java

/**
 * Uncompress a logout message (base64 + deflate).
 *
 * @param originalMessage the original logout message.
 * @return the uncompressed logout message.
 *//*w  w  w . jav a  2  s . co  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:net.dv8tion.jda.core.requests.WebSocketClient.java

@Override
public void onBinaryMessage(WebSocket websocket, byte[] binary)
        throws UnsupportedEncodingException, DataFormatException {
    //Thanks to ShadowLordAlpha for code and debugging.
    //Get the compressed message and inflate it
    StringBuilder builder = new StringBuilder();
    Inflater decompresser = new Inflater();
    decompresser.setInput(binary, 0, binary.length);
    byte[] result = new byte[128];
    while (!decompresser.finished()) {
        int resultLength = decompresser.inflate(result);
        builder.append(new String(result, 0, resultLength, "UTF-8"));
    }/*  www.  j  a  v a  2 s .  c o m*/
    decompresser.end();

    // send the inflated message to the TextMessage method
    onTextMessage(websocket, builder.toString());
}

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

private ICC_Profile tryToExctractICCProfileFromPNGMetadataNode(Element pngNode) {
    ICC_Profile iccProf = null;//from   ww  w.  j a  va 2 s.  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.zaproxy.zap.extension.ascanrulesAlpha.GitMetadata.java

/**
 * inflate the byte array, using the specified buffer size
 *
 * @param data the data to inflate//from  w w w . j  a  v  a2 s  .c om
 * @param buffersize the buffer size to use when inflating the data
 * @return the inflated data
 * @throws Exception
 */
protected byte[] inflate(byte[] data, int buffersize) throws Exception {
    Inflater inflater = new Inflater();
    inflater.setInput(data);

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
    byte[] buffer = new byte[buffersize];
    while (!inflater.finished()) {
        int count = inflater.inflate(buffer);
        outputStream.write(buffer, 0, count);
    }
    outputStream.close();
    inflater.end();
    return outputStream.toByteArray();
}

From source file:com.eryansky.common.utils.SysUtils.java

/**
  * /* w w  w .  j av a2  s . co m*/
  * 
  * @param in
  *            ?
  * @return 
  */
 public static String unZip_Str(byte[] in) {
     Inflater decompresser = new Inflater();
     decompresser.setInput(in);
     ArrayList<Byte> al = new ArrayList<Byte>();
     byte[] result;
     int count = 0;
     for (; !decompresser.finished();) {
         result = new byte[100];
         try {
             count += decompresser.inflate(result);
         } catch (DataFormatException e) {
             e.printStackTrace();
         }
         for (int i = 0; i < result.length; i++) {
             al.add(new Byte(result[i]));
         }
     }
     result = new byte[al.size()];
     for (int i = 0; i < al.size(); i++) {
         result[i] = (al.get(i)).byteValue();
     }
     decompresser.end();

     try {
         return new String(result, 0, count, "UTF-8");
     } catch (UnsupportedEncodingException e) {
         return "";
     }
 }

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 w w. ja  va2 s.  com*/

    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:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

/**
 * @param buf//  w  w  w.ja  va2s .  c  om
 * @return Uncompressed form.
 * @throws IOException
 */
public static byte[] inflate(byte[] buf) throws IOException {
    if (!DB_COMPRESSION)
        return buf;
    Inflater inflator = new Inflater();
    inflator.setInput(buf);
    byte[] decompressed = new byte[buf.length];
    ByteArrayOutputStream baos = new ByteArrayOutputStream(buf.length);
    try {
        while (!inflator.finished()) {
            int count = inflator.inflate(decompressed);
            if (count == 0)
                break;
            baos.write(decompressed, 0, count);
        }
        baos.close();
        inflator.end();
    } catch (DataFormatException e) {
        PaxosManager.getLogger()
                .severe("DataFormatException while decompressing buffer of length " + buf.length);
        e.printStackTrace();
        return buf;
    }
    return baos.toByteArray();
}