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:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

/**
 * Open the {@link InputStream} of an Http response. This method supports
 * GZIP and DEFLATE responses.//from ww w .jav a 2 s . c  o m
 */
private static InputStream getInputStream(HttpURLConnection conn) throws IOException {
    final List<String> contentEncodingValues = conn.getHeaderFields().get("Content-Encoding");
    if (contentEncodingValues != null) {
        for (final String contentEncoding : contentEncodingValues) {
            if (contentEncoding != null) {
                if (contentEncoding.contains("gzip")) {
                    return new GZIPInputStream(conn.getInputStream());
                }
                if (contentEncoding.contains("deflate")) {
                    return new InflaterInputStream(conn.getInputStream(), new Inflater(true));
                }
            }
        }
    }
    return conn.getInputStream();
}

From source file:org.apache.xmlgraphics.image.codec.png.PNGImageDecoder.java

private void parse_IEND_chunk(final PNGChunk chunk) {
    // Store text strings
    final int textLen = this.textKeys.size();
    final String[] textArray = new String[2 * textLen];
    for (int i = 0; i < textLen; ++i) {
        final String key = this.textKeys.get(i);
        final String val = this.textStrings.get(i);
        textArray[2 * i] = key;//w  w  w  .ja va 2s.co m
        textArray[2 * i + 1] = val;
        if (this.emitProperties) {
            final String uniqueKey = "text_" + i + ':' + key;
            this.properties.put(uniqueKey.toLowerCase(), val);
        }
    }
    if (this.encodeParam != null) {
        this.encodeParam.setText(textArray);
    }

    // Store compressed text strings
    final int ztextLen = this.ztextKeys.size();
    final String[] ztextArray = new String[2 * ztextLen];
    for (int i = 0; i < ztextLen; ++i) {
        final String key = this.ztextKeys.get(i);
        final String val = this.ztextStrings.get(i);
        ztextArray[2 * i] = key;
        ztextArray[2 * i + 1] = val;
        if (this.emitProperties) {
            final String uniqueKey = "ztext_" + i + ':' + key;
            this.properties.put(uniqueKey.toLowerCase(), val);
        }
    }
    if (this.encodeParam != null) {
        this.encodeParam.setCompressedText(ztextArray);
    }

    // Parse prior IDAT chunks
    final InputStream seqStream = new SequenceInputStream(Collections.enumeration(this.streamVec));
    final InputStream infStream = new InflaterInputStream(seqStream, new Inflater());
    this.dataStream = new DataInputStream(infStream);

    // Create an empty WritableRaster
    int depth = this.bitDepth;
    if (this.colorType == PNG_COLOR_GRAY && this.bitDepth < 8 && this.output8BitGray) {
        depth = 8;
    }
    if (this.colorType == PNG_COLOR_PALETTE && this.expandPalette) {
        depth = 8;
    }
    final int bytesPerRow = (this.outputBands * this.width * depth + 7) / 8;
    final int scanlineStride = depth == 16 ? bytesPerRow / 2 : bytesPerRow;

    this.theTile = createRaster(this.width, this.height, this.outputBands, scanlineStride, depth);

    if (this.performGammaCorrection && this.gammaLut == null) {
        initGammaLut(this.bitDepth);
    }
    if (this.postProcess == POST_GRAY_LUT || this.postProcess == POST_GRAY_LUT_ADD_TRANS
            || this.postProcess == POST_GRAY_LUT_ADD_TRANS_EXP) {
        initGrayLut(this.bitDepth);
    }

    decodeImage(this.interlaceMethod == 1);
    this.sampleModel = this.theTile.getSampleModel();

    if (this.colorType == PNG_COLOR_PALETTE && !this.expandPalette) {
        if (this.outputHasAlphaPalette) {
            this.colorModel = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette,
                    this.greenPalette, this.bluePalette, this.alphaPalette);
        } else {
            this.colorModel = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette,
                    this.greenPalette, this.bluePalette);
        }
    } else if (this.colorType == PNG_COLOR_GRAY && this.bitDepth < 8 && !this.output8BitGray) {
        final byte[] palette = this.expandBits[this.bitDepth];
        this.colorModel = new IndexColorModel(this.bitDepth, palette.length, palette, palette, palette);
    } else {
        this.colorModel = createComponentColorModel(this.sampleModel);
    }
}

From source file:org.kymjs.kjframe.http.httpclient.HttpRequestBuilder.java

/**
 * Open the error {@link InputStream} of an Http response. This method
 * supports GZIP and DEFLATE responses./*from   w ww  .  ja v  a  2 s .  c  o  m*/
 */
