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.lindenb.jvarkit.tools.redon.CopyNumber01.java

@Override
public int doWork(String[] args) {
    String outfile = "output";
    File bedFile = null;//ww  w . jav  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:de.derschimi.proxyservlet.TestServlet.java

/** Copy response body data (the entity) from the proxy to the servlet client. */
protected void copyResponseEntity(HttpResponse proxyResponse, HttpServletResponse servletResponse)
        throws IOException {
    HttpEntity entity = proxyResponse.getEntity();
    if (entity != null) {

        OutputStream servletOutputStream = servletResponse.getOutputStream();
        if (entity.getContentEncoding() != null) {
            servletResponse.setCharacterEncoding("UTF-8");

            String charset = entity.getContentType().getValue();

            String charst = charset.substring(charset.lastIndexOf("=") + 1);
            if (entity.getContentEncoding().getValue().equals("gzip")) {
                InputStream in = entity.getContent();

                InputStream zin = new GZIPInputStream(in);
                StringWriter writer = new StringWriter();

                IOUtils.copy(zin, writer, "UTF-8");
                String theString = writer.toString();

                // System.out.println(theString);
                theString = theString.replaceAll("href=\"/", "href=\"/" + path + "/");
                theString = theString.replaceAll("src=\"/", "src=\"/" + path + "/");

                // css
                String par = "(";
                String pattern = "url" + par + "\"/static/";
                // replace all uses regex
                while (theString.contains(pattern)) {
                    theString = theString.replace(pattern, "url" + par + "\"/" + path + "/static/");
                }//from   w  w w.  j a  v  a  2s  . c  om
                // css...
                String pattern2 = "url" + par + "/static/";
                while (theString.contains(pattern2)) {
                    theString = theString.replace(pattern2, "url" + par + "/" + path + "/static/");
                }
                //  window.location = '/artikel/a-774487.html';
                theString = replace(theString, "window.location = '/artikel/",
                        "windows.location = '/" + path + "/artikel/");
                //a.href = "/video/video
                theString = replace(theString, "a.href = \"/video/video",
                        "a.href = \"/" + path + "/video/video");
                // ("src", "/video/video
                theString = replace(theString, "(\"src\", \"/video/video",
                        "(\"src\", \"" + path + "/video/video");

                // flash :)
                String pattern3 = "data=\"/static/";
                while (theString.contains(pattern3)) {
                    theString = theString.replace(pattern3, "data=" + "/" + path + "/static/");
                }

                ByteArrayOutputStream out = new ByteArrayOutputStream();

                GZIPOutputStream gzip = new GZIPOutputStream(out);
                gzip.write(theString.getBytes());
                gzip.close();

                servletOutputStream.write(out.toByteArray());
            } else {
                System.err.println("not a gzip request:");
            }
        } else {
            entity.writeTo(servletOutputStream);
        }
    }
}

From source file:org.atomserver.core.filestore.FileBasedContentStorage.java

protected void writeStringToFile(String content, File file) throws IOException {
    if (file.getName().endsWith(GZIP_EXTENSION)) {
        GZIPOutputStream outputStream = new GZIPOutputStream(new FileOutputStream(file));
        IOUtils.write(content, outputStream, UTF_8);
        outputStream.close();
    } else {/*ww w .  j  ava 2  s .  c  o m*/
        FileUtils.writeStringToFile(file, content, UTF_8);
    }
}

From source file:at.ofai.gate.virtualcorpus.JDBCCorpus.java

protected InputStream getGZIPCompressedInputStream(String theString, String theEncoding) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(baos);
    gos.write(theString.getBytes(theEncoding));
    gos.close();
    ByteArrayInputStream inputStream = new ByteArrayInputStream(baos.toByteArray());
    return inputStream;
}

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

