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:au.org.ala.layers.web.ObjectsService.java

/**
 * This method returns all objects associated with a field
 *
 * @param id/*w ww .ja v  a 2  s .  co m*/
 * @return
 */
@RequestMapping(value = "/objects/csv/{id}", method = RequestMethod.GET)
public void fieldObjectAsCSV(@PathVariable("id") String id, HttpServletResponse resp) throws IOException {
    try {
        resp.setContentType("text/csv");
        resp.setHeader("Content-Disposition", "attachment; filename=\"objects-" + id + ".csv.gz\"");
        GZIPOutputStream gzipped = new GZIPOutputStream(resp.getOutputStream());
        objectDao.writeObjectsToCSV(gzipped, id);
        gzipped.flush();
        gzipped.close();
    } catch (Exception e) {
        logger.error(e.getMessage(), e);
        resp.sendError(500, "Problem performing download");
    }
}

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 2s.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:io.restassured.internal.http.GZIPDecompressingEntityTest.java

private byte[] gzipCompress(String string) throws IOException {
    byte[] bytes = string.getBytes("UTF-8");
    ByteArrayOutputStream bos = new ByteArrayOutputStream(bytes.length);
    GZIPOutputStream gzip = new GZIPOutputStream(bos);
    gzip.write(bytes);//from  ww  w  .  j  ava 2  s .  com
    gzip.close();
    byte[] compressed = bos.toByteArray();
    bos.close();
    return compressed;
}

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

/**
 * Performs the filtering for a request.
 *//*w w  w  .  j av a  2  s . 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];
        }

        // 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);
    }
}

From source file:edu.cmu.cs.lti.ark.util.SerializedObjects.java

public static OutputStream getOutputStream(String outFile) throws IOException {
    if (outFile.endsWith(".gz")) {
        return new GZIPOutputStream(new FileOutputStream(outFile));
    } else {/*from w w  w  .j a v a  2s  . c o m*/
        return new FileOutputStream(outFile);
    }
}

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

/**
 * Performs the filtering for a request.
 *///from   w  w w.  j a  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:com.salsaberries.narchiver.Writer.java

/**
 *
 * @param files//from   w w  w .j  a v  a2 s.  co m
 * @param output
 * @throws IOException
 */
public static void compressFiles(Collection<File> files, File output) throws IOException {
    // Wrap the output file stream in streams that will tar and gzip everything
    try (FileOutputStream fos = new FileOutputStream(output);
            // Wrap the output file stream in streams that will tar and gzip everything
            TarArchiveOutputStream taos = new TarArchiveOutputStream(
                    new GZIPOutputStream(new BufferedOutputStream(fos)))) {

        // Enable support for long file names
        taos.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);

        // Put all the files in a compressed output file
        for (File f : files) {
            addFilesToCompression(taos, f, ".");
        }
    }
}

From source file:io.druid.segment.loading.LocalDataSegmentPullerTest.java

@Test
public void simpleGZTest() throws IOException, SegmentLoadingException {
    File zipFile = File.createTempFile("gztest", ".gz");
    File unZipFile = new File(tmpDir, Files.getNameWithoutExtension(zipFile.getAbsolutePath()));
    unZipFile.delete();//from   w  w w  . j  ava  2 s. c om
    zipFile.delete();
    try (OutputStream fOutStream = new FileOutputStream(zipFile)) {
        try (OutputStream outputStream = new GZIPOutputStream(fOutStream)) {
            outputStream.write(new byte[0]);
            outputStream.flush();
        }
    }

    Assert.assertTrue(zipFile.exists());
    Assert.assertFalse(unZipFile.exists());
    puller.getSegmentFiles(zipFile, tmpDir);
    Assert.assertTrue(unZipFile.exists());
}

From source file:com.github.trask.comet.loadtest.aws.ChefBootstrap.java

private static void prepareCookbook(String cookbooksDir, List<String> cookbooks, String destFilename)
        throws IOException, FileNotFoundException {

    TarArchiveOutputStream cookbooksTarOut = new TarArchiveOutputStream(
            new GZIPOutputStream(new FileOutputStream(destFilename)));
    for (String cookbook : cookbooks) {
        File cookbookDir = new File(cookbooksDir, cookbook);
        if (!cookbookDir.exists()) {
            throw new IllegalStateException("missing cookbook " + cookbookDir);
        }/*from   w w w.  j a v a2 s  .c  o  m*/
        addToTarWithBase(cookbookDir, cookbooksTarOut, "cookbooks/");
    }
    cookbooksTarOut.close();
}

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

@Override
public void save(final StoreableEntity entity) {
    FileOutputStream fos = null;//from www  .  j a va2  s  . c o 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);
    }
}