private static InputStream getErrorStream(HttpURLConnection conn) throws IOException {
    final List<String> contentEncodingValues = conn.getHeaderFields().get("Content-Encoding");
    if (contentEncodingValues != null) {
        for (final String contentEncoding : contentEncodingValues) {
            if (contentEncoding != null) {
                if (contentEncoding.contains("gzip")) {
                    return new GZIPInputStream(conn.getErrorStream());
                }
                if (contentEncoding.contains("deflate")) {
                    return new InflaterInputStream(conn.getErrorStream(), new Inflater(true));
                }
            }
        }
    }
    return conn.getErrorStream();
}

From source file:org.apache.xmlgraphics.image.codec.png.PNGRed.java

private void parse_IEND_chunk(final PNGChunk chunk) throws IOException {
    // Store text strings
    final int textLen = this.textKeys.size();
    final String[] textArray = new String[2 * textLen];
    for (int i = 0; i < textLen; ++i) {
        final String key = this.textKeys.get(i);
        final String val = this.textStrings.get(i);
        textArray[2 * i] = key;//from w w w . ja v a 2s . com
        textArray[2 * i + 1] = val;
        if (this.emitProperties) {
            final String uniqueKey = "text_" + i + ':' + key;
            this.properties.put(uniqueKey.toLowerCase(), val);
        }
    }
    if (this.encodeParam != null) {
        this.encodeParam.setText(textArray);
    }

    // Store compressed text strings
    final int ztextLen = this.ztextKeys.size();
    final String[] ztextArray = new String[2 * ztextLen];
    for (int i = 0; i < ztextLen; ++i) {
        final String key = this.ztextKeys.get(i);
        final String val = this.ztextStrings.get(i);
        ztextArray[2 * i] = key;
        ztextArray[2 * i + 1] = val;
        if (this.emitProperties) {
            final String uniqueKey = "ztext_" + i + ':' + key;
            this.properties.put(uniqueKey.toLowerCase(), val);
        }
    }
    if (this.encodeParam != null) {
        this.encodeParam.setCompressedText(ztextArray);
    }

    // Parse prior IDAT chunks
    final InputStream seqStream = new SequenceInputStream(Collections.enumeration(this.streamVec));
    final InputStream infStream = new InflaterInputStream(seqStream, new Inflater());
    this.dataStream = new DataInputStream(infStream);

    // Create an empty WritableRaster
    int depth = this.bitDepth;
    if (this.colorType == PNG_COLOR_GRAY && this.bitDepth < 8 && this.output8BitGray) {
        depth = 8;
    }
    if (this.colorType == PNG_COLOR_PALETTE && this.expandPalette) {
        depth = 8;
    }
    final int width = this.bounds.width;
    final int height = this.bounds.height;

    final int bytesPerRow = (this.outputBands * width * depth + 7) / 8;
    final int scanlineStride = depth == 16 ? bytesPerRow / 2 : bytesPerRow;

    this.theTile = createRaster(width, height, this.outputBands, scanlineStride, depth);

    if (this.performGammaCorrection && this.gammaLut == null) {
        initGammaLut(this.bitDepth);
    }
    if (this.postProcess == POST_GRAY_LUT || this.postProcess == POST_GRAY_LUT_ADD_TRANS
            || this.postProcess == POST_GRAY_LUT_ADD_TRANS_EXP) {
        initGrayLut(this.bitDepth);
    }

    decodeImage(this.interlaceMethod == 1);

    // Free resources associated with compressed data.
    this.dataStream.close();
    infStream.close();
    seqStream.close();
    this.streamVec = null;

    final SampleModel sm = this.theTile.getSampleModel();
    ColorModel cm;

    if (this.colorType == PNG_COLOR_PALETTE && !this.expandPalette) {
        if (this.outputHasAlphaPalette) {
            cm = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette, this.greenPalette,
                    this.bluePalette, this.alphaPalette);
        } else {
            cm = new IndexColorModel(this.bitDepth, this.paletteEntries, this.redPalette, this.greenPalette,
                    this.bluePalette);
        }
    } else if (this.colorType == PNG_COLOR_GRAY && this.bitDepth < 8 && !this.output8BitGray) {
        final byte[] palette = this.expandBits[this.bitDepth];
        cm = new IndexColorModel(this.bitDepth, palette.length, palette, palette, palette);
    } else {
        cm = createComponentColorModel(sm);
    }

    init((CachableRed) null, this.bounds, cm, sm, 0, 0, this.properties);
}

From source file:org.pluroid.pluroium.PlurkHelper.java

