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:IntergrationTest.OCSPIntegrationTest.java

private byte[] httpGetBin(URI uri, boolean bActiveCheckUnknownHost) throws Exception {
    InputStream is = null;//from   w w  w .  j av a 2s  . c o  m
    InputStream is_temp = null;
    try {
        if (uri == null)
            return null;
        URL url = uri.toURL();
        if (bActiveCheckUnknownHost) {
            url.getProtocol();
            String host = url.getHost();
            int port = url.getPort();
            if (port == -1)
                port = url.getDefaultPort();
            InetSocketAddress isa = new InetSocketAddress(host, port);
            if (isa.isUnresolved()) {
                //fix JNLP popup error issue
                throw new UnknownHostException("Host Unknown:" + isa.toString());
            }

        }
        HttpURLConnection uc = (HttpURLConnection) url.openConnection();
        uc.setDoInput(true);
        uc.setAllowUserInteraction(false);
        uc.setInstanceFollowRedirects(true);
        setTimeout(uc);
        String contentEncoding = uc.getContentEncoding();
        int len = uc.getContentLength();
        // is = uc.getInputStream();
        if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("gzip") != -1) {
            is_temp = uc.getInputStream();
            is = new GZIPInputStream(is_temp);

        } else if (contentEncoding != null && contentEncoding.toLowerCase().indexOf("deflate") != -1) {
            is_temp = uc.getInputStream();
            is = new InflaterInputStream(is_temp);

        } else {
            is = uc.getInputStream();

        }
        if (len != -1) {
            int ch, i = 0;
            byte[] res = new byte[len];
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);

            }
            return res;

        } else {
            ArrayList<byte[]> buffer = new ArrayList<>();
            int buf_len = 1024;
            byte[] res = new byte[buf_len];
            int ch, i = 0;
            while ((ch = is.read()) != -1) {
                res[i++] = (byte) (ch & 0xff);
                if (i == buf_len) {
                    //rotate
                    buffer.add(res);
                    i = 0;
                    res = new byte[buf_len];

                }

            }
            int total_len = buffer.size() * buf_len + i;
            byte[] buf = new byte[total_len];
            for (int j = 0; j < buffer.size(); j++) {
                System.arraycopy(buffer.get(j), 0, buf, j * buf_len, buf_len);

            }
            if (i > 0) {
                System.arraycopy(res, 0, buf, buffer.size() * buf_len, i);

            }
            return buf;

        }

    } catch (Exception e) {
        e.printStackTrace();
        return null;

    } finally {
        closeInputStream(is_temp);
        closeInputStream(is);

    }

}

From source file:org.apache.flex.swf.io.InputBitStream.java

/**
 * Set if the InputStream is a compressed SWF stream.
 *//*from   w w  w  .  jav  a2  s .com*/
public void setCompress(Header.Compression compression) throws IOException {
    switch (compression) {
    case NONE:
        break;
    case ZLIB:
        this.in = new BufferedInputStream(new InflaterInputStream(in));
        break;
    case LZMA:
        this.in = new LZMAInputStream(in);
        break;
    default:
        assert false;
    }
}

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

private static String zlibDeflate(final byte[] bytes) {
    final ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final InflaterInputStream iis = new InflaterInputStream(bais);
    final byte[] buf = new byte[1024];

    try {/*from  www . ja v a  2  s .com*/
        int count = iis.read(buf);
        while (count != -1) {
            baos.write(buf, 0, count);
            count = iis.read(buf);
        }
        return new String(baos.toByteArray());
    } catch (final Exception e) {
        return null;
    } finally {
        IOUtils.closeQuietly(iis);
    }
}

From source file:org.adblockplus.brazil.RequestHandler.java

