Example usage for java.util.zip GZIPOutputStream close

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

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Document

Writes remaining compressed data to the output stream and closes the underlying stream.

Usage

From source file:com.github.jasonruckman.gzip.AbstractBenchmark.java

protected byte[] doWriteJackson() {
    try {/*www  .  j  a v  a 2  s .  c  o  m*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gzos = new GZIPOutputStream(baos);
        mapper().writeValue(gzos, sampleData);
        gzos.close();
        return baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.mule.util.compression.GZipCompression.java

/**
 * Used for compressing a byte array into a new byte array using GZIP
 * /*from   w ww  . j  ava 2  s . com*/
 * @param bytes An array of bytes to compress
 * @return a compressed byte array
 * @throws java.io.IOException if it fails to write to a GZIPOutputStream
 * @see java.util.zip.GZIPOutputStream
 */
public byte[] compressByteArray(byte[] bytes) throws IOException {
    // TODO add strict behaviour as option
    if (bytes == null || isCompressed(bytes)) {
        // nothing to compress
        if (logger.isDebugEnabled()) {
            logger.debug("Data already compressed; doing nothing");
        }
        return bytes;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Compressing message of size: " + bytes.length);
    }

    ByteArrayOutputStream baos = null;
    GZIPOutputStream gzos = null;

    try {
        baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);
        gzos = new GZIPOutputStream(baos);

        gzos.write(bytes, 0, bytes.length);
        gzos.finish();
        gzos.close();

        byte[] compressedByteArray = baos.toByteArray();
        baos.close();

        if (logger.isDebugEnabled()) {
            logger.debug("Compressed message to size: " + compressedByteArray.length);
        }

        return compressedByteArray;
    } catch (IOException ioex) {
        throw ioex;
    } finally {
        IOUtils.closeQuietly(gzos);
        IOUtils.closeQuietly(baos);
    }
}

From source file:edu.duke.cabig.c3pr.utils.web.filter.GzipFilter.java

/**
 * Performs the filtering for a request.
 *///  w  w  w  .  ja v  a 2  s.c om
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws Exception {
    if (!isIncluded(request) && acceptsEncoding(request, "gzip")) {
        // Client accepts zipped content
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL() + ". Writing with gzip compression");
        }

        // Create a gzip stream
        final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
        final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

        // Handle the request
        final GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout);
        chain.doFilter(request, wrapper);
        wrapper.flush();

        gzout.close();

        //return on error or redirect code, because response is already committed
        int statusCode = wrapper.getStatus();
        if (statusCode != HttpServletResponse.SC_OK) {
            return;
        }

        //Saneness checks
        byte[] compressedBytes = compressed.toByteArray();
        boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request);
        boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus());
        if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
            compressedBytes = new byte[0];
        }

        try {
            // Write the zipped body
            ResponseUtil.addGzipHeader(response);
            response.setContentLength(compressedBytes.length);
        } catch (ResponseHeadersNotModifiableException e) {
            return;
        }

        response.getOutputStream().write(compressedBytes);
    } else {
        // Client does not accept zipped content - don't bother zipping
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL()
                    + ". Writing without gzip compression because the request does not accept gzip.");
        }
        chain.doFilter(request, response);
    }
}

From source file:parquet.hadoop.ParquetInputSplit.java

String compressString(String str) {
    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip;
    try {//from  w ww . j a v  a  2s.c  o 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:gov.nih.nci.cabig.caaers.web.filters.GzipFilter.java

/**
 * Performs the filtering for a request.
 *///w  w w  .  j  a v a 2s . c  o m
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws Exception {
    if (!isIncluded(request) && acceptsEncoding(request, "gzip")) {
        // Client accepts zipped content
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL() + ". Writing with gzip compression");
        }

        // Create a gzip stream
        final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
        final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

        // Handle the request
        final GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout);
        chain.doFilter(request, wrapper);
        wrapper.flush();

        gzout.close();

        //return on error or redirect code, because response is already committed
        int statusCode = wrapper.getStatus();
        if (statusCode != HttpServletResponse.SC_OK) {
            return;
        }

        //Saneness checks
        byte[] compressedBytes = compressed.toByteArray();
        boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request);
        boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus());
        if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
            compressedBytes = new byte[0];
        }

        try {
            // Write the zipped body
            ResponseUtil.addGzipHeader(response);
            // see http://httpd.apache.org/docs/2.0/mod/mod_deflate.html or 'High Performance Web Sites' by Steve Souders.
            response.addHeader(VARY, "Accept-Encoding");
            response.addHeader(VARY, "User-Agent");
            response.setContentLength(compressedBytes.length);
        } catch (ResponseHeadersNotModifiableException e) {
            return;
        }

        response.getOutputStream().write(compressedBytes);
    } else {
        // Client does not accept zipped content - don't bother zipping
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL()
                    + ". Writing without gzip compression because the request does not accept gzip.");
        }
        chain.doFilter(request, response);
    }
}

