Example usage for java.util.zip GZIPOutputStream GZIPOutputStream

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

Introduction

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

Prototype

public GZIPOutputStream(OutputStream out) throws IOException 

Source Link

Document

Creates a new output stream with a default buffer size.

Usage

From source file:uk.ac.ebi.eva.test.utils.JobTestUtils.java

public static File makeGzipFile(String content) throws IOException {
    File tempFile = createTempFile();
    try (FileOutputStream output = new FileOutputStream(tempFile)) {
        try (Writer writer = new OutputStreamWriter(new GZIPOutputStream(output), "UTF-8")) {
            writer.write(content);//from w w  w.j  av a  2s .  c  o  m
        }
    }
    return tempFile;
}

From source file:gov.nih.nci.cabig.caaers.web.filters.GzipFilter.java

/**
 * Performs the filtering for a request.
 *//*from   w  w w .jav  a2s  . 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:eu.delving.sip.files.FileImporter.java

@Override
public void run() {
    int fileBlocks = (int) (inputFile.length() / BLOCK_SIZE);
    progressListener.prepareFor(fileBlocks);
    try {/*  w w  w.j  a  v a  2  s. c o  m*/
        OutputStream outputStream = new GZIPOutputStream(new FileOutputStream(dataSet.importedOutput()));
        InputStream inputStream = new FileInputStream(inputFile);
        inputStream = countingInputStream = new CountingInputStream(inputStream);
        try {
            String name = inputFile.getName();
            if (name.endsWith(".csv")) {
                consumeCSVFile(inputStream, outputStream);
            } else if (name.endsWith(".xml.zip")) {
                consumeXMLZipFile(inputStream, outputStream);
            } else if (name.endsWith(".xml") || name.endsWith(".xml.gz")) {
                if (name.endsWith(".xml.gz"))
                    inputStream = new GZIPInputStream(inputStream);
                consumeXMLFile(inputStream, outputStream);
            } else {
                throw new IllegalArgumentException("Unrecognized file extension: " + name);
            }
        } finally {
            IOUtils.closeQuietly(outputStream);
            IOUtils.closeQuietly(inputStream);
        }
        delete(statsFile(dataSet.importedOutput().getParentFile(), false, null));
        if (finished != null)
            finished.run();
    } catch (CancelException e) {
        delete(dataSet.importedOutput());
        progressListener.getFeedback().alert("Cancelled", e);
    } catch (IOException e) {
        delete(dataSet.importedOutput());
        progressListener.getFeedback().alert("Unable to import: " + e.getMessage(), e);
    }
}

From source file:com.generalbioinformatics.rdf.AbstractTripleStore.java

public RecordStream sparqlSelect(String query) throws StreamException {
    try {/*from w ww .j a  v  a 2 s. c om*/
        RecordStream rs;

        long start = System.currentTimeMillis();

        if (cacheDir == null) {
            rs = _sparqlSelectDirect(query);
            long delta = System.currentTimeMillis() - start;
            fireQueryPerformed(query, delta);
        } else {
            if (!cacheDir.exists()) {
                if (!cacheDir.mkdirs())
                    throw new IOException("Could not create cache directory");
            }

            int hashCode = query.hashCode() + 3 * this.hashCode();
            String hashCodeString = String.format("%08x", hashCode);
            File cacheSubdir = new File(cacheDir, hashCodeString.substring(0, 2));
            File out = new File(cacheSubdir, hashCodeString + ".txt.gz");

            if (out.exists()) {
                // merely "touch" the file, so we know the cached file was used recently.
                org.apache.commons.io.FileUtils.touch(out);
            } else {
                // make subdir if it doesn't exist.
                if (!cacheSubdir.exists()) {
                    if (!cacheSubdir.mkdir())
                        throw new IOException("Couldn't create directory " + cacheSubdir);
                }

                File tmp = File.createTempFile(hashCodeString + "-", ".tmp", cacheSubdir);
                try {
                    OutputStream os = new FileOutputStream(tmp);
                    GZIPOutputStream gos = new GZIPOutputStream(os);
                    RecordStream rsx = _sparqlSelectDirect(query);
                    long delta = System.currentTimeMillis() - start;
                    Utils.queryResultsToFile(this, delta, rsx, query, gos);
                    gos.finish();
                    os.close();
                    fireQueryPerformed(query, delta);
                } catch (RuntimeException e) {
                    tmp.delete();
                    throw (e);
                } catch (StreamException e) {
                    tmp.delete();
                    throw (e);
                }
                tmp.renameTo(out);
            }

            InputStream is = HFileUtils.openZipStream(out);
            rs = TsvRecordStream.open(is).filterComments().get();
        }

        return rs;
    } catch (IOException ex) {
        throw new StreamException(ex);
    }
}

