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:de.hofuniversity.iisys.neo4j.websock.query.encoding.safe.TSafeDeflateJsonQueryHandler.java

@Override
public boolean willDecode(ByteBuffer buff) {
    boolean valid = true;

    //TODO: actually check whether it's a query
    try {/*from  ww w  .ja v  a2s.  c o  m*/
        //decompress
        final Inflater inflater = new Inflater(true);
        inflater.setInput(buff.array());

        int read = 0;
        int totalSize = 0;
        final List<byte[]> buffers = new LinkedList<byte[]>();

        byte[] buffer = new byte[BUFFER_SIZE];
        read = inflater.inflate(buffer);
        while (read > 0) {
            totalSize += read;
            buffers.add(buffer);
            buffer = new byte[BUFFER_SIZE];
            read = inflater.inflate(buffer);
        }

        final byte[] data = fuse(buffers, totalSize).array();
        new JSONObject(new String(data));
    } catch (Exception e) {
        valid = false;
    }

    return valid;
}

From source file:org.nuxeo.opensocial.shindig.gadgets.NXHttpFetcher.java

/**
 * @param httpMethod// w  w  w  .  j  av a 2  s.co m
 * @param responseCode
 * @return A HttpResponse object made by consuming the response of the given
 *         HttpMethod.
 * @throws java.io.IOException
 */
private HttpResponse makeResponse(HttpMethod httpMethod, int responseCode) throws IOException {
    Map<String, String> headers = Maps.newHashMap();

    if (httpMethod.getResponseHeaders() != null) {
        for (Header h : httpMethod.getResponseHeaders()) {
            headers.put(h.getName(), h.getValue());
        }
    }

    // The first header is always null here to provide the response body.
    headers.remove(null);

    // Find the response stream - the error stream may be valid in cases
    // where the input stream is not.
    InputStream responseBodyStream = null;
    try {
        responseBodyStream = httpMethod.getResponseBodyAsStream();
    } catch (IOException e) {
        // normal for 401, 403 and 404 responses, for example...
    }

    if (responseBodyStream == null) {
        // Fall back to zero length response.
        responseBodyStream = new ByteArrayInputStream(ArrayUtils.EMPTY_BYTE_ARRAY);
    }

    String encoding = headers.get("Content-Encoding");

    // Create the appropriate stream wrapper based on the encoding type.
    InputStream is = responseBodyStream;
    if (encoding == null) {
        is = responseBodyStream;
    } else if (encoding.equalsIgnoreCase("gzip")) {
        is = new GZIPInputStream(responseBodyStream);
    } else if (encoding.equalsIgnoreCase("deflate")) {
        Inflater inflater = new Inflater(true);
        is = new InflaterInputStream(responseBodyStream, inflater);
    }

    ByteArrayOutputStream output = new ByteArrayOutputStream();
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    int totalBytesRead = 0;
    int currentBytesRead;

    while ((currentBytesRead = is.read(buffer)) != -1) {
        output.write(buffer, 0, currentBytesRead);
        totalBytesRead += currentBytesRead;

        if (maxObjSize > 0 && totalBytesRead > maxObjSize) {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(output);
            // Exceeded max # of bytes
            return HttpResponse.badrequest("Exceeded maximum number of bytes - " + this.maxObjSize);
        }
    }

    return new HttpResponseBuilder().setHttpStatusCode(responseCode).setResponse(output.toByteArray())
            .addHeaders(headers).create();
}

From source file:it.greenvulcano.util.zip.ZipHelper.java

/**
 * Uncompress the input buffer.//from  w  ww  . ja v  a  2 s. c o m
 *
 * @param input
 *        the data to uncompress
 * @return the uncompressed data
 * @throws ZipHelperException
 *         if error occurs
 */
public byte[] unzip(byte[] input) throws ZipHelperException {
    try {
        if (decompresser == null) {
            decompresser = new Inflater(true);
        }

        byte[] output = new byte[DEFAULT_SIZE];
        ByteArrayOutputStream outstream = new ByteArrayOutputStream(input.length);
        decompresser.setInput(input);
        while (!decompresser.needsInput()) {
            int decompressedDataLength = decompresser.inflate(output, 0, output.length);
            if (decompressedDataLength > 0) {
                outstream.write(output, 0, decompressedDataLength);
            }
        }
        return outstream.toByteArray();
    } catch (Exception exc) {
        throw new ZipHelperException("Error occurred decompressing data: " + exc.getMessage(), exc);
    } finally {
        if (decompresser != null) {
            decompresser.reset();
        }
    }
}