From source file:org.exist.replication.shared.MessageHelper.java

/**
 *  Serialize document to byte array as gzipped document.
 * /*from  ww  w  .  j  a v  a  2  s  .c o  m*/
 * @param broker
 * @param document
 * @return
 * @throws IOException 
 */
public static byte[] gzipSerialize(DBBroker broker, DocumentImpl document) throws IOException {

    // This is the weak spot, the data is serialized into
    // a byte array. Better to have an overloap to a file,
    byte[] payload;

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(baos);

    if (document.getResourceType() == DocumentImpl.XML_FILE) {

        // Stream XML document
        Serializer serializer = broker.getSerializer();
        serializer.reset();
        try {
            serializer.setProperties(OUTPUT_PROPERTIES);

            Writer w = new OutputStreamWriter(gos, "UTF-8");
            serializer.serialize(document, w);
            w.flush();
            w.close();

            payload = baos.toByteArray();

        } catch (SAXException e) {
            payload = new byte[0];
            LOG.error(e);
            throw new IOException("Error while serializing XML document: " + e.getMessage(), e);

        } catch (Throwable e) {
            payload = new byte[0];
            System.gc(); // recover from out of memory exception
            LOG.error(e);
            throw new IOException("Error while serializing XML document: " + e.getMessage(), e);
        }

    } else {
        // Stream NON-XML document

        try {
            broker.readBinaryResource((BinaryDocument) document, gos);
            gos.flush();
            gos.close();

            payload = baos.toByteArray();

        } catch (IOException e) {
            payload = new byte[0];
            LOG.error(e);
            throw new IOException("Error while serializing binary document: " + e.getMessage(), e);

        } catch (Throwable e) {
            payload = new byte[0];
            System.gc(); // recover from out of memory exception
            LOG.error(e);
            throw new IOException("Error while serializing binary document: " + e.getMessage(), e);
        }
    }

    return payload;

}

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

public SerializableNode(Node n) throws IOException {
    super(n);//from   w w w .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.panet.imeta.www.GetJobStatusServlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (!request.getContextPath().equals(CONTEXT_PATH))
        return;/*from  w w w. j ava  2  s .  co  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:com.google.ie.web.view.GsonView.java

@Override
protected void renderMergedOutputModel(Map<String, Object> model, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String jsonResult = getJsonString(filterModel(model));

    // Write the result to response
    response.setContentType(contentType);
    response.setStatus(statusCode);//from   w ww .  ja  v  a  2  s.co m
    response.setCharacterEncoding(characterEncoding);
    response.setHeader("Cache-Control", "no-cache");
    response.setHeader("Expires", "0");
    response.setHeader("Pragma", "No-cache");
    if (isGzipInRequest(request)) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream out = null;
        try {
            out = new GZIPOutputStream(response.getOutputStream());
            out.write(jsonResult.getBytes(characterEncoding));
        } finally {
            if (out != null) {
                out.finish();
                out.close();
            }
        }
    } else {
        response.getWriter().print(jsonResult);
    }

}

From source file:net.sf.ehcache.constructs.web.filter.GzipFilter.java

/**
 * Performs the filtering for a request.
 *///from  w w w. j  a v  a2 s.  c  om
protected void doFilter(final HttpServletRequest request, final HttpServletResponse response,
        final FilterChain chain) throws Exception {
    if (!isIncluded(request) && acceptsEncoding(request, "gzip")) {
        // Client accepts zipped content
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL() + ". Writing with gzip compression");
        }

        // Create a gzip stream
        final ByteArrayOutputStream compressed = new ByteArrayOutputStream();
        final GZIPOutputStream gzout = new GZIPOutputStream(compressed);

        // Handle the request
        final GenericResponseWrapper wrapper = new GenericResponseWrapper(response, gzout);
        chain.doFilter(request, wrapper);
        wrapper.flush();

        gzout.close();

        //return on error or redirect code, because response is already committed
        int statusCode = wrapper.getStatus();
        if (statusCode != HttpServletResponse.SC_OK) {
            return;
        }

        //Saneness checks
        byte[] compressedBytes = compressed.toByteArray();
        boolean shouldGzippedBodyBeZero = ResponseUtil.shouldGzippedBodyBeZero(compressedBytes, request);
        boolean shouldBodyBeZero = ResponseUtil.shouldBodyBeZero(request, wrapper.getStatus());
        if (shouldGzippedBodyBeZero || shouldBodyBeZero) {
            compressedBytes = new byte[0];
        }

        // Write the zipped body
        ResponseUtil.addGzipHeader(response);
        response.setContentLength(compressedBytes.length);

        response.getOutputStream().write(compressedBytes);
    } else {
        // Client does not accept zipped content - don't bother zipping
        if (LOG.isDebugEnabled()) {
            LOG.debug(request.getRequestURL()
                    + ". Writing without gzip compression because the request does not accept gzip.");
        }
        chain.doFilter(request, response);
    }
}