Example usage for java.util.zip GZIPOutputStream write

List of usage examples for java.util.zip GZIPOutputStream write

Introduction

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

Prototype

public void write(int b) throws IOException 

Source Link

Document

Writes a byte to the compressed output stream.

Usage

From source file:com.panet.imeta.www.GetJobStatusServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!request.getContextPath().equals(CONTEXT_PATH))
        return;/*from w  ww .  ja v  a 2s . c  o m*/

    if (log.isDebug())
        log.logDebug(toString(), Messages.getString("GetJobStatusServlet.Log.JobStatusRequested"));

    String jobName = request.getParameter("name");
    boolean useXML = "Y".equalsIgnoreCase(request.getParameter("xml"));

    response.setStatus(HttpServletResponse.SC_OK);

    if (useXML) {
        response.setContentType("text/xml");
        response.setCharacterEncoding(Const.XML_ENCODING);
    } else {
        response.setContentType("text/html");
    }

    PrintWriter out = response.getWriter();

    Job job = jobMap.getJob(jobName);
    if (job != null) {
        String status = job.getStatus();

        if (useXML) {
            response.setContentType("text/xml");
            response.setCharacterEncoding(Const.XML_ENCODING);
            out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING));

            SlaveServerJobStatus jobStatus = new SlaveServerJobStatus(jobName, status);

            Log4jStringAppender appender = (Log4jStringAppender) jobMap.getAppender(jobName);
            if (appender != null) {
                // The log can be quite large at times, we are going to put a base64 encoding around a compressed stream
                // of bytes to handle this one.

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzos = new GZIPOutputStream(baos);
                gzos.write(appender.getBuffer().toString().getBytes());
                gzos.close();

                String loggingString = new String(Base64.encodeBase64(baos.toByteArray()));
                jobStatus.setLoggingString(loggingString);
            }

            // Also set the result object...
            //
            jobStatus.setResult(job.getResult()); // might be null

            out.println(jobStatus.getXML());
        } else {
            response.setContentType("text/html");

            out.println("<HTML>");
            out.println("<HEAD>");
            out.println("<TITLE>" + Messages.getString("GetJobStatusServlet.KettleJobStatus") + "</TITLE>");
            out.println("<META http-equiv=\"Refresh\" content=\"10;url=/kettle/jobStatus?name="
                    + URLEncoder.encode(jobName, "UTF-8") + "\">");
            out.println("</HEAD>");
            out.println("<BODY>");
            out.println("<H1>" + Messages.getString("GetJobStatusServlet.JobStatus") + "</H1>");

            try {
                out.println("<table border=\"1\">");
                out.print("<tr> <th>" + Messages.getString("GetJobStatusServlet.Jobname") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.TransStatus") + "</th> </tr>");

                out.print("<tr>");
                out.print("<td>" + jobName + "</td>");
                out.print("<td>" + status + "</td>");
                out.print("</tr>");
                out.print("</table>");

                out.print("<p>");

                if (job.isFinished()) {
                    out.print("<a href=\"/kettle/startJob?name=" + URLEncoder.encode(jobName, "UTF-8") + "\">"
                            + Messages.getString("GetJobStatusServlet.StartJob") + "</a>");
                    out.print("<p>");
                } else {
                    out.print("<a href=\"/kettle/stopJob?name=" + URLEncoder.encode(jobName, "UTF-8") + "\">"
                            + Messages.getString("GetJobStatusServlet.StopJob") + "</a>");
                    out.print("<p>");
                }

                out.println("<p>");

                out.print("<a href=\"/kettle/jobStatus/?name=" + URLEncoder.encode(jobName, "UTF-8")
                        + "&xml=y\">" + Messages.getString("TransStatusServlet.ShowAsXml") + "</a><br>");
                out.print("<a href=\"/kettle/status\">"
                        + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><br>");
                out.print("<p><a href=\"/kettle/jobStatus?name=" + URLEncoder.encode(jobName, "UTF-8") + "\">"
                        + Messages.getString("TransStatusServlet.Refresh") + "</a>");

                // Put the logging below that.
                Log4jStringAppender appender = (Log4jStringAppender) jobMap.getAppender(jobName);
                if (appender != null) {
                    out.println("<p>");
                    /*
                    out.println("<pre>");
                    out.println(appender.getBuffer().toString());
                    out.println("</pre>");
                    */
                    out.println(
                            "<textarea id=\"joblog\" cols=\"120\" rows=\"20\" wrap=\"off\" name=\"Job log\" readonly=\"readonly\">"
                                    + appender.getBuffer().toString() + "</textarea>");

                    out.println("<script type=\"text/javascript\"> ");
                    out.println("  joblog.scrollTop=joblog.scrollHeight; ");
                    out.println("</script> ");
                    out.println("<p>");
                }
            } catch (Exception ex) {
                out.println("<p>");
                out.println("<pre>");
                ex.printStackTrace(out);
                out.println("</pre>");
            }

            out.println("<p>");
            out.println("</BODY>");
            out.println("</HTML>");
        }
    } else {
        if (useXML) {
            out.println(new WebResult(WebResult.STRING_ERROR,
                    Messages.getString("StartJobServlet.Log.SpecifiedJobNotFound", jobName)));
        } else {
            out.println("<H1>Job '" + jobName + "' could not be found.</H1>");
            out.println("<a href=\"/kettle/status\">"
                    + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><p>");
        }
    }
}

From source file:org.apache.roller.weblogger.ui.core.filters.CompressionFilter.java

/** 
 * If browser does not support gzip, invoke resource normally. If browser 
 * does support gzip, set the Content-Encoding response header and invoke 
 * resource with a wrapped response that collects all the output. Extract 
 * the output and write it into a gzipped byte array. Finally, write that 
 * array to the client's output stream.//from  w  ww  .j  av a  2s . com
 */
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws ServletException, IOException {

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse res = (HttpServletResponse) response;

    if (!this.enabled || !isGzipSupported(req)) {
        // Invoke resource normally.
        chain.doFilter(req, res);
    } else {
        // Tell browser we are sending it gzipped data.
        res.setHeader("Content-Encoding", "gzip");

        // Invoke resource, accumulating output in the wrapper.
        ByteArrayResponseWrapper responseWrapper = new ByteArrayResponseWrapper(response);

        chain.doFilter(req, responseWrapper);

        ByteArrayOutputStream outputStream = responseWrapper.getByteArrayOutputStream();

        // Get character array representing output.
        log.debug("Pre-zip size:" + outputStream.size());

        // Make a writer that compresses data and puts
        // it into a byte array.
        ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
        GZIPOutputStream zipOut = new GZIPOutputStream(byteStream);

        // Compress original output and put it into byte array.
        zipOut.write(responseWrapper.getByteArrayOutputStream().toByteArray());

        // Gzip streams must be explicitly closed.
        zipOut.close();

        log.debug("Gzip size:" + byteStream.size());

        // Update the Content-Length header.
        res.setContentLength(byteStream.size());

        ByteArrayOutputStreamWrapper newOut = (ByteArrayOutputStreamWrapper) responseWrapper.getOutputStream();
        newOut.clear();
        newOut.setFinallized();

        /* now force close of OutputStream */
        newOut.write(byteStream.toByteArray());
        newOut.close();
    }

}

From source file:parquet.hadoop.ParquetInputSplit.java

String compressString(String str) {
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip;
    try {/*from   ww w . j a v  a2 s  .co m*/
        gzip = new GZIPOutputStream(obj);
        gzip.write(str.getBytes("UTF-8"));
        gzip.close();
    } catch (IOException e) {
        // Not really sure how we can get here. I guess the best thing to do is to croak.
        LOG.error("Unable to gzip InputSplit string " + str, e);
        throw new RuntimeException("Unable to gzip InputSplit string", e);
    }
    String compressedStr = Base64.encodeBase64String(obj.toByteArray());
    return compressedStr;
}

From source file:org.xenei.compressedgraph.SerializableNode.java

public SerializableNode(Node n) throws IOException {
    super(n);/* w  ww.  j  a  v a 2s  .c o m*/
    if (n.equals(Node.ANY)) {
        // ANY has a hash code of 0
        fillBuffer(WILD, 0, _ANY, null);
    } else if (n.isVariable()) {
        fillBuffer(WILD, n.hashCode(), _VAR, encodeString(n.getName()));
    } else if (n.isURI()) {
        fillBuffer(WILD, n.hashCode(), _URI, encodeString(n.getURI()));
    } else if (n.isBlank()) {
        fillBuffer(WILD, n.hashCode(), _ANON, encodeString(n.getBlankNodeId().getLabelString()));
    } else if (n.isLiteral()) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        DataOutputStream os = new DataOutputStream(baos);
        write(os, n.getLiteralLexicalForm());
        write(os, n.getLiteralLanguage());
        write(os, n.getLiteralDatatypeURI());

        os.close();
        baos.close();
        byte[] value = baos.toByteArray();
        if (value.length > MAX_STR_SIZE) {
            baos = new ByteArrayOutputStream();
            GZIPOutputStream dos = new GZIPOutputStream(baos);
            dos.write(value);
            dos.close();
            fillBuffer(WILD, n.hashCode(), (byte) (_LIT | _COMPRESSED), baos.toByteArray());
        } else {
            fillBuffer(WILD, n.hashCode(), _LIT, value);
        }
    } else {
        throw new IllegalArgumentException("Unknown node type " + n);
    }
}