From source file:fr.free.movierenamer.utils.URIRequest.java

private static InputStream getInputStreamNoSync(URLConnection connection) throws IOException {
    String encoding = connection.getContentEncoding();
    InputStream inputStream;// w  ww . j a  v  a  2s. com
    try {
        inputStream = connection.getInputStream();
    } catch (IOException ioe) {
        throw ioe;
    }

    if ("gzip".equalsIgnoreCase(encoding)) {
        inputStream = new GZIPInputStream(inputStream);
    } else if ("deflate".equalsIgnoreCase(encoding)) {
        inputStream = new InflaterInputStream(inputStream, new Inflater(true));
    }

    return inputStream;
}

From source file:com.kactech.otj.Utils.java

public static byte[] zlibDecompress(byte[] data) throws IOException, DataFormatException {
    Inflater inflater = new Inflater(false);

    inflater.setInput(data);/*  ww  w.j ava  2 s.c om*/

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length);
    byte[] buffer = new byte[1024];
    while (!inflater.finished()) {
        int count = inflater.inflate(buffer);
        if (count == 0)
            throw new DataFormatException("probably bad, has infinite loop at encoded message");
        outputStream.write(buffer, 0, count);
    }
    outputStream.close();
    byte[] output = outputStream.toByteArray();

    return output;
}

From source file:com.qut.middleware.esoe.sso.plugins.redirect.handler.impl.RedirectLogicImpl.java

