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) 

Source Link

Document

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

Usage

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

/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq/*w  w  w .  j  ava 2 s  .co  m*/
 * @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.wso2.carbon.identity.saml.inbound.util.SAMLSSOUtil.java

/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq//from   ww  w . j  a  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.mrgeo.vector.mrsvector.VectorTile.java

protected static InputStream parseBlob(final DataInputStream dis, final BlobHeader header) throws IOException {
    final byte[] blob = new byte[header.getDatasize()];
    dis.read(blob);/*from  w w w  .j av  a  2 s. c o  m*/

    final Blob b = Blob.parseFrom(blob);

    InputStream blobData;
    if (b.hasZlibData()) {
        blobData = new InflaterInputStream(b.getZlibData().newInput());
    } else {
        blobData = b.getRaw().newInput();
    }

    return blobData;
}

From source file:fabiogentile.powertutor.ui.UMLogger.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case MENU_PREFERENCES:
        startActivity(new Intent(this, EditPreferences.class));
        return true;
    case MENU_SAVE_LOG:
        new Thread() {
            public void start() {
                File writeFile = new File(Environment.getExternalStorageDirectory(),
                        "PowerTrace" + System.currentTimeMillis() + ".log");

                try {
                    InflaterInputStream logIn = new InflaterInputStream(openFileInput("PowerTrace.log"));
                    BufferedOutputStream logOut = new BufferedOutputStream(new FileOutputStream(writeFile));

                    byte[] buffer = new byte[20480];
                    for (int ln = logIn.read(buffer); ln != -1; ln = logIn.read(buffer)) {
                        logOut.write(buffer, 0, ln);
                    }/*  w ww  .j ava 2s  . c  o  m*/
                    logIn.close();
                    logOut.close();
                    Toast.makeText(UMLogger.this, "Wrote log to " + writeFile.getAbsolutePath(),
                            Toast.LENGTH_SHORT).show();
                    return;

                } catch (EOFException e) {
                    Toast.makeText(UMLogger.this, "Wrote log to " + writeFile.getAbsolutePath(),
                            Toast.LENGTH_SHORT).show();
                    return;
                } catch (IOException e) {
                    Log.e(TAG, "failed to save log: " + e.getMessage());
                }
                Toast.makeText(UMLogger.this, "Failed to write log to sdcard", Toast.LENGTH_SHORT).show();
            }
        }.start();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

From source file:org.oclc.oai.harvester2.verb.HarvesterVerb.java

/**
 * Preforms the OAI request//from w  w  w .jav  a2 s. co  m
 *
 * @param requestURL
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
public void harvestOldOclcImplementation(String requestURL)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    this.requestURL = requestURL;
    logger.debug("requestURL=" + requestURL);
    InputStream in;
    URL url = new URL(requestURL);
    HttpURLConnection con;
    int responseCode;
    do {
        con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "OAIHarvester/2.0");
        con.setRequestProperty("Accept-Encoding", "compress, gzip, identify");
        try {
            responseCode = con.getResponseCode();
            logger.debug("responseCode=" + responseCode);
        } catch (FileNotFoundException e) {
            // assume it's a 503 response
            logger.error(requestURL, e);
            responseCode = HttpURLConnection.HTTP_UNAVAILABLE;
        }

        if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
            long retrySeconds = con.getHeaderFieldInt("Retry-After", -1);
            if (retrySeconds == -1) {
                long now = (new Date()).getTime();
                long retryDate = con.getHeaderFieldDate("Retry-After", now);
                retrySeconds = retryDate - now;
            }
            if (retrySeconds == 0) { // Apparently, it's a bad URL
                throw new FileNotFoundException("Bad URL?");
            }
            logger.warn("Server response: Retry-After=" + retrySeconds);
            if (retrySeconds > 0) {
                try {
                    Thread.sleep(retrySeconds * 1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    } while (responseCode == HttpURLConnection.HTTP_UNAVAILABLE);
    String contentEncoding = con.getHeaderField("Content-Encoding");
    logger.debug("contentEncoding=" + contentEncoding);
    if ("compress".equals(contentEncoding)) {
        ZipInputStream zis = new ZipInputStream(con.getInputStream());
        zis.getNextEntry();
        in = zis;
    } else if ("gzip".equals(contentEncoding)) {
        in = new GZIPInputStream(con.getInputStream());
    } else if ("deflate".equals(contentEncoding)) {
        in = new InflaterInputStream(con.getInputStream());
    } else {
        in = con.getInputStream();
    }

    InputSource data = new InputSource(in);

    Thread t = Thread.currentThread();
    DocumentBuilder builder = (DocumentBuilder) builderMap.get(t);
    if (builder == null) {
        builder = factory.newDocumentBuilder();
        builderMap.put(t, builder);
    }
    doc = builder.parse(data);

    StringTokenizer tokenizer = new StringTokenizer(getSingleString("/*/@xsi:schemaLocation"), " ");
    StringBuffer sb = new StringBuffer();
    while (tokenizer.hasMoreTokens()) {
        if (sb.length() > 0)
            sb.append(" ");
        sb.append(tokenizer.nextToken());
    }
    this.schemaLocation = sb.toString();
}