From source file:com.github.abilityapi.abilityapi.external.Metrics.java

/**
 * Gzips the given String./*from   ww w. j a v a2s .  c  o m*/
 *
 * @param str The string to gzip.
 * @return The gzipped String.
 * @throws IOException If the compression failed.
 */
private static byte[] compress(final String str) throws IOException {
    if (str == null) {
        return null;
    }
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(outputStream);
    gzip.write(str.getBytes("UTF-8"));
    gzip.close();
    return outputStream.toByteArray();
}

From source file:org.pentaho.di.www.GetJobStatusServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (isJettyMode() && !request.getContextPath().startsWith(CONTEXT_PATH)) {
        return;//from  w  w w  .ja  v  a2 s  .c o  m
    }

    if (log.isDebug())
        logDebug(BaseMessages.getString(PKG, "GetJobStatusServlet.Log.JobStatusRequested"));

    String jobName = request.getParameter("name");
    String id = request.getParameter("id");
    boolean useXML = "Y".equalsIgnoreCase(request.getParameter("xml"));
    int startLineNr = Const.toInt(request.getParameter("from"), 0);

    response.setStatus(HttpServletResponse.SC_OK);

    if (useXML) {
        response.setContentType("text/xml");
        response.setCharacterEncoding(Const.XML_ENCODING);
    } else {
        response.setContentType("text/html;charset=UTF-8");
    }

    PrintWriter out = response.getWriter();

    // ID is optional...
    //
    Job job;
    CarteObjectEntry entry;
    if (Const.isEmpty(id)) {
        // get the first job that matches...
        //
        entry = getJobMap().getFirstCarteObjectEntry(jobName);
        if (entry == null) {
            job = null;
        } else {
            id = entry.getId();
            job = getJobMap().getJob(entry);
        }
    } else {
        // Take the ID into account!
        //
        entry = new CarteObjectEntry(jobName, id);
        job = getJobMap().getJob(entry);
    }

    if (job != null) {
        String status = job.getStatus();
        int lastLineNr = CentralLogStore.getLastBufferLineNr();
        String logText = CentralLogStore.getAppender()
                .getBuffer(job.getLogChannel().getLogChannelId(), false, startLineNr, lastLineNr).toString();

        if (useXML) {
            response.setContentType("text/xml");
            response.setCharacterEncoding(Const.XML_ENCODING);
            out.print(XMLHandler.getXMLHeader(Const.XML_ENCODING));

            SlaveServerJobStatus jobStatus = new SlaveServerJobStatus(jobName, id, status);
            jobStatus.setFirstLoggingLineNr(startLineNr);
            jobStatus.setLastLoggingLineNr(lastLineNr);

            // The log can be quite large at times, we are going to put a base64 encoding around a compressed stream
            // of bytes to handle this one.

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            GZIPOutputStream gzos = new GZIPOutputStream(baos);
            gzos.write(logText.getBytes());
            gzos.close();

            String loggingString = new String(Base64.encodeBase64(baos.toByteArray()));
            jobStatus.setLoggingString(loggingString);

            // Also set the result object...
            //
            jobStatus.setResult(job.getResult()); // might be null

            try {
                out.println(jobStatus.getXML());
            } catch (KettleException e) {
                throw new ServletException("Unable to get the job status in XML format", e);
            }
        } else {
            response.setContentType("text/html");

            out.println("<HTML>");
            out.println("<HEAD>");
            out.println("<TITLE>" + BaseMessages.getString(PKG, "GetJobStatusServlet.KettleJobStatus")
                    + "</TITLE>");
            out.println("<META http-equiv=\"Refresh\" content=\"10;url="
                    + convertContextPath(GetJobStatusServlet.CONTEXT_PATH) + "?name="
                    + URLEncoder.encode(jobName, "UTF-8") + "&id=" + id + "\">");
            out.println("<META http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">");
            out.println("</HEAD>");
            out.println("<BODY>");
            out.println("<H1>" + BaseMessages.getString(PKG, "GetJobStatusServlet.JobStatus") + "</H1>");

            try {
                out.println("<table border=\"1\">");
                out.print("<tr> <th>" + BaseMessages.getString(PKG, "GetJobStatusServlet.Jobname")
                        + "</th> <th>" + BaseMessages.getString(PKG, "TransStatusServlet.TransStatus")
                        + "</th> </tr>");

                out.print("<tr>");
                out.print("<td>" + jobName + "</td>");
                out.print("<td>" + status + "</td>");
                out.print("</tr>");
                out.print("</table>");

                out.print("<p>");

                if (job.isFinished()) {
                    out.print("<a href=\"" + convertContextPath(StartJobServlet.CONTEXT_PATH) + "?name="
                            + URLEncoder.encode(jobName, "UTF-8") + "&id=" + id + "\">"
                            + BaseMessages.getString(PKG, "GetJobStatusServlet.StartJob") + "</a>");
                    out.print("<p>");
                } else {
                    out.print("<a href=\"" + convertContextPath(StopJobServlet.CONTEXT_PATH) + "?name="
                            + URLEncoder.encode(jobName, "UTF-8") + "&id=" + id + "\">"
                            + BaseMessages.getString(PKG, "GetJobStatusServlet.StopJob") + "</a>");
                    out.print("<p>");
                }

                out.println("<p>");

                out.print("<a href=\"" + convertContextPath(GetJobStatusServlet.CONTEXT_PATH) + "?name="
                        + URLEncoder.encode(jobName, "UTF-8") + "&xml=y&id=" + id + "\">"
                        + BaseMessages.getString(PKG, "TransStatusServlet.ShowAsXml") + "</a><br>");
                out.print("<a href=\"" + convertContextPath(GetStatusServlet.CONTEXT_PATH) + "\">"
                        + BaseMessages.getString(PKG, "TransStatusServlet.BackToStatusPage") + "</a><br>");
                out.print("<p><a href=\"" + convertContextPath(GetJobStatusServlet.CONTEXT_PATH) + "?name="
                        + URLEncoder.encode(jobName, "UTF-8") + "&id=" + id + "\">"
                        + BaseMessages.getString(PKG, "TransStatusServlet.Refresh") + "</a>");

                // Put the logging below that.

                out.println("<p>");
                out.println(
                        "<textarea id=\"joblog\" cols=\"120\" rows=\"20\" wrap=\"off\" name=\"Job log\" readonly=\"readonly\">"
                                + logText + "</textarea>");

                out.println("<script type=\"text/javascript\"> ");
                out.println("  joblog.scrollTop=joblog.scrollHeight; ");
                out.println("</script> ");
                out.println("<p>");
            } catch (Exception ex) {
                out.println("<p>");
                out.println("<pre>");
                ex.printStackTrace(out);
                out.println("</pre>");
            }

            out.println("<p>");
            out.println("</BODY>");
            out.println("</HTML>");
        }
    } else {
        if (useXML) {
            out.println(new WebResult(WebResult.STRING_ERROR,
                    BaseMessages.getString(PKG, "StartJobServlet.Log.SpecifiedJobNotFound", jobName, id)));
        } else {
            out.println("<H1>Job '" + jobName + "' could not be found.</H1>");
            out.println("<a href=\"" + convertContextPath(GetStatusServlet.CONTEXT_PATH) + "\">"
                    + BaseMessages.getString(PKG, "TransStatusServlet.BackToStatusPage") + "</a><p>");
        }
    }
}