@Override
public boolean respond(final Request request) throws IOException {
    boolean block = false;

    final String referrer = request.getRequestHeader("referer");
    try {//from  w  w w  . jav a  2s .  c  o m
        block = application.matches(request.url, request.query, referrer, request.getRequestHeader("accept"));
    } catch (final Exception e) {
        Log.e(prefix, "Filter error", e);
    }

    request.log(Server.LOG_LOG, prefix, block + ": " + request.url);

    int count = request.server.requestCount;
    if (shouldLogHeaders) {
        // FIXME Don't log to "err"
        System.err.println(dumpHeaders(count, request, request.headers, true));
    }

    if (block) {
        request.sendHeaders(204, null, 0);
        BLOCKED_REQUESTS.incrementAndGet();
        return true;
    }

    UNBLOCKED_REQUESTS.incrementAndGet();

    // Do not further process non-http requests
    if (!RE_HTTP.matcher(request.url).find()) {
        return false;
    }

    String url = request.url;

    if ((request.query != null) && (request.query.length() > 0)) {
        url += "?" + request.query;
    }

    /*
     * "Proxy-Connection" may be used (instead of just "Connection")
     * to keep alive a connection between a client and this proxy.
     */
    final String pc = request.headers.get("Proxy-Connection");
    if (pc != null) {
        request.connectionHeader = "Proxy-Connection";
        request.keepAlive = pc.equalsIgnoreCase("Keep-Alive");
    }

    HttpRequest.removePointToPointHeaders(request.headers, false);

    final HttpRequest target = new HttpRequest(url);
    try {
        target.setMethod(request.method);
        request.headers.copyTo(target.requestHeaders);

        if (proxyHost != null) {
            target.setProxy(proxyHost, proxyPort);
            if (auth != null) {
                target.requestHeaders.add("Proxy-Authorization", auth);
            }
        }

        if (request.postData != null) {
            final OutputStream out = target.getOutputStream();
            out.write(request.postData);
            out.close();
        } else {
            target.setHttpInputStream(request.in);
        }
        target.connect();

        if (shouldLogHeaders) {
            System.err.println("      " + target.status + "\n"
                    + dumpHeaders(count, request, target.responseHeaders, false));
        }
        HttpRequest.removePointToPointHeaders(target.responseHeaders, true);

        request.setStatus(target.getResponseCode());
        target.responseHeaders.copyTo(request.responseHeaders);
        try {
            request.responseHeaders.add("Via", target.status.substring(0, 8) + via);
        } catch (final StringIndexOutOfBoundsException e) {
            request.responseHeaders.add("Via", via);
        }

        // Detect if we need to add ElemHide filters
        final String type = request.responseHeaders.get("Content-Type");

        String[] selectors = null;
        if (type != null && type.toLowerCase().startsWith("text/html")) {
            String reqHost = "";

            try {
                reqHost = (new URL(request.url)).getHost();
            } catch (final MalformedURLException e) {
                // We are transparent, it's not our deal if it's malformed.
            }

            selectors = application.getSelectorsForDomain(reqHost, referrer);
        }
        // If no filters are applicable just pass through the response
        if (selectors == null || target.getResponseCode() != 200) {
            final int contentLength = target.getContentLength();
            if (contentLength == 0) {
                // we do not use request.sendResponse to avoid arbitrary
                // 200 -> 204 response code conversion
                request.sendHeaders(-1, null, -1);
            } else {
                request.sendResponse(target.getInputStream(), contentLength, null, -1);
            }
        }
        // Insert filters otherwise
        else {
            final HttpInputStream his = target.getInputStream();
            int size = target.getContentLength();
            if (size < 0) {
                size = Integer.MAX_VALUE;
            }

            FilterInputStream in = null;
            FilterOutputStream out = null;

            // Detect if content needs decoding
            String encodingHeader = request.responseHeaders.get("Content-Encoding");
            if (encodingHeader != null) {
                encodingHeader = encodingHeader.toLowerCase();
                if (encodingHeader.equals("gzip") || encodingHeader.equals("x-gzip")) {
                    in = new GZIPInputStream(his);
                } else if (encodingHeader.equals("compress") || encodingHeader.equals("x-compress")) {
                    in = new InflaterInputStream(his);
                } else {
                    // Unsupported encoding, proxy content as-is
                    in = his;
                    out = request.out;
                    selectors = null;
                }
            } else {
                in = his;
            }
            // Use chunked encoding when injecting filters in page
            if (out == null) {
                request.responseHeaders.remove("Content-Length");
                request.responseHeaders.remove("Content-Encoding");
                out = new ChunkedOutputStream(request.out);
                request.responseHeaders.add("Transfer-Encoding", "chunked");
                size = Integer.MAX_VALUE;
            }

            String charsetName = "utf-8";
            final String contentType = request.responseHeaders.get("Content-Type");
            if (contentType != null) {
                final Matcher matcher = Pattern.compile("charset=([^;]*)").matcher(contentType);
                if (matcher.matches()) {
                    try {
                        final String extractedCharsetName = matcher.group(0);
                        Charset.forName(extractedCharsetName);
                        charsetName = extractedCharsetName;
                    } catch (final IllegalArgumentException e) {
                        Log.e(prefix, "Unsupported site charset, falling back to " + charsetName, e);
                    }
                }
            }

            request.sendHeaders(-1, null, -1);

            final byte[] buf = new byte[Math.min(4096, size)];

            boolean sent = selectors == null;
            final BoyerMoore matcher = new BoyerMoore("<html".getBytes());

            while (size > 0) {
                out.flush();

                count = in.read(buf, 0, Math.min(buf.length, size));
                if (count < 0) {
                    break;
                }
                size -= count;
                try {
                    // Search for <html> tag
                    if (!sent && count > 0) {
                        final List<Integer> matches = matcher.match(buf, 0, count);
                        if (!matches.isEmpty()) {
                            // Add filters right before match
                            final int m = matches.get(0);
                            out.write(buf, 0, m);
                            out.write("<style type=\"text/css\">\n".getBytes());
                            out.write(StringUtils.join(selectors, ",\r\n").getBytes(charsetName));
                            out.write("{ display: none !important }</style>\n".getBytes());
                            out.write(buf, m, count - m);
                            sent = true;
                            continue;
                        }
                    }
                    out.write(buf, 0, count);
                } catch (final IOException e) {
                    break;
                }
            }
            // The correct way would be to close ChunkedOutputStream
            // but we can not do it because underlying output stream is
            // used later in caller code. So we use this ugly hack:
            if (out instanceof ChunkedOutputStream)
                ((ChunkedOutputStream) out).writeFinalChunk();
        }
    } catch (final InterruptedIOException e) {
        /*
         * Read timeout while reading from the remote side. We use a
         * read timeout in case the target never responds.
         */
        request.sendError(408, "Timeout / No response");
    } catch (final EOFException e) {
        request.sendError(500, "No response");
    } catch (final UnknownHostException e) {
        request.sendError(500, "Unknown host");
    } catch (final ConnectException e) {
        request.sendError(500, "Connection refused");
    } catch (final IOException e) {
        /*
         * An IOException will happen if we can't communicate with the
         * target or the client. Rather than attempting to discriminate,
         * just send an error message to the client, and let the send
         * fail if the client was the one that was in error.
         */

        String msg = "Error from proxy";
        if (e.getMessage() != null) {
            msg += ": " + e.getMessage();
        }
        request.sendError(500, msg);
        Log.e(prefix, msg, e);
    } finally {
        target.close();
    }
    return true;
}

