Example usage for java.util.zip GZIPOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing compressed data to the output stream without closing the underlying stream.

Usage

From source file:org.n52.ses.common.environment.SESMiniServlet.java

private void printResponse(HttpServletRequest request, HttpServletResponse response, String string)
        throws IOException {
    int contentLength = string.getBytes("UTF-8").length;

    if (firstResponsePrint.getAndSet(false)) {
        ConfigurationRegistry conf = ConfigurationRegistry.getInstance();
        if (conf == null) {
            firstResponsePrint.getAndSet(true);
        } else {//  ww  w . j  av a  2 s  .co m
            minimumContentLengthForGzip = Integer
                    .parseInt(conf.getPropertyForKey(ConfigurationRegistry.MINIMUM_GZIP_SIZE));
        }
    }

    // compressed response
    if (contentLength > minimumContentLengthForGzip && clientSupportsGzip(request)) {
        response.addHeader("Content-Encoding", "gzip");
        GZIPOutputStream gzip = new GZIPOutputStream(response.getOutputStream(), contentLength);
        String type = response.getContentType();
        if (!type.contains("charset")) {
            response.setContentType(type + "; charset=utf-8");
        }
        gzip.write(string.getBytes(Charset.forName("UTF-8")));
        gzip.flush();
        gzip.finish();
    }
    // uncompressed response
    else {
        response.setContentLength(contentLength);
        response.setCharacterEncoding("UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write(string);
        writer.flush();
    }

}

From source file:org.mule.util.Base64.java

/**
 * Encodes a byte array into Base64 notation.
 * <p>//from  www.ja v a2s .  c  om
 * Valid options:
 * 
 * <pre>
 *              GZIP: gzip-compresses object before encoding it.
 *              DONT_BREAK_LINES: don't break lines at 76 characters
 *                &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
 * </pre>
 * 
 * <p>
 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
 * <p>
 * Example:
 * <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
 * 
 * @param source The data to convert
 * @param off Offset in array where conversion should begin
 * @param len Length of data to convert
 * @param options Specified options
 * @see Base64#GZIP
 * @see Base64#DONT_BREAK_LINES
 * @since 2.0
 */
public static String encodeBytes(byte[] source, int off, int len, int options) throws IOException {
    // Isolate options
    int dontBreakLines = (options & DONT_BREAK_LINES);
    int gzip = (options & GZIP);

    // Compress?
    if (gzip == GZIP) {
        ByteArrayOutputStream baos = null;
        GZIPOutputStream gzos = null;
        Base64.OutputStream b64os = null;

        try {
            // GZip -> Base64 -> ByteArray
            baos = new ByteArrayOutputStream(4096);
            b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);
            gzos = new GZIPOutputStream(b64os);

            gzos.write(source, off, len);
            gzos.finish();
            gzos.close();
        } // end try
        catch (IOException e) {
            throw e;
        } // end catch
        finally {
            IOUtils.closeQuietly(gzos);
            IOUtils.closeQuietly(b64os);
            IOUtils.closeQuietly(baos);
        } // end finally

        // Return value according to relevant encoding.
        try {
            return new String(baos.toByteArray(), PREFERRED_ENCODING);
        } // end try
        catch (UnsupportedEncodingException uue) {
            return new String(baos.toByteArray());
        } // end catch
    } // end if: compress

    // Else, don't compress. Better not to use streams at all then.
    else {
        // Convert option to boolean in way that code likes it.
        boolean breakLines = dontBreakLines == 0;

        int len43 = len * 4 / 3;
        byte[] outBuff = new byte[(len43) // Main 4:3
                + ((len % 3) > 0 ? 4 : 0) // Account for
                                          // padding
                + (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New
                                                                 // lines

        int d = 0;
        int e = 0;
        int len2 = len - 2;
        int lineLength = 0;
        for (; d < len2; d += 3, e += 4) {
            encode3to4(source, d + off, 3, outBuff, e);

            lineLength += 4;
            if (breakLines && lineLength == MAX_LINE_LENGTH) {
                outBuff[e + 4] = NEW_LINE;
                e++;
                lineLength = 0;
            } // end if: end of line
        } // en dfor: each piece of array

        if (d < len) {
            encode3to4(source, d + off, len - d, outBuff, e);
            e += 4;
        } // end if: some padding needed

        // Return value according to relevant encoding.
        try {
            return new String(outBuff, 0, e, PREFERRED_ENCODING);
        } // end try
        catch (UnsupportedEncodingException uue) {
            return new String(outBuff, 0, e);
        } // end catch

    } // end else: don't compress

}

From source file:com.ning.metrics.collector.processing.db.DatabaseCounterStorage.java

/**
 * serialize the given rolled-up counter data's distribution to a byte
 * array for storage in a blob/*from w  w w.ja v a2  s  .  c o  m*/
 * @param counter
 * @return
 * @throws java.io.IOException technically, but unlikely because all ops are
 *          in memory
 */
public static byte[] serializeDistribution(RolledUpCounterData counter) throws IOException {

    ByteArrayOutputStream result = new ByteArrayOutputStream();
    GZIPOutputStream zipStream = new GZIPOutputStream(result);
    PrintStream printer = new PrintStream(zipStream, true, "UTF-8");

    int index = 0;

    // iterate through all the entries in the distribution and generate a
    // serialization of the form:
    //
    // uniqueId1|count1\n
    // uniqueId2|count2\n
    // ...
    //
    // and then gzip the result into a byte array
    for (Map.Entry<String, Integer> entry : counter.getDistribution().entrySet()) {
        String id = entry.getKey();
        int value = entry.getValue() == null ? 0 : entry.getValue();

        // Don't write unique ids that have a zero count
        if (value == 0) {
            continue;
        }

        if (index++ > 0) {
            printer.println();
        }

        printer.print(id);
        printer.print('|');
        printer.print(Integer.toString(value));
    }

    zipStream.finish();
    printer.close();

    return result.toByteArray();
}

From source file:com.kolich.havalo.io.stores.MetaObjectStore.java

@Override
public void save(final StoreableEntity entity) {
    FileOutputStream fos = null;/*from   w  ww.  j a v  a  2 s  .  co m*/
    GZIPOutputStream gos = null;
    Writer writer = null;
    try {
        fos = new FileOutputStream(getCanonicalFile(entity));
        gos = new GZIPOutputStream(fos) {
            // Ugly anonymous constructor hack to set the compression
            // level on the underlying Deflater to "max compression".
            {
                def.setLevel(BEST_COMPRESSION);
            }
        };
        writer = new OutputStreamWriter(gos, UTF_8);
        // Call the entity to write itself to the output stream.
        entity.toWriter(writer);
        writer.flush(); // Muy importante
        gos.finish(); // Muy importante mucho!
    } catch (Exception e) {
        throw new ObjectFlushException("Failed to save entity: " + entity.getKey(), e);
    } finally {
        closeQuietly(writer);
        closeQuietly(gos);
        closeQuietly(fos);
    }
}

From source file:com.github.lindenb.jvarkit.tools.redon.CopyNumber01.java

@Override
public int doWork(String[] args) {
    String outfile = "output";
    File bedFile = null;/*from  ww  w .  j a  v  a  2 s  .  c  om*/
    File refFile = null;
    String chromNameFile = null;
    com.github.lindenb.jvarkit.util.cli.GetOpt opt = new com.github.lindenb.jvarkit.util.cli.GetOpt();
    int c;
    while ((c = opt.getopt(args, getGetOptDefault() + "R:w:b:N:o:")) != -1) {
        switch (c) {
        case 'w':
            this.windowSize = Integer.parseInt(opt.getOptArg());
            break;
        case 'b':
            bedFile = new File(opt.getOptArg());
            break;
        case 'R':
            refFile = new File(opt.getOptArg());
            break;
        case 'o':
            outfile = opt.getOptArg();
            break;
        case 'N': {
            chromNameFile = opt.getOptArg();
            break;
        }
        default: {
            switch (handleOtherOptions(c, opt, args)) {
            case EXIT_FAILURE:
                return -1;
            case EXIT_SUCCESS:
                return 0;
            default:
                break;
            }
        }
        }
    }

    if (refFile == null) {
        error("Undefined REF file");
        return -1;
    }

    if (outfile == null) {
        error("Undefined output file.");
        return -1;
    }

    SamReader samReader = null;

    try {
        File bamFile = null;
        if (opt.getOptInd() + 1 == args.length) {
            bamFile = new File(args[opt.getOptInd()]);
        } else {
            error("Illegal Number of arguments.");
            return -1;
        }

        final SamReaderFactory srf = SamReaderFactory.makeDefault()
                .validationStringency(ValidationStringency.LENIENT);

        info("get Dict for " + bamFile);
        samReader = srf.open(bamFile);
        this.samDictionary = samReader.getFileHeader().getSequenceDictionary();
        for (SAMReadGroupRecord rg : samReader.getFileHeader().getReadGroups()) {
            String s = rg.getSample();
            if (s == null || s.trim().isEmpty())
                continue;
            this.sampleName = s;
            break;
        }

        /* loading REF Reference */
        info("Loading " + refFile);
        this.indexedFastaSequenceFile = new IndexedFastaSequenceFile(refFile);
        SAMSequenceDictionary dict = this.indexedFastaSequenceFile.getSequenceDictionary();
        if (dict == null) {
            error("Cannot get sequence dictionary for " + refFile);
            return -1;
        }

        if (chromNameFile != null) {
            info("Reading " + chromNameFile);
            LineIterator r = IOUtils.openURIForLineIterator(chromNameFile);
            while (r.hasNext()) {
                String tokens[] = r.next().split("[\t]");
                if (tokens.length < 2)
                    continue;
                this.resolveChromName.put(tokens[0], tokens[1]);
                this.resolveChromName.put(tokens[1], tokens[0]);
            }
            CloserUtil.close(r);
        }
        if (bedFile != null) {
            prefillGCPercentWithCapture(bedFile);
        } else {
            prefillGCPercentWithoutCapture();
        }

        scanCoverage(samReader);
        samReader.close();

        /* save raw coverage */
        GZIPOutputStream zout = new GZIPOutputStream(new FileOutputStream(outfile + "_raw.tsv.gz"));
        saveCoverage(zout);
        zout.finish();
        zout.close();

        normalizeCoverage();

        /* save normalized coverage */
        zout = new GZIPOutputStream(new FileOutputStream(outfile + "_normalized.tsv.gz"));
        saveCoverage(zout);
        zout.finish();
        zout.close();

        return 0;
    } catch (Exception err) {
        error(err);
        return -1;
    } finally {
        CloserUtil.close(this.indexedFastaSequenceFile);
    }
}

From source file:org.intermine.api.lucene.KeywordSearch.java

private static void writeObjectToDB(ObjectStore os, String key, Object object)
        throws IOException, SQLException {
    LOG.debug("Saving stream to database...");
    Database db = ((ObjectStoreInterMineImpl) os).getDatabase();

    LargeObjectOutputStream streamOut = null;
    GZIPOutputStream gzipStream = null;
    ObjectOutputStream objectStream = null;

    try {/*from www  .  j  a  va  2  s .co  m*/
        streamOut = MetadataManager.storeLargeBinary(db, key);
        gzipStream = new GZIPOutputStream(new BufferedOutputStream(streamOut));
        objectStream = new ObjectOutputStream(gzipStream);

        LOG.debug("GZipping and serializing object...");
        objectStream.writeObject(object);
    } finally {
        if (objectStream != null) {
            objectStream.flush();
            objectStream.close();
        }
        if (gzipStream != null) {
            gzipStream.finish();
            gzipStream.flush();
            gzipStream.close();
        }
        if (streamOut != null) {
            streamOut.close();
        }
    }

}

From source file:org.xwiki.contrib.mailarchive.xwiki.internal.XWikiPersistence.java

private String treatHtml(final String htmlcontent, final HashMap<String, MailAttachment> attachmentsMap)
        throws IOException {
    String htmlcontentReplaced = "";
    if (!StringUtils.isBlank(htmlcontent)) {
        logger.debug("Original HTML length " + htmlcontent.length());

        // Replacement to avoid issue of "A circumflex" characters displayed (???)
        htmlcontentReplaced = htmlcontent.replaceAll("&Acirc;", " ");

        // Replace attachment URLs in HTML content for images to be shown
        for (Entry<String, MailAttachment> att : attachmentsMap.entrySet()) {
            // remove starting "<" and finishing ">"
            final String cid = att.getKey();
            // If there is no cid, it means this attachment is not INLINE, so there's nothing more to do
            if (!StringUtils.isEmpty(cid)) {
                String pattern = att.getKey().substring(1, att.getKey().length() - 2);
                pattern = "cid:" + pattern;

                logger.debug("Testing for CID pattern " + Util.encodeURI(pattern, context) + " " + pattern);
                String replacement = att.getValue().getUrl();
                logger.debug("To be replaced by " + replacement);
                htmlcontentReplaced = htmlcontentReplaced.replaceAll(pattern, replacement);
            } else {
                logger.warn("treatHtml: attachment is supposed not inline as cid is null or empty: "
                        + att.getValue().getFilename());
            }//w w w .  j  a  v a2 s . c  o  m
        }

        logger.debug("Zipping HTML part ...");
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        GZIPOutputStream zos = new GZIPOutputStream(bos);
        byte[] bytes = htmlcontentReplaced.getBytes("UTF8");
        zos.write(bytes, 0, bytes.length);
        zos.finish();
        zos.close();

        byte[] compbytes = bos.toByteArray();
        htmlcontentReplaced = Utils.byte2hex(compbytes);
        bos.close();

        if (htmlcontentReplaced.length() > ITextUtils.LONG_STRINGS_MAX_LENGTH) {
            logger.debug("Failed to have HTML fit in target field, truncating");
            htmlcontentReplaced = textUtils.truncateForLargeString(htmlcontentReplaced);
        }

    } else {
        logger.debug("No HTML to treat");
    }

    logger.debug("Html Zipped length : " + htmlcontentReplaced.length());
    return htmlcontentReplaced;
}

From source file:com.bt.download.android.gui.httpserver.BrowseHandler.java

@Override
public void handle(HttpExchange exchange) throws IOException {
    assertUPnPActive();/*  www. ja v a  2s.c o m*/

    GZIPOutputStream os = null;

    byte type = -1;

    try {

        List<NameValuePair> query = URLEncodedUtils.parse(exchange.getRequestURI(), "UTF-8");

        for (NameValuePair item : query) {
            if (item.getName().equals("type")) {
                type = Byte.parseByte(item.getValue());
            }
        }

        if (type == -1) {
            exchange.sendResponseHeaders(Code.HTTP_BAD_REQUEST, 0);
            return;
        }

        String response = getResponse(exchange, type);

        exchange.getResponseHeaders().set("Content-Encoding", "gzip");
        exchange.getResponseHeaders().set("Content-Type", "text/json; charset=UTF-8");
        exchange.sendResponseHeaders(Code.HTTP_OK, 0);

        os = new GZIPOutputStream(exchange.getResponseBody());

        os.write(response.getBytes("UTF-8"));
        os.finish();

    } catch (IOException e) {
        LOG.warning("Error browsing files type=" + type);
        throw e;
    } finally {
        if (os != null) {
            os.close();
        }
        exchange.close();
    }
}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

private void writeResponse(HttpServletRequest request, HttpServletResponse response, String responsePayload)
        throws IOException {

    byte[] reply = responsePayload.getBytes(CHARSET_UTF8);
    String contentType = CONTENT_TYPE_TEXT_PLAIN_UTF8;

    if (acceptsGzipEncoding(request) && shouldCompressResponse(request, response, responsePayload)) {
        // Compress the reply and adjust headers.
        ///*from   w  w w. jav a2s  .  c om*/
        ByteArrayOutputStream output = null;
        GZIPOutputStream gzipOutputStream = null;
        Throwable caught = null;
        try {
            output = new ByteArrayOutputStream(reply.length);
            gzipOutputStream = new GZIPOutputStream(output);
            gzipOutputStream.write(reply);
            gzipOutputStream.finish();
            gzipOutputStream.flush();
            response.setHeader(CONTENT_ENCODING, CONTENT_ENCODING_GZIP);
            reply = output.toByteArray();
        } catch (UnsupportedEncodingException e) {
            caught = e;
        } catch (IOException e) {
            caught = e;
        } finally {
            if (null != gzipOutputStream) {
                gzipOutputStream.close();
            }
            if (null != output) {
                output.close();
            }
        }

        if (caught != null) {
            /**
             * Our logger will not be servlet context's log (we don't have
             * direct access to it at this point)
             * @author rlogman@gmail.com
             */
            logger.error("Unable to compress response", caught);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    // Send the reply.
    //
    response.setContentLength(reply.length);
    response.setContentType(contentType);
    response.setStatus(HttpServletResponse.SC_OK);
    response.getOutputStream().write(reply);
}

From source file:com.weibo.api.motan.protocol.rpc.CompressRpcCodec.java

public byte[] compress(byte[] org, boolean useGzip, int minGzSize) throws IOException {
    if (useGzip && org.length > minGzSize) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(outputStream);
        gos.write(org);//w w w.  j a v  a  2  s  .c om
        gos.finish();
        gos.flush();
        gos.close();
        byte[] ret = outputStream.toByteArray();
        return ret;
    } else {
        return org;
    }

}