From source file:de.schildbach.wallet.ui.TransactionFragment.java

public void update(final Transaction tx) {
    final Wallet wallet = ((WalletApplication) activity.getApplication()).getWallet();

    final byte[] serializedTx = tx.unsafeBitcoinSerialize();

    Address from = null;//from  ww  w. j  a va2 s  .  co  m
    boolean fromMine = false;
    try {
        from = tx.getInputs().get(0).getFromAddress();
        fromMine = wallet.isPubKeyHashMine(from.getHash160());
    } catch (final ScriptException x) {
        x.printStackTrace();
    }

    Address to = null;
    boolean toMine = false;
    try {
        to = tx.getOutputs().get(0).getScriptPubKey().getToAddress();
        toMine = wallet.isPubKeyHashMine(to.getHash160());
    } catch (final ScriptException x) {
        x.printStackTrace();
    }

    final ContentResolver contentResolver = activity.getContentResolver();

    final View view = getView();

    final Date time = tx.getUpdateTime();
    view.findViewById(R.id.transaction_fragment_time_row)
            .setVisibility(time != null ? View.VISIBLE : View.GONE);
    if (time != null) {
        final TextView viewDate = (TextView) view.findViewById(R.id.transaction_fragment_time);
        viewDate.setText(
                (DateUtils.isToday(time.getTime()) ? getString(R.string.time_today) : dateFormat.format(time))
                        + ", " + timeFormat.format(time));
    }

    try {
        final BigInteger amountSent = tx.getValueSentFromMe(wallet);
        view.findViewById(R.id.transaction_fragment_amount_sent_row)
                .setVisibility(amountSent.signum() != 0 ? View.VISIBLE : View.GONE);
        if (amountSent.signum() != 0) {
            final TextView viewAmountSent = (TextView) view.findViewById(R.id.transaction_fragment_amount_sent);
            viewAmountSent.setText(Constants.CURRENCY_MINUS_SIGN + WalletUtils.formatValue(amountSent));
        }
    } catch (final ScriptException x) {
        x.printStackTrace();
    }

    final BigInteger amountReceived = tx.getValueSentToMe(wallet);
    view.findViewById(R.id.transaction_fragment_amount_received_row)
            .setVisibility(amountReceived.signum() != 0 ? View.VISIBLE : View.GONE);
    if (amountReceived.signum() != 0) {
        final TextView viewAmountReceived = (TextView) view
                .findViewById(R.id.transaction_fragment_amount_received);
        viewAmountReceived.setText(Constants.CURRENCY_PLUS_SIGN + WalletUtils.formatValue(amountReceived));
    }

    final View viewFromButton = view.findViewById(R.id.transaction_fragment_from_button);
    final TextView viewFromLabel = (TextView) view.findViewById(R.id.transaction_fragment_from_label);
    if (from != null) {
        final String label = AddressBookProvider.resolveLabel(contentResolver, from.toString());
        final StringBuilder builder = new StringBuilder();

        if (fromMine)
            builder.append(getString(R.string.transaction_fragment_you)).append(", ");

        if (label != null) {
            builder.append(label);
        } else {
            builder.append(from.toString());
            viewFromLabel.setTypeface(Typeface.MONOSPACE);
        }

        viewFromLabel.setText(builder.toString());

        final String addressStr = from.toString();
        viewFromButton.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                EditAddressBookEntryFragment.edit(getFragmentManager(), addressStr);
            }
        });
    } else {
        viewFromLabel.setText(null);
    }

    final View viewToButton = view.findViewById(R.id.transaction_fragment_to_button);
    final TextView viewToLabel = (TextView) view.findViewById(R.id.transaction_fragment_to_label);
    if (to != null) {
        final String label = AddressBookProvider.resolveLabel(contentResolver, to.toString());
        final StringBuilder builder = new StringBuilder();

        if (toMine)
            builder.append(getString(R.string.transaction_fragment_you)).append(", ");

        if (label != null) {
            builder.append(label);
        } else {
            builder.append(to.toString());
            viewToLabel.setTypeface(Typeface.MONOSPACE);
        }

        viewToLabel.setText(builder.toString());

        final String addressStr = to.toString();
        viewToButton.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                EditAddressBookEntryFragment.edit(getFragmentManager(), addressStr);
            }
        });
    } else {
        viewToLabel.setText(null);
    }

    final TextView viewStatus = (TextView) view.findViewById(R.id.transaction_fragment_status);
    final ConfidenceType confidenceType = tx.getConfidence().getConfidenceType();
    if (confidenceType == ConfidenceType.DEAD || confidenceType == ConfidenceType.NOT_IN_BEST_CHAIN)
        viewStatus.setText(R.string.transaction_fragment_status_dead);
    else if (confidenceType == ConfidenceType.NOT_SEEN_IN_CHAIN)
        viewStatus.setText(R.string.transaction_fragment_status_pending);
    else if (confidenceType == ConfidenceType.BUILDING)
        viewStatus.setText(R.string.transaction_fragment_status_confirmed);
    else
        viewStatus.setText(R.string.transaction_fragment_status_unknown);

    final TextView viewHash = (TextView) view.findViewById(R.id.transaction_fragment_hash);
    viewHash.setText(tx.getHash().toString());

    final TextView viewLength = (TextView) view.findViewById(R.id.transaction_fragment_length);
    viewLength.setText(Integer.toString(serializedTx.length));

    final ImageView viewQr = (ImageView) view.findViewById(R.id.transaction_fragment_qr);

    try {
        // encode transaction URI
        final ByteArrayOutputStream bos = new ByteArrayOutputStream(serializedTx.length);
        final GZIPOutputStream gos = new GZIPOutputStream(bos);
        gos.write(serializedTx);
        gos.close();

        final byte[] gzippedSerializedTx = bos.toByteArray();
        final boolean useCompressioon = gzippedSerializedTx.length < serializedTx.length;

        final StringBuilder txStr = new StringBuilder("btctx:");
        txStr.append(useCompressioon ? 'Z' : '-');
        txStr.append(Base43.encode(useCompressioon ? gzippedSerializedTx : serializedTx));

        final Bitmap qrCodeBitmap = WalletUtils.getQRCodeBitmap(txStr.toString().toUpperCase(Locale.US), 512);
        viewQr.setImageBitmap(qrCodeBitmap);
        viewQr.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                BitmapFragment.show(getFragmentManager(), qrCodeBitmap);
            }
        });
    } catch (final IOException x) {
        throw new RuntimeException(x);
    }
}