From source file:org.openhab.io.net.http.HttpUtil.java

/**
 * Executes the given <code>url</code> with the given <code>httpMethod</code>
 * /*from  w ww  . j av a  2s. c  o m*/
 * @param httpMethod the HTTP method to use
 * @param url the url to execute (in milliseconds)
 * @param httpHeaders optional HTTP headers which has to be set on request
 * @param content the content to be send to the given <code>url</code> or 
 * <code>null</code> if no content should be send.
 * @param contentType the content type of the given <code>content</code>
 * @param timeout the socket timeout to wait for data
 * @param proxyHost the hostname of the proxy
 * @param proxyPort the port of the proxy
 * @param proxyUser the username to authenticate with the proxy
 * @param proxyPassword the password to authenticate with the proxy
 * @param nonProxyHosts the hosts that won't be routed through the proxy
 * @return the response body or <code>NULL</code> when the request went wrong
 */
public static String executeUrl(String httpMethod, String url, Properties httpHeaders, InputStream content,
        String contentType, int timeout, String proxyHost, Integer proxyPort, String proxyUser,
        String proxyPassword, String nonProxyHosts) {

    HttpClient client = new HttpClient();

    // only configure a proxy if a host is provided
    if (StringUtils.isNotBlank(proxyHost) && proxyPort != null && shouldUseProxy(url, nonProxyHosts)) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);
        if (StringUtils.isNotBlank(proxyUser)) {
            client.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
        }
    }

    HttpMethod method = HttpUtil.createHttpMethod(httpMethod, url);
    method.getParams().setSoTimeout(timeout);
    method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
            new DefaultHttpMethodRetryHandler(3, false));
    if (httpHeaders != null) {
        for (String httpHeaderKey : httpHeaders.stringPropertyNames()) {
            method.addRequestHeader(new Header(httpHeaderKey, httpHeaders.getProperty(httpHeaderKey)));
        }
    }
    // add content if a valid method is given ...
    if (method instanceof EntityEnclosingMethod && content != null) {
        EntityEnclosingMethod eeMethod = (EntityEnclosingMethod) method;
        eeMethod.setRequestEntity(new InputStreamRequestEntity(content, contentType));
    }

    Credentials credentials = extractCredentials(url);
    if (credentials != null) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(AuthScope.ANY, credentials);
    }

    if (logger.isDebugEnabled()) {
        try {
            logger.debug("About to execute '" + method.getURI().toString() + "'");
        } catch (URIException e) {
            logger.debug(e.getMessage());
        }
    }

    try {

        int statusCode = client.executeMethod(method);
        if (statusCode == HttpStatus.SC_NO_CONTENT || statusCode == HttpStatus.SC_ACCEPTED) {
            // perfectly fine but we cannot expect any answer...
            return null;
        }

        if (statusCode != HttpStatus.SC_OK) {
            logger.warn("Method failed: " + method.getStatusLine());
        }

        InputStream tmpResponseStream = method.getResponseBodyAsStream();
        Header encodingHeader = method.getResponseHeader("Content-Encoding");
        if (encodingHeader != null) {
            for (HeaderElement ehElem : encodingHeader.getElements()) {
                if (ehElem.toString().matches(".*gzip.*")) {
                    tmpResponseStream = new GZIPInputStream(tmpResponseStream);
                    logger.debug("GZipped InputStream from {}", url);
                } else if (ehElem.toString().matches(".*deflate.*")) {
                    tmpResponseStream = new InflaterInputStream(tmpResponseStream);
                    logger.debug("Deflated InputStream from {}", url);
                }
            }
        }

        String responseBody = IOUtils.toString(tmpResponseStream);
        if (!responseBody.isEmpty()) {
            logger.debug(responseBody);
        }

        return responseBody;
    } catch (HttpException he) {
        logger.error("Fatal protocol violation: {}", he.toString());
    } catch (IOException ioe) {
        logger.error("Fatal transport error: {}", ioe.toString());
    } finally {
        method.releaseConnection();
    }

    return null;
}