private Response performRequest(String url, Map<String, String> reqParams) {
    Response rsp = null;/* ww  w . ja v a  2s  . co m*/

    ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();
    params.add(new BasicNameValuePair("api_key", API_KEY));
    for (String key : reqParams.keySet()) {
        params.add(new BasicNameValuePair(key, reqParams.get(key)));
    }
    HttpEntity entity = null;
    try {
        entity = new UrlEncodedFormEntity(params, "UTF-8");
    } catch (final UnsupportedEncodingException e) {
        // this should never happen.
        throw new AssertionError(e);
    }
    HttpPost post = new HttpPost(url);
    post.addHeader(entity.getContentType());
    post.addHeader("Accept-Encoding", "gzip,deflate");
    post.setEntity(entity);

    try {
        HttpResponse resp = httpClient.execute(post);
        rsp = new Response();
        rsp.statusCode = resp.getStatusLine().getStatusCode();
        HttpEntity respEntity = resp.getEntity();
        InputStream is = null;
        if (respEntity.getContentEncoding() != null) {
            String contentEncoding = respEntity.getContentEncoding().getValue();
            if ("gzip".equals(contentEncoding)) {
                is = new GZIPInputStream(respEntity.getContent());
            } else if ("deflate".equals(contentEncoding)) {
                is = new InflaterInputStream(respEntity.getContent(), new Inflater(true));
            } else {
                is = respEntity.getContent();
            }
        } else {
            is = respEntity.getContent();
        }

        rsp.responseText = getResponseText(is);
    } catch (IOException e) {
        Log.e(TAG, "Network access error!", e);
    } finally {
        connMgr.shutdown();
    }

    return rsp;
}

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

private String inflate(String saml) throws Exception {
    byte[] compressedData = org.bouncycastle.util.encoders.Base64.decode(saml);
    ByteArrayInputStream bin = new ByteArrayInputStream(compressedData);

    InflaterInputStream decompressor = new InflaterInputStream(bin, new Inflater(true));
    //decompressor.setInput(compressedData);

    // Create an expandable byte array to hold the decompressed data
    ByteArrayOutputStream bos = new ByteArrayOutputStream(compressedData.length);

    // Decompress the data
    byte[] buf = new byte[1024];
    int len;//from   w  w  w. j  a  va 2s .  co m
    while ((len = decompressor.read(buf)) > 0) {

        bos.write(buf, 0, len);

    }
    try {
        bos.close();
    } catch (IOException e) {
    }

    // Get the decompressed data
    byte[] decompressedData = bos.toByteArray();

    String decoded = new String(decompressedData);

    return decoded;
}

From source file:tr.edu.gsu.nerwip.retrieval.reader.wikipedia.WikipediaReader.java

/**
 * Reads the source code of the web page at the specified
 * URL./* ww  w . jav a  2  s . c o  m*/
 * 
 * @param url
 *       Address of the web page to be read.
 * @return
 *       String containing the read HTML source code.
 * 
 * @throws IOException
 *       Problem while accessing the specified URL.
 */
private String manuallyReadUrl(URL url) throws IOException {
    boolean trad = false;

    BufferedReader br = null;

    // open page the traditional way
    if (trad) {
        InputStream is = url.openStream();
        InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
    }

    // open with more options
    else { // setup connection
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("GET");
        connection.setDoOutput(true);
        connection.setReadTimeout(2000);
        connection.setChunkedStreamingMode(0);
        connection.setRequestProperty("Content-Length", "0");
        //         connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.4; en-US; rv:1.9.2.2) Gecko/20100316 Firefox/3.6.2");
        connection.setRequestProperty("User-Agent",
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36");
        connection.connect();

        // setup input stream
        // part retrieved from http://stackoverflow.com/questions/538999/java-util-scanner-and-wikipedia
        // original author: Marco Beggio
        InputStream is = null;
        String encoding = connection.getContentEncoding();
        if (connection.getContentEncoding() != null && encoding.equals("gzip")) {
            is = new GZIPInputStream(connection.getInputStream());
        } else if (encoding != null && encoding.equals("deflate")) {
            is = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
        } else {
            is = connection.getInputStream();
        }

        // alternative to spot error details            
        //         InputStream is;
        //         if (connection.getResponseCode() != 200) 
        //            is = connection.getErrorStream();
        //         else 
        //            is = connection.getInputStream();

        InputStreamReader isr = new InputStreamReader(is);
        br = new BufferedReader(isr);
    }

    // read page
    StringBuffer sourceCode = new StringBuffer();
    String line = br.readLine();
    while (line != null) {
        sourceCode.append(line + "\n");
        line = br.readLine();
    }

    String result = sourceCode.toString();
    br.close();
    return result;
}

From source file:cgeo.geocaching.cgBase.java

public static void postTweet(cgeoapplication app, cgSettings settings, String status, final Geopoint coords) {
    if (app == null) {
        return;// ww w  .  j a  va2 s .c  o  m
    }
    if (settings == null || StringUtils.isBlank(settings.tokenPublic)
            || StringUtils.isBlank(settings.tokenSecret)) {
        return;
    }

    try {
        Map<String, String> parameters = new HashMap<String, String>();

        parameters.put("status", status);
        if (coords != null) {
            parameters.put("lat", String.format("%.6f", coords.getLatitude()));
            parameters.put("long", String.format("%.6f", coords.getLongitude()));
            parameters.put("display_coordinates", "true");
        }

        final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false,
                parameters, settings.tokenPublic, settings.tokenSecret);

        HttpURLConnection connection = null;
        try {
            final StringBuffer buffer = new StringBuffer();
            final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
            final URLConnection uc = u.openConnection();

            uc.setRequestProperty("Host", "api.twitter.com");

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(paramsDone);
            wr.flush();
            wr.close();

            Log.i(cgSettings.tag,
                    "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());

            InputStream ins;
            final String encoding = connection.getContentEncoding();

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }

            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
            connection.disconnect();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage() + " ~ " + e.toString());

            final InputStream ins = connection.getErrorStream();
            final StringBuffer buffer = new StringBuffer();
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
        }

        connection.disconnect();
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
    }
}