From source file:com.chenshu.compress.CompressOldTest.java

@Benchmark
public int jdkGzipCompress() {
    ByteArrayOutputStream bout = null;
    GZIPOutputStream gzout = null;
    try {/*from w  ww  .j a  v  a2 s. com*/
        bout = new ByteArrayOutputStream(data.length);
        gzout = new GZIPOutputStream(bout) {
            {
                def.setLevel(level);
            }
        };
        gzout.write(data);
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (gzout != null) {
            try {
                gzout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (bout != null) {
            try {
                bout.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    byte[] bs = bout.toByteArray();
    return bs.length;
}

From source file:com.kkbox.toolkit.internal.api.APIRequest.java

public void addGZIPPostParam(String key, String value) {
    try {/*w w  w  .j a  v  a 2  s .  c o m*/
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ArrayList<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add((new BasicNameValuePair(key, value)));
        GZIPOutputStream gZIPOutputStream = new GZIPOutputStream(byteArrayOutputStream);
        gZIPOutputStream.write(EntityUtils.toByteArray(new UrlEncodedFormEntity(postParams, HTTP.UTF_8)));
        gZIPOutputStream.close();
        byte[] byteDataForGZIP = byteArrayOutputStream.toByteArray();
        byteArrayOutputStream.close();
        gzipStreamEntity = new InputStreamEntity(new ByteArrayInputStream(byteDataForGZIP),
                byteDataForGZIP.length);
        gzipStreamEntity.setContentType("application/x-www-form-urlencoded");
        gzipStreamEntity.setContentEncoding("gzip");
    } catch (Exception e) {
    }
}

From source file:piuk.blockchain.android.ui.TransactionFragment.java

public void update(final MyTransaction tx) {

    final MyRemoteWallet wallet = ((WalletApplication) activity.getApplication()).getRemoteWallet();

    final byte[] serializedTx = tx.unsafeBitcoinSerialize();

    Address from = null;//from  www. j ava 2  s . c om
    boolean fromMine = false;
    try {
        from = tx.getInputs().get(0).getFromAddress();
        fromMine = wallet.isMine(from.toString());
    } catch (final ScriptException x) {
        x.printStackTrace();
    }

    Address to = null;
    boolean toMine = false;
    try {
        to = tx.getOutputs().get(0).getScriptPubKey().getToAddress();
        toMine = wallet.isMine(to.toString());
    } catch (final ScriptException x) {
        x.printStackTrace();
    }

    final ContentResolver contentResolver = activity.getContentResolver();

    final View view = getView();

    final Date time = tx.getUpdateTime();
    view.findViewById(R.id.transaction_fragment_time_row)
            .setVisibility(time != null ? View.VISIBLE : View.GONE);
    if (time != null) {
        final TextView viewDate = (TextView) view.findViewById(R.id.transaction_fragment_time);
        viewDate.setText(
                (DateUtils.isToday(time.getTime()) ? getString(R.string.transaction_fragment_time_today)
                        : dateFormat.format(time)) + ", " + timeFormat.format(time));
    }

    final BigInteger amountSent = tx.getResult();
    view.findViewById(R.id.transaction_fragment_amount_sent_row)
            .setVisibility(amountSent.signum() != 0 ? View.VISIBLE : View.GONE);
    if (amountSent.signum() != 0) {
        final TextView viewAmountSent = (TextView) view.findViewById(R.id.transaction_fragment_amount_sent);
        viewAmountSent.setText(Constants.CURRENCY_MINUS_SIGN + WalletUtils.formatValue(amountSent));
    }

    final BigInteger amountReceived = tx.getResult();
    view.findViewById(R.id.transaction_fragment_amount_received_row)
            .setVisibility(amountReceived.signum() != 0 ? View.VISIBLE : View.GONE);
    if (amountReceived.signum() != 0) {
        final TextView viewAmountReceived = (TextView) view
                .findViewById(R.id.transaction_fragment_amount_received);
        viewAmountReceived.setText(Constants.CURRENCY_PLUS_SIGN + WalletUtils.formatValue(amountReceived));
    }

    final View viewFromButton = view.findViewById(R.id.transaction_fragment_from_button);
    final TextView viewFromLabel = (TextView) view.findViewById(R.id.transaction_fragment_from_label);
    if (from != null) {
        String label = null;
        if (tx instanceof MyTransaction && ((MyTransaction) tx).getTag() != null)
            label = ((MyTransaction) tx).getTag();
        else
            label = AddressBookProvider.resolveLabel(contentResolver, from.toString());

        final StringBuilder builder = new StringBuilder();

        if (fromMine)
            builder.append(getString(R.string.transaction_fragment_you)).append(", ");

        if (label != null) {
            builder.append(label);
        } else {
            builder.append(from.toString());
            viewFromLabel.setTypeface(Typeface.MONOSPACE);
        }

        viewFromLabel.setText(builder.toString());

        final String addressStr = from.toString();
        viewFromButton.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                EditAddressBookEntryFragment.edit(getFragmentManager(), addressStr);
            }
        });
    } else {
        viewFromLabel.setText(null);
    }

    final View viewToButton = view.findViewById(R.id.transaction_fragment_to_button);
    final TextView viewToLabel = (TextView) view.findViewById(R.id.transaction_fragment_to_label);
    if (to != null) {

        String label = null;
        if (tx instanceof MyTransaction && ((MyTransaction) tx).getTag() != null)
            label = ((MyTransaction) tx).getTag();
        else
            label = AddressBookProvider.resolveLabel(contentResolver, from.toString());

        final StringBuilder builder = new StringBuilder();

        if (toMine)
            builder.append(getString(R.string.transaction_fragment_you)).append(", ");

        if (label != null) {
            builder.append(label);
        } else {
            builder.append(to.toString());
            viewToLabel.setTypeface(Typeface.MONOSPACE);
        }

        viewToLabel.setText(builder.toString());

        final String addressStr = to.toString();
        viewToButton.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                EditAddressBookEntryFragment.edit(getFragmentManager(), addressStr);
            }
        });
    } else {
        viewToLabel.setText(null);
    }

    final TextView viewStatus = (TextView) view.findViewById(R.id.transaction_fragment_status);
    final ConfidenceType confidenceType = tx.getConfidence().getConfidenceType();
    if (confidenceType == ConfidenceType.DEAD || confidenceType == ConfidenceType.NOT_IN_BEST_CHAIN)
        viewStatus.setText(R.string.transaction_fragment_status_dead);
    else if (confidenceType == ConfidenceType.NOT_SEEN_IN_CHAIN)
        viewStatus.setText(R.string.transaction_fragment_status_pending);
    else if (confidenceType == ConfidenceType.BUILDING)
        viewStatus.setText(R.string.transaction_fragment_status_confirmed);
    else
        viewStatus.setText(R.string.transaction_fragment_status_unknown);

    final TextView viewHash = (TextView) view.findViewById(R.id.transaction_fragment_hash);
    viewHash.setText(tx.getHash().toString());

    final TextView viewLength = (TextView) view.findViewById(R.id.transaction_fragment_length);
    viewLength.setText(Integer.toString(serializedTx.length));

    final ImageView viewQr = (ImageView) view.findViewById(R.id.transaction_fragment_qr);

    try {
        // encode transaction URI
        final ByteArrayOutputStream bos = new ByteArrayOutputStream(serializedTx.length);
        final GZIPOutputStream gos = new GZIPOutputStream(bos);
        gos.write(serializedTx);
        gos.close();

        final byte[] gzippedSerializedTx = bos.toByteArray();
        final boolean useCompressioon = gzippedSerializedTx.length < serializedTx.length;

        final StringBuilder txStr = new StringBuilder("btctx:");
        txStr.append(useCompressioon ? 'Z' : '-');
        txStr.append(Base43.encode(useCompressioon ? gzippedSerializedTx : serializedTx));

        final Bitmap qrCodeBitmap = WalletUtils.getQRCodeBitmap(txStr.toString().toUpperCase(), 512);
        viewQr.setImageBitmap(qrCodeBitmap);
        viewQr.setOnClickListener(new OnClickListener() {
            public void onClick(final View v) {
                new QrDialog(activity, qrCodeBitmap).show();
            }
        });
    } catch (final IOException x) {
        throw new RuntimeException(x);
    }
}