From source file:tor.Consensus.java

private InputStream connectToDirectory(String address, String port, String path) throws IOException {
    URL url = new URL("http://" + address + ":" + port + path);

    // try the compressed version first, and transparently inflate it
    if (!path.endsWith(".z")) {
        try {/*from   w ww  .j  a  v a2 s  .  c o m*/
            URL zurl = new URL("http://" + address + ":" + port + path + ".z");
            log.debug("Downloading (from directory server): " + zurl.toString());
            return new InflaterInputStream(zurl.openStream());
        } catch (SocketException e) {
            log.warn("Failed to connect: " + e);
            throw e;
        } catch (IOException e) {
            log.warn("Transparent download of compressed stream failed, falling back to uncompressed."
                    + " Exception: " + e.toString());
        }
    }

    log.debug("Downloading: " + url.toString());
    InputStream in = url.openStream();
    if (path.endsWith(".z"))
        return new InflaterInputStream(in);
    return in;
}

From source file:com.diablominer.DiabloMiner.NetworkState.JSONRPCNetworkState.java

JsonNode doJSONRPCCall(boolean longPoll, ObjectNode message) throws IOException {
    HttpURLConnection connection = null;
    try {//from  w  ww. jav  a 2s.c  o  m
        URL url;

        if (longPoll)
            url = longPollUrl;
        else
            url = queryUrl;

        Proxy proxy = diabloMiner.getProxy();

        if (proxy == null)
            connection = (HttpURLConnection) url.openConnection();
        else
            connection = (HttpURLConnection) url.openConnection(proxy);

        if (longPoll) {
            connection.setConnectTimeout(10 * 60 * 1000);
            connection.setReadTimeout(10 * 60 * 1000);
        } else {
            connection.setConnectTimeout(15 * 1000);
            connection.setReadTimeout(15 * 1000);
        }

        connection.setRequestProperty("Authorization", userPass);
        connection.setRequestProperty("Accept", "application/json");
        connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("User-Agent", "DiabloMiner");
        connection.setRequestProperty("X-Mining-Extensions", "longpoll rollntime switchto");
        connection.setDoOutput(true);

        OutputStream requestStream = connection.getOutputStream();
        Writer request = new OutputStreamWriter(requestStream);
        request.write(message.toString());
        request.close();
        requestStream.close();

        ObjectNode responseMessage = null;

        InputStream responseStream = null;

        try {
            String xLongPolling = connection.getHeaderField("X-Long-Polling");

            if (xLongPolling != null && !"".equals(xLongPolling) && longPollAsync == null) {
                if (xLongPolling.startsWith("http"))
                    longPollUrl = new URL(xLongPolling);
                else if (xLongPolling.startsWith("/"))
                    longPollUrl = new URL(queryUrl.getProtocol(), queryUrl.getHost(), queryUrl.getPort(),
                            xLongPolling);
                else
                    longPollUrl = new URL(queryUrl.getProtocol(), queryUrl.getHost(), queryUrl.getPort(),
                            (url.getFile() + "/" + xLongPolling).replace("//", "/"));

                longPollAsync = new LongPollAsync();
                Thread thread = new Thread(longPollAsync,
                        "DiabloMiner JSONRPC LongPollAsync for " + url.getHost());
                thread.start();
                diabloMiner.addThread(thread);

                workLifetime = 60000;

                diabloMiner.debug(queryUrl.getHost() + ": Enabling long poll support");
            }

            String xRollNTime = connection.getHeaderField("X-Roll-NTime");

            if (xRollNTime != null && !"".equals(xRollNTime)) {
                if (!"n".equalsIgnoreCase(xRollNTime) && rollNTime == false) {
                    rollNTime = true;

                    if (xRollNTime.startsWith("expire=")) {
                        try {
                            workLifetime = Integer.parseInt(xRollNTime.substring(7)) * 1000;
                        } catch (NumberFormatException ex) {
                        }
                    } else {
                        workLifetime = 60000;
                    }

                    diabloMiner.debug(queryUrl.getHost() + ": Enabling roll ntime support, expire after "
                            + (workLifetime / 1000) + " seconds");
                } else if ("n".equalsIgnoreCase(xRollNTime) && rollNTime == true) {
                    rollNTime = false;

                    if (longPoll)
                        workLifetime = 60000;
                    else
                        workLifetime = diabloMiner.getWorkLifetime();

                    diabloMiner.debug(queryUrl.getHost() + ": Disabling roll ntime support");
                }
            }

            String xSwitchTo = connection.getHeaderField("X-Switch-To");

            if (xSwitchTo != null && !"".equals(xSwitchTo)) {
                String oldHost = queryUrl.getHost();
                JsonNode newHost = mapper.readTree(xSwitchTo);

                queryUrl = new URL(queryUrl.getProtocol(), newHost.get("host").asText(),
                        newHost.get("port").getIntValue(), queryUrl.getPath());

                if (longPollUrl != null)
                    longPollUrl = new URL(longPollUrl.getProtocol(), newHost.get("host").asText(),
                            newHost.get("port").getIntValue(), longPollUrl.getPath());

                diabloMiner.info(oldHost + ": Switched to " + queryUrl.getHost());
            }

            String xRejectReason = connection.getHeaderField("X-Reject-Reason");

            if (xRejectReason != null && !"".equals(xRejectReason)) {
                rejectReason = xRejectReason;
            }

            String xIsP2Pool = connection.getHeaderField("X-Is-P2Pool");

            if (xIsP2Pool != null && !"".equals(xIsP2Pool)) {
                if (!noDelay)
                    diabloMiner.info("P2Pool no delay mode enabled");

                noDelay = true;
            }

            if (connection.getContentEncoding() != null) {
                if (connection.getContentEncoding().equalsIgnoreCase("gzip"))
                    responseStream = new GZIPInputStream(connection.getInputStream());
                else if (connection.getContentEncoding().equalsIgnoreCase("deflate"))
                    responseStream = new InflaterInputStream(connection.getInputStream());
            } else {
                responseStream = connection.getInputStream();
            }

            if (responseStream == null)
                throw new IOException("Drop to error handler");

            Object output = mapper.readTree(responseStream);

            if (NullNode.class.equals(output.getClass())) {
                throw new IOException("Bitcoin returned unparsable JSON");
            } else {
                try {
                    responseMessage = (ObjectNode) output;
                } catch (ClassCastException e) {
                    throw new IOException("Bitcoin returned unparsable JSON");
                }
            }

            responseStream.close();
        } catch (JsonProcessingException e) {
            throw new IOException("Bitcoin returned unparsable JSON");
        } catch (IOException e) {
            InputStream errorStream = null;
            IOException e2 = null;

            if (connection.getErrorStream() == null)
                throw new IOException("Bitcoin disconnected during response: " + connection.getResponseCode()
                        + " " + connection.getResponseMessage());

            if (connection.getContentEncoding() != null) {
                if (connection.getContentEncoding().equalsIgnoreCase("gzip"))
                    errorStream = new GZIPInputStream(connection.getErrorStream());
                else if (connection.getContentEncoding().equalsIgnoreCase("deflate"))
                    errorStream = new InflaterInputStream(connection.getErrorStream());
            } else {
                errorStream = connection.getErrorStream();
            }

            if (errorStream == null)
                throw new IOException("Bitcoin disconnected during response: " + connection.getResponseCode()
                        + " " + connection.getResponseMessage());

            byte[] errorbuf = new byte[8192];

            if (errorStream.read(errorbuf) < 1)
                throw new IOException("Bitcoin returned an error, but with no message");

            String error = new String(errorbuf).trim();

            if (error.startsWith("{")) {
                try {
                    Object output = mapper.readTree(error);

                    if (NullNode.class.equals(output.getClass()))
                        throw new IOException("Bitcoin returned an error message: " + error);
                    else
                        try {
                            responseMessage = (ObjectNode) output;
                        } catch (ClassCastException f) {
                            throw new IOException("Bitcoin returned unparsable JSON");
                        }

                    if (responseMessage.get("error") != null) {
                        if (responseMessage.get("error").get("message") != null
                                && responseMessage.get("error").get("message").asText() != null) {
                            error = responseMessage.get("error").get("message").asText().trim();
                            e2 = new IOException("Bitcoin returned error message: " + error);
                        } else if (responseMessage.get("error").asText() != null) {
                            error = responseMessage.get("error").asText().trim();

                            if (!"null".equals(error) && !"".equals(error))
                                e2 = new IOException("Bitcoin returned an error message: " + error);
                        }
                    }
                } catch (JsonProcessingException f) {
                    e2 = new IOException("Bitcoin returned unparsable JSON");
                }
            } else {
                e2 = new IOException("Bitcoin returned an error message: " + error);
            }

            errorStream.close();

            if (responseStream != null)
                responseStream.close();

            if (e2 == null)
                e2 = new IOException("Bitcoin returned an error, but with no message");

            throw e2;
        }

        if (responseMessage.get("error") != null) {
            if (responseMessage.get("error").get("message") != null
                    && responseMessage.get("error").get("message").asText() != null) {
                String error = responseMessage.get("error").get("message").asText().trim();
                throw new IOException("Bitcoin returned error message: " + error);
            } else if (responseMessage.get("error").asText() != null) {
                String error = responseMessage.get("error").asText().trim();

                if (!"null".equals(error) && !"".equals(error))
                    throw new IOException("Bitcoin returned error message: " + error);
            }
        }

        JsonNode result;

        try {
            result = responseMessage.get("result");
        } catch (Exception e) {
            throw new IOException("Bitcoin returned unparsable JSON");
        }

        if (result == null)
            throw new IOException("Bitcoin did not return a result or an error");

        return result;
    } catch (IOException e) {
        if (connection != null)
            connection.disconnect();

        throw e;
    }
}

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