From source file:com.isecpartners.gizmo.HttpResponse.java

public String deflateData(byte[] blist) {
    return uncompressData(blist, new InflaterInputStream(new ByteArrayInputStream(reduceToBodyBlock(blist))));
}

From source file:org.oclc.oai.harvester2.verb.HarvesterVerb.java

public static void main(String[] args) throws IOException, ParserConfigurationException, SAXException {
    String requestURL = "https://databank.ora.ox.ac.uk/oaipmh?verb=ListRecords&resumptionToken=20121206_TKMGW4A_SWT3NHV";

    //String requestURL = "http://bd2.inesc-id.pt:8080/repox2Eudml/OAIHandler?verb=ListRecords&resumptionToken=1354116062009:ELibM_external:eudml-article2:33753:37054::";
    //String requestURL = "http://bd2.inesc-id.pt:8080/repox2Eudml/OAIHandler?verb=GetRecord&identifier=urn:eudml.eu:ELibM_external:05152756&metadataPrefix=eudml-article2";
    //String requestURL = "C:/Users/Gilberto Pedrosa/Desktop/OAIHandler.xml";
    //FileInputStream fis = new FileInputStream(requestURL);
    //InputStream in = fis;
    logger.debug("requestURL=" + requestURL);
    DocumentBuilderFactory factory;
    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(true);//from www .  j a  v a 2  s  .com
    Thread t = Thread.currentThread();
    DocumentBuilder builder = factory.newDocumentBuilder();
    HashMap builderMap = new HashMap();
    builderMap.put(t, builder);

    InputStream in;

    URL url = new URL(requestURL);
    HttpURLConnection con;
    int responseCode;
    do {
        con = (HttpURLConnection) url.openConnection();
        con.setConnectTimeout(30000);
        con.setReadTimeout(600000);

        if (con.getAllowUserInteraction()) {
            con.setRequestProperty("User-Agent", "OAIHarvester/2.0");
            con.setRequestProperty("Accept-Encoding", "compress, gzip, identify");
        }
        try {
            responseCode = con.getResponseCode();
            logger.debug("responseCode=" + responseCode);
        } catch (FileNotFoundException e) {
            // assume it's a 503 response
            logger.error(requestURL, e);
            responseCode = HttpURLConnection.HTTP_UNAVAILABLE;
        }

        if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
            long retrySeconds = con.getHeaderFieldInt("Retry-After", -1);
            if (retrySeconds == -1) {
                long now = (new Date()).getTime();
                long retryDate = con.getHeaderFieldDate("Retry-After", now);
                retrySeconds = retryDate - now;
            }
            if (retrySeconds == 0) { // Apparently, it's a bad URL
                throw new FileNotFoundException("Bad URL?");
            }
            logger.warn("Server response: Retry-After=" + retrySeconds);
            if (retrySeconds > 0) {
                try {
                    Thread.sleep(retrySeconds * 1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    while (responseCode == HttpURLConnection.HTTP_UNAVAILABLE);
    String contentEncoding = con.getHeaderField("Content-Encoding");
    logger.debug("contentEncoding=" + contentEncoding);
    if ("compress".equals(contentEncoding)) {
        ZipInputStream zis = new ZipInputStream(con.getInputStream());
        zis.getNextEntry();
        in = zis;
    } else if ("gzip".equals(contentEncoding)) {
        in = new GZIPInputStream(con.getInputStream());
    } else if ("deflate".equals(contentEncoding)) {
        in = new InflaterInputStream(con.getInputStream());
    } else {
        in = con.getInputStream();
    }

    byte[] inputBytes = IOUtils.toByteArray(in);
    InputSource data = new InputSource(new ByteArrayInputStream(inputBytes));

    String xmlString = new String(inputBytes, "UTF-8");
    xmlString = XmlUtil.removeInvalidXMLCharacters(xmlString);

    builder.parse(data);

    System.out.println("data = " + data);
}

From source file:microsoft.exchange.webservices.data.core.request.ServiceRequestBase.java

/**
 * Gets the response stream (may be wrapped with GZip/Deflate stream to decompress content).
 *
 * @param request HttpWebRequest object from which response stream can be read.
 * @return ResponseStream/* w ww .j a v a 2s . c  om*/
 * @throws java.io.IOException Signals that an I/O exception has occurred.
 * @throws EWSHttpException    the EWS http exception
 */
protected static InputStream getResponseStream(HttpWebRequest request) throws IOException, EWSHttpException {
    String contentEncoding = "";

    if (null != request.getContentEncoding()) {
        contentEncoding = request.getContentEncoding().toLowerCase();
    }

    InputStream responseStream;

    if (contentEncoding.contains("gzip")) {
        responseStream = new GZIPInputStream(request.getInputStream());
    } else if (contentEncoding.contains("deflate")) {
        responseStream = new InflaterInputStream(request.getInputStream());
    } else {
        responseStream = request.getInputStream();
    }
    return responseStream;
}

From source file:org.oclc.oai.harvester.verb.HarvesterVerb.java

/**
 * Performs the OAI request/*from  w  ww .  ja va  2s .  com*/
 * 
 * @param requestURL
 * @throws IOException
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws TransformerException
 */
public void harvestOldOclcImplementation(String requestURL)
        throws IOException, ParserConfigurationException, SAXException, TransformerException {
    this.requestURL = requestURL;
    logger.debug("requestURL=" + requestURL);
    InputStream in;
    URL url = new URL(requestURL);
    HttpURLConnection con;
    int responseCode;
    do {
        con = (HttpURLConnection) url.openConnection();
        con.setRequestProperty("User-Agent", "OAIHarvester/2.0");
        con.setRequestProperty("Accept-Encoding", "compress, gzip, identify");
        try {
            responseCode = con.getResponseCode();
            logger.debug("responseCode=" + responseCode);
        } catch (FileNotFoundException e) {
            // assume it's a 503 response
            logger.error(requestURL, e);
            responseCode = HttpURLConnection.HTTP_UNAVAILABLE;
        }

        if (responseCode == HttpURLConnection.HTTP_UNAVAILABLE) {
            long retrySeconds = con.getHeaderFieldInt("Retry-After", -1);
            if (retrySeconds == -1) {
                long now = (new Date()).getTime();
                long retryDate = con.getHeaderFieldDate("Retry-After", now);
                retrySeconds = retryDate - now;
            }
            if (retrySeconds == 0) { // Apparently, it's a bad URL
                throw new FileNotFoundException("Bad URL?");
            }
            logger.warn("Server response: Retry-After=" + retrySeconds);
            if (retrySeconds > 0) {
                try {
                    Thread.sleep(retrySeconds * 1000);
                } catch (InterruptedException ex) {
                    ex.printStackTrace();
                }
            }
        }
    } while (responseCode == HttpURLConnection.HTTP_UNAVAILABLE);
    String contentEncoding = con.getHeaderField("Content-Encoding");
    logger.debug("contentEncoding=" + contentEncoding);
    if ("compress".equals(contentEncoding)) {
        ZipInputStream zis = new ZipInputStream(con.getInputStream());
        zis.getNextEntry();
        in = zis;
    } else if ("gzip".equals(contentEncoding)) {
        in = new GZIPInputStream(con.getInputStream());
    } else if ("deflate".equals(contentEncoding)) {
        in = new InflaterInputStream(con.getInputStream());
    } else {
        in = con.getInputStream();
    }

    InputSource data = new InputSource(in);

    Thread t = Thread.currentThread();
    DocumentBuilder builder = builderMap.get(t);
    if (builder == null) {
        builder = factory.newDocumentBuilder();
        builderMap.put(t, builder);
    }
    doc = builder.parse(data);

    StringTokenizer tokenizer = new StringTokenizer(getSingleString("/*/@xsi:schemaLocation"), " ");
    StringBuffer sb = new StringBuffer();
    while (tokenizer.hasMoreTokens()) {
        if (sb.length() > 0)
            sb.append(" ");
        sb.append(tokenizer.nextToken());
    }
    this.schemaLocation = sb.toString();
}

From source file:com.ichi2.anki.AnkiDroidProxy.java

/**
 * Anki Desktop -> libanki/anki/sync.py, HttpSyncServerProxy - summary
 * /*  www  .  j a  v  a  2 s .c o  m*/
 * @param lastSync
 */
public JSONObject summary(double lastSync) {

    Log.i(AnkiDroidApp.TAG, "Summary Server");

    // Log.i(AnkiDroidApp.TAG, "user = " + username + ", password = " + password + ", lastSync = " + lastSync);
    JSONObject summaryServer = new JSONObject();

    try {
        // FIXME: Try to do the connection without encoding the lastSync in Base 64
        String data = "p=" + URLEncoder.encode(mPassword, "UTF-8") + "&u="
                + URLEncoder.encode(mUsername, "UTF-8") + "&d=" + URLEncoder.encode(mDeckName, "UTF-8")
                + "&lastSync="
                + URLEncoder.encode(
                        Base64.encodeBytes(
                                Utils.compress(String.format(Utils.ENGLISH_LOCALE, "%f", lastSync).getBytes())),
                        "UTF-8")
                + "&base64=" + URLEncoder.encode("true", "UTF-8");

        // Log.i(AnkiDroidApp.TAG, "Data json = " + data);
        HttpPost httpPost = new HttpPost(SYNC_URL + "summary");
        StringEntity entity = new StringEntity(data);
        httpPost.setEntity(entity);
        httpPost.setHeader("Accept-Encoding", "identity");
        httpPost.setHeader("Content-type", "application/x-www-form-urlencoded");
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpResponse response = httpClient.execute(httpPost);
        Log.i(AnkiDroidApp.TAG, "Response = " + response.toString());
        HttpEntity entityResponse = response.getEntity();
        Log.i(AnkiDroidApp.TAG, "Entity's response = " + entityResponse.toString());
        InputStream content = entityResponse.getContent();
        Log.i(AnkiDroidApp.TAG, "Content = " + content.toString());
        summaryServer = new JSONObject(Utils.convertStreamToString(new InflaterInputStream(content)));
        Log.i(AnkiDroidApp.TAG, "Summary server = ");
        Utils.printJSONObject(summaryServer);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        Log.i(AnkiDroidApp.TAG, "ClientProtocolException = " + e.getMessage());
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
    }

    return summaryServer;
}