Example usage for java.util.zip InflaterInputStream InflaterInputStream

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

Introduction

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

Prototype

public InflaterInputStream(InputStream in, Inflater inf) 

Source Link

Document

Creates a new input stream with the specified decompressor and a default buffer size.

Usage

From source file:com.nesscomputing.httpclient.response.ContentResponseHandler.java

/**
 * Processes the client response.//from   www.ja v a 2  s .  com
 */
@Override
public T handle(final HttpClientResponse response) throws IOException {
    if (allowRedirect && response.isRedirected()) {
        LOG.debug("Redirecting based on '%d' response code", response.getStatusCode());
        throw new RedirectedException(response);
    } else {
        // Find the response stream - the error stream may be valid in cases
        // where the input stream is not.
        InputStream is = null;
        try {
            is = response.getResponseBodyAsStream();
        } catch (IOException e) {
            LOG.warnDebug(e, "Could not locate response body stream");
            // normal for 401, 403 and 404 responses, for example...
        }

        if (is == null) {
            // Fall back to zero length response.
            is = new NullInputStream(0);
        }

        try {
            final Long contentLength = response.getContentLength();

            if (maxBodyLength > 0) {
                if (contentLength != null && contentLength > maxBodyLength) {
                    throw new SizeExceededException("Content-Length: " + contentLength);
                }

                LOG.debug("Limiting stream length to '%d'", maxBodyLength);
                is = new SizeLimitingInputStream(is, maxBodyLength);
            }

            final String encoding = StringUtils.trimToEmpty(response.getHeader("Content-Encoding"));

            if (StringUtils.equalsIgnoreCase(encoding, "lz4")) {
                LOG.debug("Found LZ4 stream");
                is = new LZ4BlockInputStream(is);
            } else if (StringUtils.equalsIgnoreCase(encoding, "gzip")
                    || StringUtils.equalsIgnoreCase(encoding, "x-gzip")) {
                LOG.debug("Found GZIP stream");
                is = new GZIPInputStream(is);
            } else if (StringUtils.equalsIgnoreCase(encoding, "deflate")) {
                LOG.debug("Found deflate stream");
                final Inflater inflater = new Inflater(true);
                is = new InflaterInputStream(is, inflater);
            }

            return contentConverter.convert(response, is);
        } catch (IOException ioe) {
            return contentConverter.handleError(response, ioe);
        }
    }
}

From source file:com.adamrosenfield.wordswithcrosses.versions.DefaultUtil.java

private void downloadHelper(URL url, String scrubbedUrl, Map<String, String> headers, HttpContext httpContext,
        OutputStream output) throws IOException {
    HttpGet httpget;//from w w  w  .  java 2 s .  c om
    try {
        httpget = new HttpGet(url.toURI());
    } catch (URISyntaxException e) {
        e.printStackTrace();
        throw new IOException("Invalid URL: " + url);
    }

    httpget.setHeader("Accept-Encoding", "gzip, deflate");
    for (Entry<String, String> e : headers.entrySet()) {
        httpget.setHeader(e.getKey(), e.getValue());
    }

    HttpResponse response = mHttpClient.execute(httpget, httpContext);

    int status = response.getStatusLine().getStatusCode();
    HttpEntity entity = response.getEntity();

    if (status != 200) {
        LOG.warning("Download failed: " + scrubbedUrl + " status=" + status);
        if (entity != null) {
            entity.consumeContent();
        }

        throw new HTTPException(status);
    }

    if (entity != null) {
        // If we got a compressed entity, create the proper decompression
        // stream wrapper
        InputStream content = entity.getContent();
        Header contentEncoding = entity.getContentEncoding();
        if (contentEncoding != null) {
            if ("gzip".equals(contentEncoding.getValue())) {
                content = new GZIPInputStream(content);
            } else if ("deflate".equals(contentEncoding.getValue())) {
                content = new InflaterInputStream(content, new Inflater(true));
            }
        }

        try {
            IO.copyStream(content, output);
        } finally {
            entity.consumeContent();
        }
    }
}

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

/**
 * @param httpMethod// w  ww.  j a v  a 2 s  .  c  om
 * @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:fr.free.movierenamer.utils.URIRequest.java

private static InputStream getInputStreamNoSync(URLConnection connection) throws IOException {
    String encoding = connection.getContentEncoding();
    InputStream inputStream;// w w w  . jav  a  2 s  .co m
    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.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 {//w ww.  ja  v a  2  s. c om
        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.apache.fop.render.pdf.ImageRawPNGAdapter.java

/** {@inheritDoc} */
public void outputContents(OutputStream out) throws IOException {
    InputStream in = ((ImageRawStream) image).createInputStream();

    try {//  w  ww .j a va2 s. com
        if (numberOfInterleavedComponents == 1 || numberOfInterleavedComponents == 3) {
            // means we have Gray, RGB, or Palette
            IOUtils.copy(in, out);
        } else {
            // means we have Gray + alpha or RGB + alpha
            // TODO: since we have alpha here do this when the alpha channel is extracted
            int numBytes = numberOfInterleavedComponents - 1; // 1 for Gray, 3 for RGB
            int numColumns = image.getSize().getWidthPx();
            InflaterInputStream infStream = new InflaterInputStream(in, new Inflater());
            DataInputStream dataStream = new DataInputStream(infStream);
            int offset = 0;
            int bytesPerRow = numberOfInterleavedComponents * numColumns;
            int filter;
            // here we need to inflate the PNG pixel data, which includes alpha, separate the alpha
            // channel and then deflate the RGB channels back again
            DeflaterOutputStream dos = new DeflaterOutputStream(out, new Deflater());
            while ((filter = dataStream.read()) != -1) {
                byte[] bytes = new byte[bytesPerRow];
                dataStream.readFully(bytes, 0, bytesPerRow);
                dos.write((byte) filter);
                for (int j = 0; j < numColumns; j++) {
                    dos.write(bytes, offset, numBytes);
                    offset += numberOfInterleavedComponents;
                }
                offset = 0;
            }
            dos.close();
        }
    } finally {
        IOUtils.closeQuietly(in);
    }
}

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

public String getDecodedSAMLMessage(String encodedSamlMessage, ConversationID id) {
    /*/*from   ww w.  j  a v a  2s  . 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);
    }/*from   www. j ava 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: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());
    }/*w w  w . j a v  a 2  s.com*/
    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;
}