private AuthnRequest getRedirectRequest(SSOProcessorData data, RedirectBindingData bindingData)
        throws RedirectBindingException {
    InflaterInputStream inflaterStream = null;
    ByteArrayOutputStream inflatedByteStream = null;
    byte[] chunk = new byte[TMP_BUFFER_SIZE];

    boolean signed = (bindingData.getSignature() != null && bindingData.getSignature().length() > 0);

    SSOProcessor ssoProcessor = data.getSSOProcessor();
    String remoteAddress = data.getRemoteAddress();

    try {//from   w  ww  . j a va  2 s .co m
        if (bindingData.getSAMLRequestString() == null || bindingData.getSAMLRequestString().length() <= 0) {
            ssoProcessor.createStatusAuthnResponse(data, StatusCodeConstants.requester, null,
                    "No AuthnRequest document was supplied to the Redirect binding.", true);
            this.logger.error(
                    "[SSO for {}] Redirect binding failed: No AuthnRequest document was supplied in the request.",
                    remoteAddress);
            throw new RedirectBindingException(
                    "Redirect binding failed as no AuthnRequest document was supplied in the request.");
        }

        if (bindingData.getRequestEncoding() != null
                && !bindingData.getRequestEncoding().equals(BindingConstants.deflateEncoding)) {
            ssoProcessor.createStatusAuthnResponse(data, StatusCodeConstants.requester, null,
                    "The given SAML Request encoding is not supported in this implementation.", true);
            this.logger.error(
                    "[SSO for {}] Redirect binding failed: SAML Request encoding '{}' is not supported in the current implementation.",
                    new Object[] { remoteAddress, bindingData.getRequestEncoding() });
            throw new RedirectBindingException(
                    "Redirect binding failed as the given SAML Request encoding is not supported in the current implementation.");
        }

        if (bindingData.getSignature() != null) {
            ssoProcessor.createStatusAuthnResponse(data, StatusCodeConstants.requester, null,
                    "Signed Redirect binding documents are not supported in this implementation.", true);
            this.logger.error(
                    "[SSO for {}] Redirect binding failed: Signed Redirect binding documents are not supported in the current implementation.",
                    remoteAddress);
            throw new RedirectBindingException(
                    "Redirect binding failed as Signed Redirect binding documents are not supported in the current implementation.");
        }
    } catch (SSOException e) {
        this.logger.error("[SSO for {}] Redirect binding failed to generate an error response. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        throw new RedirectBindingException(
                "Redirect binding failed to generate an error reponse. Original error follows", e);
    }

    try {
        /*
         * Retrieves the AuthnRequest from the encoded and compressed String extracted from the request of SAML HTTP
         * Redirect. The AuthnRequest XML is retrieved in the following order: 1. Base64 decode, 2. Inflate
         */
        byte[] decodedBytes = Base64.decodeBase64(bindingData.getSAMLRequestString().getBytes());
        ByteArrayInputStream decodedByteStream = new ByteArrayInputStream(decodedBytes);
        inflaterStream = new InflaterInputStream(decodedByteStream, new Inflater(true));
        inflatedByteStream = new ByteArrayOutputStream();

        int writeCount = 0;
        int count = 0;
        // Inflate and dump in the output stream to build a byte array.
        while ((count = inflaterStream.read(chunk)) >= 0) {
            inflatedByteStream.write(chunk, 0, count);
            writeCount = writeCount + count;
        }

        byte[] samlRequestDocument = inflatedByteStream.toByteArray();

        AuthnRequest authnRequest = ssoProcessor.unmarshallRequest(samlRequestDocument, signed);
        this.logger.debug("[SSO for {}] AuthnRequest was unmarshalled successfully by the SSO Processor",
                remoteAddress);

        return authnRequest;
    } catch (IOException e) {
        this.logger.error(
                "[SSO for {}] IO exception occurred while inflating the request document. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        throw new RedirectBindingException("IO exception occurred while inflating the request document.");
    } catch (SignatureValueException e) {
        this.logger.error(
                "[SSO for {}] Signature value exception occurred while trying to unmarshal the redirect request. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        this.logger.debug(
                "[SSO for {}] Signature value exception occurred while trying to unmarshal the redirect request. Exception follows",
                remoteAddress, e);
        throw new RedirectBindingException(
                "Signature value exception occurred while trying to unmarshal the redirect request.");
    } catch (ReferenceValueException e) {
        this.logger.error(
                "[SSO for {}] Reference value exception occurred while unmarshalling the redirect request. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        this.logger.debug(
                "[SSO for {}] Reference value exception occurred while unmarshalling the redirect request. Exception follows",
                remoteAddress, e);
        throw new RedirectBindingException(
                "Reference value exception occurred while unmarshalling the redirect request.");
    } catch (UnmarshallerException e) {
        this.logger.error(
                "[SSO for {}] Unmarshaller exception occurred while unmarshalling the redirect request. Error was: {}",
                new Object[] { remoteAddress, e.getMessage() });
        this.logger.debug(
                "[SSO for {}] Unmarshaller exception occurred while unmarshalling the redirect request. Exception follows",
                remoteAddress, e);
        throw new RedirectBindingException(
                "Unmarshaller exception occurred while unmarshalling the redirect request.");
    } finally {
        try {
            if (inflatedByteStream != null) {
                inflatedByteStream.reset();
                inflatedByteStream.close();
            }

            if (inflaterStream != null)
                inflaterStream.close();
        } catch (IOException e) {
            this.logger.error("Unable to close stream correctly - " + e.getLocalizedMessage());
            this.logger.debug(e.getLocalizedMessage(), e);
        }
    }
}

From source file:org.jasig.cas.authentication.principal.GoogleAccountsService.java

private static String inflate(final byte[] bytes) {
    final Inflater inflater = new Inflater(true);
    final byte[] xmlMessageBytes = new byte[10000];

    final byte[] extendedBytes = new byte[bytes.length + 1];
    System.arraycopy(bytes, 0, extendedBytes, 0, bytes.length);
    extendedBytes[bytes.length] = 0;/*from   www.  jav  a2  s.  c o m*/

    inflater.setInput(extendedBytes);

    try {
        final int resultLength = inflater.inflate(xmlMessageBytes);
        inflater.end();

        if (!inflater.finished()) {
            throw new RuntimeException("buffer not large enough.");
        }

        inflater.end();
        return new String(xmlMessageBytes, 0, resultLength, "UTF-8");
    } catch (final DataFormatException e) {
        return null;
    } catch (final UnsupportedEncodingException e) {
        throw new RuntimeException("Cannot find encoding: UTF-8", e);
    }
}

From source file:org.wso2.carbon.identity.application.authenticator.samlsso.util.SSOUtils.java

/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq/*w ww.  j  ava 2  s  .  com*/
 * @return decoded AuthReq
 */
public static String decode(String encodedStr) throws SAMLSSOException {
    try {
        if (log.isDebugEnabled()) {
            log.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.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 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 (log.isDebugEnabled()) {
                log.debug("Request message " + decodedStr);
            }
            return decodedStr;
        }
    } catch (IOException e) {
        throw new SAMLSSOException("Error when decoding the SAML Request.", e);
    }

}

From source file:org.socraticgrid.workbench.security.wso2.Saml2Util.java

/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq/*  www.  j a va 2s . c o m*/
 * @return decoded AuthReq
 */
public static String decode(String encodedStr) throws Exception {
    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.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) {
            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());
            return decodedStr;
        }
    } catch (IOException e) {
        throw new Exception("Error when decoding the SAML Request.", e);
    }

}