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.GetTransStatusServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!request.getContextPath().equals(CONTEXT_PATH))
        return;//from   w  w w  . j a  v a2  s.  com

    if (log.isDebug())
        log.logDebug(toString(), Messages.getString("TransStatusServlet.Log.TransStatusRequested"));

    String transName = 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();

    Trans trans = transformationMap.getTransformation(transName);

    if (trans != null) {
        String status = trans.getStatus();

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

            SlaveServerTransStatus transStatus = new SlaveServerTransStatus(transName, status);

            for (int i = 0; i < trans.nrSteps(); i++) {
                BaseStep baseStep = trans.getRunThread(i);
                if ((baseStep.isAlive()) || baseStep.getStatus() != StepDataInterface.STATUS_EMPTY) {
                    StepStatus stepStatus = new StepStatus(baseStep);
                    transStatus.getStepStatusList().add(stepStatus);
                }
            }

            Log4jStringAppender appender = (Log4jStringAppender) transformationMap.getAppender(transName);
            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()));
                transStatus.setLoggingString(loggingString);
            }

            // Also set the result object...
            //
            transStatus.setResult(trans.getResult());

            // Is the transformation paused?
            //
            transStatus.setPaused(trans.isPaused());

            // Send the result back as XML
            //
            out.println(transStatus.getXML());
        } else {
            response.setContentType("text/html");

            out.println("<HTML>");
            out.println("<HEAD>");
            out.println("<TITLE>" + Messages.getString("TransStatusServlet.KettleTransStatus") + "</TITLE>");
            out.println("<META http-equiv=\"Refresh\" content=\"10;url=/kettle/transStatus?name="
                    + URLEncoder.encode(transName, "UTF-8") + "\">");
            out.println("</HEAD>");
            out.println("<BODY>");
            out.println("<H1>" + Messages.getString("TransStatusServlet.TopTransStatus", transName) + "</H1>");

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

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

                out.print("<p>");

                if ((trans.isFinished() && trans.isRunning())
                        || (!trans.isRunning() && !trans.isPreparing() && !trans.isInitializing())) {
                    out.print("<a href=\"/kettle/startTrans?name=" + URLEncoder.encode(transName, "UTF-8")
                            + "\">" + Messages.getString("TransStatusServlet.StartTrans") + "</a>");
                    out.print("<p>");
                    out.print("<a href=\"/kettle/prepareExec?name=" + URLEncoder.encode(transName, "UTF-8")
                            + "\">" + Messages.getString("TransStatusServlet.PrepareTrans") + "</a><br>");
                    //out.print("<a href=\"/kettle/startExec?name="+URLEncoder.encode(transName, "UTF-8")+"\">" + Messages.getString("TransStatusServlet.StartTrans") + "</a><p>");
                } else if (trans.isRunning()) {
                    out.print("<a href=\"/kettle/pauseTrans?name=" + URLEncoder.encode(transName, "UTF-8")
                            + "\">" + Messages.getString("PauseStatusServlet.PauseResumeTrans") + "</a><br>");
                    out.print("<a href=\"/kettle/stopTrans?name=" + URLEncoder.encode(transName, "UTF-8")
                            + "\">" + Messages.getString("TransStatusServlet.StopTrans") + "</a>");
                    out.print("<p>");
                }
                out.print("<a href=\"/kettle/cleanupTrans?name=" + URLEncoder.encode(transName, "UTF-8") + "\">"
                        + Messages.getString("TransStatusServlet.CleanupTrans") + "</a>");
                out.print("<p>");

                out.println("<table border=\"1\">");
                out.print("<tr> <th>" + Messages.getString("TransStatusServlet.Stepname") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.CopyNr") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Read") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Written") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Input") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Output") + "</th> " + "<th>"
                        + Messages.getString("TransStatusServlet.Updated") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Rejected") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Errors") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Active") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.Time") + "</th> " + "<th>"
                        + Messages.getString("TransStatusServlet.Speed") + "</th> <th>"
                        + Messages.getString("TransStatusServlet.prinout") + "</th> </tr>");

                for (int i = 0; i < trans.nrSteps(); i++) {
                    BaseStep baseStep = trans.getRunThread(i);
                    if ((baseStep.isAlive()) || baseStep.getStatus() != StepDataInterface.STATUS_EMPTY) {
                        StepStatus stepStatus = new StepStatus(baseStep);
                        out.print(stepStatus.getHTMLTableRow());
                    }
                }
                out.println("</table>");
                out.println("<p>");

                out.print("<a href=\"/kettle/transStatus/?name=" + URLEncoder.encode(transName, "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/transStatus?name=" + URLEncoder.encode(transName, "UTF-8")
                        + "\">" + Messages.getString("TransStatusServlet.Refresh") + "</a>");

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

                    out.println("<script type=\"text/javascript\"> ");
                    out.println("  translog.scrollTop=translog.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("TransStatusServlet.Log.CoundNotFindSpecTrans", transName)));
        } else {
            out.println("<H1>" + Messages.getString("TransStatusServlet.Log.CoundNotFindTrans", transName)
                    + "</H1>");
            out.println("<a href=\"/kettle/status\">"
                    + Messages.getString("TransStatusServlet.BackToStatusPage") + "</a><p>");

        }
    }
}

