Example usage for java.util.zip Inflater Inflater

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

Introduction

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

Prototype

public Inflater(boolean nowrap) 

Source Link

Document

Creates a new decompressor.

Usage

From source file:org.wso2.carbon.identity.saml.inbound.util.SAMLSSOUtil.java

/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq/*  w ww .ja v a  2 s  .c  o  m*/
 * @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(StandardCharsets.UTF_8.name());
        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.finished()) {
                throw new RuntimeException("End of the compressed data stream has NOT been reached");
            }

            inflater.end();
            String decodedString = new String(xmlMessageBytes, 0, resultLength, StandardCharsets.UTF_8.name());
            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 IdentityException.error("Error when decoding the SAML Request.", e);
    }

}

From source file:org.owasp.webscarab.plugin.saml.SamlModel.java

public String getDecodedSAMLMessage(String encodedSamlMessage, ConversationID id) {
    /*/* w  ww .j  a  v  a 2  s  .c o m*/
     * Cannot use org.owasp.webscarab.util.Encoding here as SAML tickets not
     * always come with line-breaks.
     */

    String deflate = this.model.getConversationProperty(id, "SAML-DEFLATE");
    if (null != deflate) {
        _logger.fine("inflating SAML message");
        byte[] deflated = Base64.decodeBase64(encodedSamlMessage);
        try {
            Inflater inflater = new Inflater(true);
            InflaterInputStream inflaterInputStream = new InflaterInputStream(
                    new ByteArrayInputStream(deflated), inflater);
            return new String(IOUtils.toByteArray(inflaterInputStream));
        } catch (IOException ex) {
            return "[ERROR INFLATING SAML MESSAGE]: " + ex.getMessage();
        }
    }

    String decodedSamlMessage = new String(Base64.decodeBase64(encodedSamlMessage));

    return decodedSamlMessage;
}

From source file:cn.code.notes.gtask.remote.GTaskClient.java

private String getResponseContent(HttpEntity entity) throws IOException {
    String contentEncoding = null;
    if (entity.getContentEncoding() != null) {
        contentEncoding = entity.getContentEncoding().getValue();
        Log.d(TAG, "encoding: " + contentEncoding);
    }// w w w. j  a v a 2 s. co m

    InputStream input = entity.getContent();
    if (contentEncoding != null && contentEncoding.equalsIgnoreCase("gzip")) {
        input = new GZIPInputStream(entity.getContent());
    } else if (contentEncoding != null && contentEncoding.equalsIgnoreCase("deflate")) {
        Inflater inflater = new Inflater(true);
        input = new InflaterInputStream(entity.getContent(), inflater);
    }

    try {
        InputStreamReader isr = new InputStreamReader(input);
        BufferedReader br = new BufferedReader(isr);
        StringBuilder sb = new StringBuilder();

        while (true) {
            String buff = br.readLine();
            if (buff == null) {
                return sb.toString();
            }
            sb = sb.append(buff);
        }
    } finally {
        input.close();
    }
}

From source file:org.wso2.carbon.identity.auth.saml2.common.SAML2AuthUtils.java

public static String decodeForRedirect(String encodedStr) throws IdentityRuntimeException {
    try {// w w w  .j  av a 2 s.c o m
        if (logger.isDebugEnabled()) {
            logger.debug(" >> encoded string in the SSOUtils/decode : " + encodedStr);
        }
        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 {
            //TODO if the request came in POST, inflating is wrong
            Inflater inflater = new Inflater(true);
            inflater.setInput(base64DecodedByteArray);
            byte[] xmlMessageBytes = new byte[5000];
            int resultLength = inflater.inflate(xmlMessageBytes);

            if (!inflater.finished()) {
                throw new RuntimeException("End of the compressed data stream has NOT been reached");
            }

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

        } catch (DataFormatException e) {
            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();
            String decodedStr = new String(baos.toByteArray(), Charset.forName("UTF-8"));
            if (logger.isDebugEnabled()) {
                logger.debug("Request message " + decodedStr);
            }
            return decodedStr;
        }
    } catch (IOException e) {
        throw new IdentityRuntimeException("Error when decoding the SAML Request.", e);
    }
}

From source file:de.jetwick.snacktory.HtmlFetcher.java