@Benchmark
public int jdkGzip2Compress() {
    ByteArrayInputStream bin = null;
    ByteArrayOutputStream bout = null;
    GZIPOutputStream gzout = null;
    try {/* w  w w .  j a  v  a 2 s  . c  o m*/
        bin = new ByteArrayInputStream(data);
        bout = new ByteArrayOutputStream(data.length);
        gzout = new GZIPOutputStream(bout) {
            {
                def.setLevel(level);
            }
        };
        int count;
        byte ret[] = new byte[1024];
        while ((count = bin.read(ret, 0, 1024)) != -1) {
            gzout.write(ret, 0, count);
        }
        gzout.finish();
        gzout.flush();
    } 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:org.ofbiz.webapp.event.RestEventHandler.java

private void createAndSendRESTResponse(Map<String, Object> serviceResults, String serviceName,
        HttpServletResponse response) throws EventHandlerException {
    try {//from w  ww  .java 2 s  .c o  m
        // setup the response
        Debug.logVerbose("[EventHandler] : Setting up response message", module);

        JsonConfig config = new JsonConfig();
        config.registerJsonValueProcessor(java.util.Date.class, new JsDateJsonValueProcessor());
        config.registerJsonValueProcessor(java.sql.Date.class, new JsDateJsonValueProcessor());
        config.registerJsonValueProcessor(java.sql.Timestamp.class, new JsDateJsonValueProcessor());
        config.registerJsonValueProcessor(java.sql.Time.class, new JsDateJsonValueProcessor());
        JSONObject restResults = JSONObject.fromObject(serviceResults, config);

        //               Debug.logInfo("restResults ==================" + restResults, module);

        // log the response message
        if (Debug.verboseOn()) {
            try {
                Debug.logInfo("Response Message:\n" + restResults + "\n", module);
            } catch (Throwable t) {
            }
        }

        //Writer out = response.getWriter();
        //out.write(restResults.toString());
        //restResult.write(out);
        //out.flush();
        ByteArrayOutputStream bout = new ByteArrayOutputStream();
        GZIPOutputStream gout = new GZIPOutputStream(bout); //buffer
        gout.write(restResults.toString().getBytes());
        gout.close();
        //??
        byte g[] = bout.toByteArray();
        response.setHeader("Content-Encoding", "gzip");
        response.setHeader("Content-Length", g.length + "");
        response.getOutputStream().write(g);
        //restResult.write(response.getOutputStream());
        //response.getOutputStream().flush();
    } catch (Exception e) {
        Debug.logError(e, module);
        throw new EventHandlerException(e.getMessage(), e);
    }
}

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 a  2s .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: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 w w w  .j av  a 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.esigate.http.HttpClientRequestExecutorTest.java

private HttpResponse createMockGzippedResponse(String content) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = content.getBytes();
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("text/html; charset=ISO-8859-1");
    httpEntity.setContentEncoding("gzip");
    StatusLine statusLine = new BasicStatusLine(new ProtocolVersion("p", 1, 2), HttpStatus.SC_OK, "OK");
    BasicHttpResponse httpResponse = new BasicHttpResponse(statusLine);
    httpResponse.addHeader("Content-type", "text/html; charset=ISO-8859-1");
    httpResponse.addHeader("Content-encoding", "gzip");
    httpResponse.setEntity(httpEntity);/*  w  ww . j a va 2s.co m*/
    return httpResponse;
}

From source file:edu.cornell.med.icb.goby.alignments.UpgradeTo1_9_6.java

private void writeIndex(String basename, LongArrayList indexOffsets, LongArrayList indexAbsolutePositions)
        throws IOException {
    GZIPOutputStream indexOutput = null;
    try {//w  ww.  java  2  s.c o  m
        FileUtils.moveFile(new File(basename + ".index"),
                new File(makeBackFilename(basename + ".index", ".bak")));
        indexOutput = new GZIPOutputStream(new FileOutputStream(basename + ".index"));
        final Alignments.AlignmentIndex.Builder indexBuilder = Alignments.AlignmentIndex.newBuilder();
        assert (indexOffsets.size() == indexAbsolutePositions.size()) : "index sizes must be consistent.";
        indexBuilder.addAllOffsets(indexOffsets);
        indexBuilder.addAllAbsolutePositions(indexAbsolutePositions);
        indexBuilder.build().writeTo(indexOutput);
    } finally {
        if (indexOutput != null)
            indexOutput.close();

    }
}