From source file:net.sf.ehcache.constructs.web.PageInfoTest.java

/**
 * @param ungzipped the bytes to be gzipped
 * @return gzipped bytes//  w  ww .  jav  a 2 s  . c om
 */
private byte[] gzip(byte[] ungzipped) throws IOException {
    final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes);
    gzipOutputStream.write(ungzipped);
    gzipOutputStream.close();
    return bytes.toByteArray();
}

From source file:rapture.common.client.BaseHttpApi.java

private byte[] getCompressedParams(String request) {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = null;
    try {//  ww w.  ja  v a  2  s. c o  m
        gzos = new GZIPOutputStream(baos);
        gzos.write(request.getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        return null;
    } catch (IOException e) {
        return null;
    } finally {
        if (gzos != null) {
            try {
                gzos.close();
            } catch (IOException ignore) {

            }
        }
    }
    return baos.toByteArray();
}

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

/**
 * Create a serializable node from a node and limit the buffer size. If the
 * serialized node is a literal and exceeds the maximum buffer size the data
 * are compressed before writing and decompressed on reading.
 * /*  ww w  .jav a2 s . c  o m*/
 * @param n
 *            the node to wrap.
 * @param maxBlob
 *            The maximum buffer size.
 * @throws IOException
 *             on error.
 */
public SerializableNode(Node n, int maxBlob) throws IOException {
    this.node = new SoftReference<Node>(n);
    if (n.equals(Node.ANY)) {
        fillBuffer(Node.ANY.hashCode(), _ANY, null);
    } else if (n.isVariable()) {
        fillBuffer(n.hashCode(), _VAR, encodeString(n.getName()));
    } else if (n.isURI()) {
        fillBuffer(n.hashCode(), _URI, encodeString(n.getURI()));
    } else if (n.isBlank()) {
        fillBuffer(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 > maxBlob) {
            baos = new ByteArrayOutputStream();
            GZIPOutputStream dos = new GZIPOutputStream(baos);
            dos.write(value);
            dos.close();
            fillBuffer(n.hashCode(), (byte) (_LIT | _COMPRESSED), baos.toByteArray());
        } else {
            fillBuffer(n.hashCode(), _LIT, value);
        }
    } else {
        throw new IllegalArgumentException("Unknown node type " + n);
    }
}

From source file:com.parse.ParseOkHttpClientTest.java

@Test
public void testParseOkHttpClientExecuteWithExternalInterceptorAndGZIPResponse() throws Exception {
    // Make mock response
    Buffer buffer = new Buffer();
    final ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write("content".getBytes());
    gzipOut.close();/*from  w ww .jav a  2 s  . c  o m*/
    buffer.write(byteOut.toByteArray());
    MockResponse mockResponse = new MockResponse().setStatus("HTTP/1.1 " + 201 + " " + "OK").setBody(buffer)
            .setHeader("Content-Encoding", "gzip");

    // Start mock server
    server.enqueue(mockResponse);
    server.start();

    ParseHttpClient client = new ParseOkHttpClient(10000, null);

    final Semaphore done = new Semaphore(0);
    // Add plain interceptor to disable decompress response stream
    client.addExternalInterceptor(new ParseNetworkInterceptor() {
        @Override
        public ParseHttpResponse intercept(Chain chain) throws IOException {
            done.release();
            ParseHttpResponse parseResponse = chain.proceed(chain.getRequest());
            // Make sure the response we get from the interceptor is the raw gzip stream
            byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
            assertArrayEquals(byteOut.toByteArray(), content);

            // We need to set a new stream since we have read it
            return new ParseHttpResponse.Builder().setContent(new ByteArrayInputStream(byteOut.toByteArray()))
                    .build();
        }
    });

    // We do not need to add Accept-Encoding header manually, httpClient library should do that.
    String requestUrl = server.getUrl("/").toString();
    ParseHttpRequest parseRequest = new ParseHttpRequest.Builder().setUrl(requestUrl)
            .setMethod(ParseHttpRequest.Method.GET).build();

    // Execute request
    ParseHttpResponse parseResponse = client.execute(parseRequest);

    // Make sure the response we get is ungziped by OkHttp library
    byte[] content = ParseIOUtils.toByteArray(parseResponse.getContent());
    assertArrayEquals("content".getBytes(), content);
    // Make sure interceptor is called
    assertTrue(done.tryAcquire(10, TimeUnit.SECONDS));

    server.shutdown();
}

From source file:grails.plugin.cache.web.PageInfo.java

/**
 * @param ungzipped the bytes to be gzipped
 * @return gzipped bytes/* ww  w . ja v  a 2  s  .co m*/
 */
protected byte[] gzip(byte[] ungzipped) throws IOException, AlreadyGzippedException {
    if (isGzipped(ungzipped)) {
        throw new AlreadyGzippedException("The byte[] is already gzipped. It should not be gzipped again.");
    }
    ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes);
    gzipOutputStream.write(ungzipped);
    gzipOutputStream.close();
    return bytes.toByteArray();
}