public String fetchAsString(String urlAsString, int timeout, boolean includeSomeGooseOptions)
        throws MalformedURLException, IOException {
    urlAsString = urlAsString.replace("https", "http");
    CloseableHttpResponse response = createUrlConnection(urlAsString, timeout, includeSomeGooseOptions, false);
    if (response.getStatusLine().getStatusCode() > 399) {
        throw new MalformedURLException(response.getStatusLine().toString());
    }/*from w  w  w .  j av  a2 s .c  o  m*/
    Header header = response.getFirstHeader("Content-Type");
    String encoding = null;
    if (header == null) {
        encoding = "utf-8";
    } else {
        encoding = header.getValue();
        if (encoding == null || !encoding.startsWith("text")) {
            throw new MalformedURLException("Not an HTML content!");
        }
    }
    String res = null;
    try {
        final HttpEntity body = response.getEntity();
        InputStream is;
        if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
            is = new GZIPInputStream(body.getContent());
        } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
            is = new InflaterInputStream(body.getContent(), new Inflater(true));
        } else {
            is = body.getContent();
        }

        String enc = Converter.extractEncoding(encoding);
        res = createConverter(urlAsString).streamToString(is, enc);
        EntityUtils.consume(body);

        if (logger.isDebugEnabled())
            logger.debug(res.length() + " FetchAsString:" + urlAsString);
    } finally {
        response.close();
    }
    return res;
}

From source file:org.atricore.idbus.capabilities.sso.main.binding.SamlR2HttpRedirectBinding.java

public static String inflateFromRedirect(String redirStr, boolean decode) throws Exception {

    if (redirStr == null || redirStr.length() == 0) {
        throw new RuntimeException("Redirect string cannot be null or empty");
    }/*from  ww  w  .j av  a2 s.c  o  m*/

    byte[] redirBin = null;
    if (decode)
        redirBin = new Base64().decode(removeNewLineChars(redirStr).getBytes());
    else
        redirBin = redirStr.getBytes();

    // Decompress the bytes
    Inflater inflater = new Inflater(true);
    inflater.setInput(redirBin);

    ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);

    try {
        int resultLength = 0;
        int buffSize = 1024;
        byte[] buff = new byte[buffSize];
        while (!inflater.finished()) {
            resultLength = inflater.inflate(buff);
            baos.write(buff, 0, resultLength);
        }

    } catch (DataFormatException e) {
        throw new RuntimeException("Cannot inflate SAML message : " + e.getMessage(), e);
    }

    inflater.end();

    // Decode the bytes into a String
    String outputString = null;
    try {
        outputString = new String(baos.toByteArray(), "UTF-8");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Cannot convert byte array to string " + e.getMessage(), e);
    }
    return outputString;
}

From source file:org.apache.hadoop.mapred.TestConcatenatedCompressedInput.java

/**
 * Test using the raw Inflater codec for reading gzip files.
 *//*w  ww  . j  av  a 2  s  .co m*/
@Test
public void testPrototypeInflaterGzip() throws IOException {
    CompressionCodec gzip = new GzipCodec(); // used only for file extension
    localFs.delete(workDir, true); // localFs = FileSystem instance

    System.out.println(COLOR_BR_BLUE + "testPrototypeInflaterGzip() using "
            + "non-native/Java Inflater and manual gzip header/trailer parsing" + COLOR_NORMAL);

    // copy prebuilt (correct!) version of concat.gz to HDFS
    final String fn = "concat" + gzip.getDefaultExtension();
    Path fnLocal = new Path(System.getProperty("test.concat.data", "/tmp"), fn);
    Path fnHDFS = new Path(workDir, fn);
    localFs.copyFromLocalFile(fnLocal, fnHDFS);

    final FileInputStream in = new FileInputStream(fnLocal.toString());
    assertEquals("concat bytes available", 148, in.available());

    // should wrap all of this header-reading stuff in a running-CRC wrapper
    // (did so in BuiltInGzipDecompressor; see below)

    byte[] compressedBuf = new byte[256];
    int numBytesRead = in.read(compressedBuf, 0, 10);
    assertEquals("header bytes read", 10, numBytesRead);
    assertEquals("1st byte", 0x1f, compressedBuf[0] & 0xff);
    assertEquals("2nd byte", 0x8b, compressedBuf[1] & 0xff);
    assertEquals("3rd byte (compression method)", 8, compressedBuf[2] & 0xff);

    byte flags = (byte) (compressedBuf[3] & 0xff);
    if ((flags & 0x04) != 0) { // FEXTRA
        numBytesRead = in.read(compressedBuf, 0, 2);
        assertEquals("XLEN bytes read", 2, numBytesRead);
        int xlen = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
        in.skip(xlen);
    }
    if ((flags & 0x08) != 0) { // FNAME
        while ((numBytesRead = in.read()) != 0) {
            assertFalse("unexpected end-of-file while reading filename", numBytesRead == -1);
        }
    }
    if ((flags & 0x10) != 0) { // FCOMMENT
        while ((numBytesRead = in.read()) != 0) {
            assertFalse("unexpected end-of-file while reading comment", numBytesRead == -1);
        }
    }
    if ((flags & 0xe0) != 0) { // reserved
        assertTrue("reserved bits are set??", (flags & 0xe0) == 0);
    }
    if ((flags & 0x02) != 0) { // FHCRC
        numBytesRead = in.read(compressedBuf, 0, 2);
        assertEquals("CRC16 bytes read", 2, numBytesRead);
        int crc16 = ((compressedBuf[1] << 8) | compressedBuf[0]) & 0xffff;
    }

    // ready to go!  next bytes should be start of deflated stream, suitable
    // for Inflater
    numBytesRead = in.read(compressedBuf);

    // Inflater docs refer to a "dummy byte":  no clue what that's about;
    // appears to work fine without one
    byte[] uncompressedBuf = new byte[256];
    Inflater inflater = new Inflater(true);

    inflater.setInput(compressedBuf, 0, numBytesRead);
    try {
        int numBytesUncompressed = inflater.inflate(uncompressedBuf);
        String outString = new String(uncompressedBuf, 0, numBytesUncompressed, "UTF-8");
        System.out.println("uncompressed data of first gzip member = [" + outString + "]");
    } catch (java.util.zip.DataFormatException ex) {
        throw new IOException(ex.getMessage());
    }

    in.close();
}