From source file:cgeo.geocaching.cgBase.java

private static InputStream getInputstreamFromConnection(HttpURLConnection connection) throws IOException {
    final String encoding = connection.getContentEncoding();
    InputStream ins;//from  w  w w. j ava2s  .c o  m

    if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
        ins = new GZIPInputStream(connection.getInputStream());
    } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
        ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
    } else {
        ins = connection.getInputStream();
    }
    return ins;
}

From source file:carnero.cgeo.cgBase.java

public void postTweet(cgeoapplication app, cgSettings settings, String status, Double latitude,
        Double longitude) {// ww  w  . j  a  v a2s  .  c  o  m
    if (app == null) {
        return;
    }
    if (settings == null || settings.tokenPublic == null || settings.tokenPublic.length() == 0
            || settings.tokenSecret == null || settings.tokenSecret.length() == 0) {
        return;
    }

    try {
        HashMap<String, String> parameters = new HashMap<String, String>();

        parameters.put("status", status);
        if (latitude != null && longitude != null) {
            parameters.put("lat", String.format("%.6f", latitude));
            parameters.put("long", String.format("%.6f", longitude));
            parameters.put("display_coordinates", "true");
        }

        final String paramsDone = cgOAuth.signOAuth("api.twitter.com", "/1/statuses/update.json", "POST", false,
                parameters, settings.tokenPublic, settings.tokenSecret);

        HttpURLConnection connection = null;
        try {
            final StringBuffer buffer = new StringBuffer();
            final URL u = new URL("http://api.twitter.com/1/statuses/update.json");
            final URLConnection uc = u.openConnection();

            uc.setRequestProperty("Host", "api.twitter.com");

            connection = (HttpURLConnection) uc;
            connection.setReadTimeout(30000);
            connection.setRequestMethod("POST");
            HttpURLConnection.setFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);

            final OutputStream out = connection.getOutputStream();
            final OutputStreamWriter wr = new OutputStreamWriter(out);
            wr.write(paramsDone);
            wr.flush();
            wr.close();

            Log.i(cgSettings.tag,
                    "Twitter.com: " + connection.getResponseCode() + " " + connection.getResponseMessage());

            InputStream ins;
            final String encoding = connection.getContentEncoding();

            if (encoding != null && encoding.equalsIgnoreCase("gzip")) {
                ins = new GZIPInputStream(connection.getInputStream());
            } else if (encoding != null && encoding.equalsIgnoreCase("deflate")) {
                ins = new InflaterInputStream(connection.getInputStream(), new Inflater(true));
            } else {
                ins = connection.getInputStream();
            }

            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
            connection.disconnect();
        } catch (IOException e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.IO: " + connection.getResponseCode() + ": "
                    + connection.getResponseMessage() + " ~ " + e.toString());

            final InputStream ins = connection.getErrorStream();
            final StringBuffer buffer = new StringBuffer();
            final InputStreamReader inr = new InputStreamReader(ins);
            final BufferedReader br = new BufferedReader(inr);

            readIntoBuffer(br, buffer);

            br.close();
            ins.close();
            inr.close();
        } catch (Exception e) {
            Log.e(cgSettings.tag, "cgBase.postTweet.inner: " + e.toString());
        }

        connection.disconnect();
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.postTweet: " + e.toString());
    }
}