From source file:org.jabsorb.JSONRPCServlet.java

/**
 * Gzip something./*  w ww  . j  ava  2s .co  m*/
 *
 * @param in original content
 * @return size gzipped content
 */
private byte[] gzip(byte[] in) {
    if (in != null && in.length > 0) {
        long tstart = System.currentTimeMillis();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        try {
            GZIPOutputStream gout = new GZIPOutputStream(bout);
            gout.write(in);
            gout.flush();
            gout.close();
            if (log.isDebugEnabled()) {
                log.debug("gzipping took " + (System.currentTimeMillis() - tstart) + " msec");
            }
            return bout.toByteArray();
        } catch (IOException io) {
            log.error("io exception gzipping byte array", io);
        }
    }
    return new byte[0];
}

From source file:com.taobao.android.builder.tasks.app.GenerateAtlasSourceTask.java

private String compressBundleInfo(String bundleInfo) {
    ByteArrayOutputStream cc = new ByteArrayOutputStream();
    GZIPOutputStream gzip = null;
    try {/* w  ww . j a v  a 2s.com*/

        gzip = new GZIPOutputStream(cc);
        gzip.write(bundleInfo.getBytes("UTF-8"));
        gzip.flush();
        IOUtils.closeQuietly(gzip);
        byte[] result = cc.toByteArray();
        return org.apache.commons.codec.binary.Base64.encodeBase64String(result);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.sweble.wikitext.lazy.SerializationTest.java

private byte[] zip(byte[] serialized) throws IOException {
    ByteArrayOutputStream zipBaos = new ByteArrayOutputStream();

    GZIPOutputStream gzos = new GZIPOutputStream(zipBaos);
    gzos.write(serialized);
    gzos.close();// w  ww  .j  av  a  2s .c  o m

    return zipBaos.toByteArray();
}

From source file:com.netflix.astyanax.AbstractColumnListMutation.java

@Override
public ColumnListMutation<C> putCompressedColumn(C columnName, String value, Integer ttl) {
    Preconditions.checkNotNull(value, "Can't insert null value");

    if (value == null) {
        putEmptyColumn(columnName, ttl);
        return this;
    }//  ww w.  j  a v a  2  s . c o m

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip;
    try {
        gzip = new GZIPOutputStream(out);
        gzip.write(StringUtils.getBytesUtf8(value));
        gzip.close();
        return this.putColumn(columnName, ByteBuffer.wrap(out.toByteArray()), ttl);
    } catch (IOException e) {
        throw new RuntimeException("Error compressing column " + columnName, e);
    }
}