From source file:jfs.sync.encryption.JFSEncryptedStream.java

/**
 * /*from   w  w w  . jav  a2  s  .c om*/
 * @param fis
 * @param expectedLength
 *            length to be expected or -2 if you don't want the check
 * @param cipher
 * @return
 */
public static InputStream createInputStream(InputStream fis, long expectedLength, Cipher cipher) {
    try {
        InputStream in = fis;
        ObjectInputStream ois = new ObjectInputStream(in);
        byte marker = readMarker(ois);
        long l = readLength(ois);
        if (log.isDebugEnabled()) {
            log.debug(
                    "JFSEncryptedStream.createInputStream() length check " + expectedLength + " == " + l + "?");
        } // if
        if (expectedLength != DONT_CHECK_LENGTH) {
            if (l != expectedLength) {
                log.error("JFSEncryptedStream.createInputStream() length check failed");
                return null;
            } // if
        } // if
        if (cipher == null) {
            log.error("JFSEncryptedStream.createInputStream() no cipher for length " + expectedLength);
        } else {
            in = new CipherInputStream(in, cipher);
        } // if
        if (marker == COMPRESSION_DEFLATE) {
            Inflater inflater = new Inflater(true);
            in = new InflaterInputStream(in, inflater, COMPRESSION_BUFFER_SIZE);
        } // if
        if (marker == COMPRESSION_BZIP2) {
            in = new BZip2CompressorInputStream(in);
        } // if
        if (marker == COMPRESSION_LZMA) {
            Decoder decoder = new Decoder();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

            byte[] properties = new byte[5];
            int readBytes = in.read(properties, 0, properties.length);
            boolean result = decoder.SetDecoderProperties(properties);
            if (log.isDebugEnabled()) {
                log.debug("JFSEncryptedStream.createInputStream() readBytes=" + readBytes);
                log.debug("JFSEncryptedStream.createInputStream() result=" + result);
            } // if

            decoder.Code(in, outputStream, l);
            in.close();
            outputStream.close();
            if (log.isDebugEnabled()) {
                log.debug("JFSEncryptedStream.createInputStream() " + outputStream.size());
            } // if
            in = new ByteArrayInputStream(outputStream.toByteArray());
        } // if
        return in;
    } catch (IOException ioe) {
        log.error("JFSEncryptedStream.createInputStream() I/O Exception " + ioe.getLocalizedMessage());
        return null;
    } // try/catch
}

From source file:org.xlcloud.console.saml2.Saml2ServiceProviderConsumerServlet.java

private byte[] inflate(byte[] responseBytes) throws IOException {
    Inflater inflater = new Inflater(true);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    InflaterOutputStream ios = new InflaterOutputStream(out, inflater);

    ios.write(responseBytes);// w w w.  java2s.c o m
    ios.close();
    return out.toByteArray();
}

From source file:org.wso2.identity.integration.test.requestPathAuthenticator.RequestPathAuthenticatorTestCase.java

/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq// w  w w . ja v  a2 s . c  o  m
 * @return decoded AuthReq
 */
private static String decode(String encodedStr) {
    try {
        Base64 base64Decoder = new Base64();
        byte[] xmlBytes = encodedStr.getBytes(DEFAULT_CHARSET);
        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.finished()) {
                throw new RuntimeException("End of the compressed data stream has NOT been reached");
            }

            inflater.end();
            String decodedString = new String(xmlMessageBytes, 0, resultLength, (DEFAULT_CHARSET));
            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);

            return decodedStr;
        }
    } catch (IOException e) {
        Assert.fail("Error while decoding SAML response");
        return "";
    }
}