public void createDeck(String name) {
    Log.i(AnkiDroidApp.TAG, "createDeck");
    // Log.i(AnkiDroidApp.TAG, "user = " + username + ", password = " + password);

    try {/*from w  w  w  .ja v a2 s  .  c  om*/
        String data = "p=" + URLEncoder.encode(mPassword, "UTF-8") + "&u="
                + URLEncoder.encode(mUsername, "UTF-8") + "&d=None&name=" + URLEncoder.encode(name, "UTF-8");

        // Log.i(AnkiDroidApp.TAG, "Data json = " + data);
        HttpPost httpPost = new HttpPost(SYNC_URL + "createDeck");
        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());
        Log.i(AnkiDroidApp.TAG,
                "String content = " + Utils.convertStreamToString(new InflaterInputStream(content)));

        // Add created deck to the list of decks on server
        mDecks.put(name, new JSONArray("[0,0]"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        Log.i(AnkiDroidApp.TAG, "ClientProtocolException = " + e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
        e.printStackTrace();
    } catch (JSONException e) {
        Log.i(AnkiDroidApp.TAG, "JSONException = " + e.getMessage());
        e.printStackTrace();
    }
}

From source file:com.autonomy.aci.client.transport.impl.AbstractEncryptionCodec.java

/**
 * Strip the <tt>AUTN:</tt> prefix and inflate the given <tt>byte[]</tt> to it's original form.
 * @param bytes The bytes to inflate/*  w  w w . j  a  v  a2 s  .  co  m*/
 * @return The inflated byte array
 * @throws EncryptionCodecException If an error occurred during processing
 */
protected byte[] inflateInternal(final byte[] bytes) throws EncryptionCodecException {
    LOGGER.trace("inflateInternal() called...");

    // This is the input stream...
    InflaterInputStream inflater = null;

    try {
        LOGGER.debug("Stripping AUTN: prefix...");

        // This is the prefix in bytes...
        final byte[] prefix = "AUTN:".getBytes("UTF-8");

        // This will hold the content once it's has the prefix stripped... 
        final byte[] stripped = new byte[bytes.length - prefix.length];

        // Strip the prefix...
        System.arraycopy(bytes, prefix.length, stripped, 0, stripped.length);

        LOGGER.debug("Inflating decrypted input...");

        // Create the input stream...
        inflater = new InflaterInputStream(new ByteArrayInputStream(stripped));

        // Create the output buffer...
        final ByteArrayOutputStream inflated = new ByteArrayOutputStream();

        // Copy from one stream to the other...
        IOUtils.getInstance().copy(inflater, inflated);

        LOGGER.debug("Returning decoded, decrypted and inflated input...");

        // Convert to a string and return...
        return inflated.toByteArray();
    } catch (final IOException ioe) {
        throw new EncryptionCodecException("Unable to inflate decrypted content.", ioe);
    } finally {
        // Close the stream...
        IOUtils.getInstance().closeQuietly(inflater);
    }
}

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

/**
 * Decoding and deflating the encoded AuthReq
 *
 * @param encodedStr encoded AuthReq/*w w  w .j  av a2 s .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);
    }

}