From source file:com.handpay.ibenefit.framework.util.WebUtils.java

public static OutputStream buildGzipOutputStream(HttpServletResponse response) throws IOException {
    response.setHeader("Content-Encoding", "gzip");
    response.setHeader("Vary", "Accept-Encoding");
    return new GZIPOutputStream(response.getOutputStream());
}

From source file:ca.uhn.fhir.rest.server.servlet.ServletRestfulResponse.java

@Override
public Writer getResponseWriter(int theStatusCode, String theStatusMessage, String theContentType,
        String theCharset, boolean theRespondGzip) throws UnsupportedEncodingException, IOException {
    addHeaders();/* ww  w. j  ava 2s. co  m*/
    HttpServletResponse theHttpResponse = getRequestDetails().getServletResponse();
    theHttpResponse.setCharacterEncoding(theCharset);
    theHttpResponse.setStatus(theStatusCode);
    theHttpResponse.setContentType(theContentType);
    if (theRespondGzip) {
        theHttpResponse.addHeader(Constants.HEADER_CONTENT_ENCODING, Constants.ENCODING_GZIP);
        return new OutputStreamWriter(new GZIPOutputStream(theHttpResponse.getOutputStream()),
                Constants.CHARSET_NAME_UTF8);
    } else {
        return theHttpResponse.getWriter();
    }
}

From source file:GZIPFilter.java

public GZIPResponseStream(HttpServletResponse response) throws IOException {
    super();/*from   ww  w.ja v  a  2  s  .co m*/
    closed = false;
    this.response = response;
    this.output = response.getOutputStream();
    baos = new ByteArrayOutputStream();
    gzipstream = new GZIPOutputStream(baos);
}

From source file:ja.lingo.engine.Exporter.java

public void toFile(String fileName, IArticleList articleList, IMonitor monitor) throws IOException {
    File listTempFile = EngineFiles.createTempFile("html_export_list.html");

    TarOutputStream tos = null;/*w w w  . ja v  a2  s .com*/
    try {
        tos = new TarOutputStream(
                new GZIPOutputStream(new BufferedOutputStream(new FileOutputStream(fileName))));

        DecimalFormat format = createFormat(articleList.size() - 1);

        OutputStream listOs = null;
        try {
            listOs = new BufferedOutputStream(new FileOutputStream(listTempFile));

            writeArticles(articleList, tos, listOs, format, monitor);
        } finally {
            if (listOs != null) {
                try {
                    listOs.close();
                } catch (IOException e) {
                    LOG.error("Exception caught when tried to close list HTML FileOutputStream", e);
                }
            }
        }

        putListFile(listTempFile, tos);

        putIndexFile(articleList, tos);

        putCssFile(tos);

        tos.finish();

        monitor.finish();

    } finally {
        if (tos != null) {
            try {
                tos.close();
            } catch (IOException e) {
                LOG.error("Exception caught when tried to close TarOutputStream", e);
            }
        }

        listTempFile.delete();
    }
}

From source file:com.google.api.server.spi.IoUtilTest.java

private static byte[] compress(byte[] bytes) {
    try {/*  w  w  w  . j  a  v  a 2  s .  com*/
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(baos);
        gos.write(bytes, 0, bytes.length);
        gos.close();
        return baos.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.thoughtworks.studios.shine.cruise.stage.details.StageStorage.java

public void save(Graph graph) {
    StageIdentifier identifier = extractStageIdentifier(graph);

    if (isStageStored(identifier)) {
        return;/*  w  w  w. j  a v a 2  s .  co m*/
    }

    synchronized (stageKey(identifier)) {
        if (isStageStored(identifier)) {
            return;
        }

        File file = new File(tmpStagePath(identifier));

        file.getParentFile().mkdirs();
        try {
            OutputStream os = new BufferedOutputStream(new GZIPOutputStream(new FileOutputStream(file)));
            graph.persistToTurtle(os);
            os.flush();
            os.close();
            file.renameTo(new File(stagePath(identifier)));
        } catch (IOException e) {
            throw new ShineRuntimeException(e);
        } finally {
            file.delete();
        }
    }
}