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:builder.smartfrog.SmartFrogAction.java

public void compressLog() {
    File logFile = getLogFile();//from   w  w  w .j ava  2s .  c o m
    File compressedLog = new File(logFile.getParentFile(), logFile.getName() + ".gz");
    GZIPOutputStream gzos = null;
    FileInputStream ist = null;
    try {
        gzos = new GZIPOutputStream(new FileOutputStream(compressedLog));
        ist = new FileInputStream(logFile);
        IOUtils.copy(ist, gzos);
        gzos.finish();
    } catch (IOException e) {
        Logger.getLogger(SmartFrogBuildListener.class.getName()).log(Level.WARNING,
                "was not able to compress log file " + logFile.getAbsolutePath(), e);
        if (ist != null)
            IOUtils.closeQuietly(ist);
        if (gzos != null)
            IOUtils.closeQuietly(gzos);
        return;
    }
    logFile.delete();
}

From source file:co.cask.cdap.internal.app.runtime.LocalizationUtilsTest.java

private File createGzFile(String gzFileName, File sourceFile) throws IOException {
    File target = TEMP_FOLDER.newFile(gzFileName + ".gz");
    try (GZIPOutputStream gzos = new GZIPOutputStream(new FileOutputStream(target))) {
        com.google.common.io.Files.copy(sourceFile, gzos);
    }/* www .  ja va  2 s . co m*/
    return target;
}

From source file:com.iontorrent.vaadin.utils.JFreeChartWrapper.java

@Override
public Resource getSource() {
    if (res == null) {
        res = new ApplicationResource() {

            private ByteArrayInputStream bytestream = null;

            ByteArrayInputStream getByteStream() {
                if (chart != null && bytestream == null) {
                    int widht = getGraphWidth();
                    int height = getGraphHeight();
                    info = new ChartRenderingInfo();

                    if (mode == RenderingMode.SVG) {

                        DocumentBuilderFactory docBuilderFactory = DocumentBuilderFactory.newInstance();
                        DocumentBuilder docBuilder = null;
                        try {
                            docBuilder = docBuilderFactory.newDocumentBuilder();
                        } catch (ParserConfigurationException e1) {
                            throw new RuntimeException(e1);
                        }/*from  w w  w . j  a va 2  s .  c o m*/
                        Document document = docBuilder.newDocument();
                        Element svgelem = document.createElement("svg");
                        document.appendChild(svgelem);

                        // Create an instance of the SVG Generator
                        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);

                        // draw the chart in the SVG generator

                        chart.draw(svgGenerator, new Rectangle(widht, height), info);
                        Element el = svgGenerator.getRoot();
                        el.setAttributeNS(null, "viewBox", "0 0 " + widht + " " + height + "");
                        el.setAttributeNS(null, "style", "width:100%;height:100%;");
                        el.setAttributeNS(null, "preserveAspectRatio", getSvgAspectRatio());

                        // Write svg to buffer
                        ByteArrayOutputStream baoutputStream = new ByteArrayOutputStream();
                        Writer out;
                        try {
                            OutputStream outputStream = gzipEnabled ? new GZIPOutputStream(baoutputStream)
                                    : baoutputStream;
                            out = new OutputStreamWriter(outputStream, "UTF-8");
                            /*
                             * don't use css, FF3 can'd deal with the result
                             * perfectly: wrong font sizes
                             */
                            boolean useCSS = false;
                            svgGenerator.stream(el, out, useCSS, false);
                            outputStream.flush();
                            outputStream.close();
                            bytestream = new ByteArrayInputStream(baoutputStream.toByteArray());
                        } catch (UnsupportedEncodingException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (SVGGraphics2DIOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    } else {
                        // Draw png to bytestream
                        try {

                            byte[] bytes = ChartUtilities.encodeAsPNG(chart.createBufferedImage(widht, height));
                            bytestream = new ByteArrayInputStream(bytes);
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }

                    }

                } else {
                    bytestream.reset();
                }
                return bytestream;
            }

            public Application getApplication() {
                return JFreeChartWrapper.this.getApplication();
            }

            public int getBufferSize() {
                if (getByteStream() != null) {
                    return getByteStream().available();
                } else {
                    return 0;
                }
            }

            public long getCacheTime() {
                return 0;
            }

            public String getFilename() {
                if (mode == RenderingMode.PNG) {
                    return "graph.png";
                } else {
                    return gzipEnabled ? "graph.svgz" : "graph.svg";
                }
            }

            public DownloadStream getStream() {
                DownloadStream downloadStream = new DownloadStream(getByteStream(), getMIMEType(),
                        getFilename());
                if (gzipEnabled && mode == RenderingMode.SVG) {
                    downloadStream.setParameter("Content-Encoding", "gzip");
                }
                return downloadStream;
            }

            public String getMIMEType() {
                if (mode == RenderingMode.PNG) {
                    return "image/png";
                } else {
                    return "image/svg+xml";
                }
            }
        };
    }
    return res;
}

From source file:com.splout.db.dnode.HttpFileExchanger.java

public void send(final String tablespace, final int partition, final long version, final File binaryFile,
        final String url, boolean blockUntilComplete) {
    Future<?> future = clientExecutors.submit(new Runnable() {
        @Override/*ww w . j  a  v  a2s  . c o  m*/
        public void run() {
            DataOutputStream writer = null;
            InputStream input = null;
            try {
                HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
                connection.setChunkedStreamingMode(config.getInt(FetcherProperties.DOWNLOAD_BUFFER));
                connection.setDoOutput(true);
                connection.setRequestProperty("filename", binaryFile.getName());
                connection.setRequestProperty("tablespace", tablespace);
                connection.setRequestProperty("partition", partition + "");
                connection.setRequestProperty("version", version + "");

                Checksum checkSum = new CRC32();

                writer = new DataOutputStream(new GZIPOutputStream(connection.getOutputStream()));
                // 1 - write file size
                writer.writeLong(binaryFile.length());
                writer.flush();
                // 2 - write file content
                input = new FileInputStream(binaryFile);
                byte[] buffer = new byte[config.getInt(FetcherProperties.DOWNLOAD_BUFFER)];
                long wrote = 0;
                for (int length = 0; (length = input.read(buffer)) > 0;) {
                    writer.write(buffer, 0, length);
                    checkSum.update(buffer, 0, length);
                    wrote += length;
                }
                // 3 - add the CRC so that we can verify the download
                writer.writeLong(checkSum.getValue());
                writer.flush();
                log.info("Sent file " + binaryFile + " to " + url + " with #bytes: " + wrote + " and checksum: "
                        + checkSum.getValue());
            } catch (IOException e) {
                log.error(e);
            } finally {
                try {
                    if (input != null) {
                        input.close();
                    }
                    if (writer != null) {
                        writer.close();
                    }
                } catch (IOException ignore) {
                }
            }
        }
    });
    try {
        if (blockUntilComplete) {
            while (future.isDone() || future.isCancelled()) {
                Thread.sleep(1000);
            }
        }
    } catch (InterruptedException e) {
        // interrupted!
    }
}

From source file:com.pai.app.web.core.framework.web.filter.CompressionResponseStream.java

public void writeToGZip(byte b[], int off, int len) throws IOException {

    //log.trace("writeToGZip, len = " + len);
    /* minhnn comment/* w  ww  . j  a  va 2 s.c o m*/
    if (debug > 2) {
    System.out.print("writeToGZip(");
    System.out.write(b, off, len);
    System.out.println(")");
    }*/
    if (gzipstream == null) {
        //log.trace("new GZIPOutputStream");
        response.addHeader("Content-Encoding", "gzip");
        gzipstream = new GZIPOutputStream(output);
    }
    gzipstream.write(b, off, len);

}

From source file:cn.salesuite.saf.download.AndroidHttpClient.java

/**
 * Compress data to send to server.//  w  w w  .  j a v  a2 s .  c o m
 * Creates a Http Entity holding the gzipped data.
 * The data will not be compressed if it is too short.
 * @param data The bytes to compress
 * @return Entity holding the data
 */
public static AbstractHttpEntity getCompressedEntity(byte data[], ContentResolver resolver) throws IOException {
    AbstractHttpEntity entity;
    if (data.length < getMinGzipSize(resolver)) {
        entity = new ByteArrayEntity(data);
    } else {
        ByteArrayOutputStream arr = new ByteArrayOutputStream();
        OutputStream zipper = new GZIPOutputStream(arr);
        zipper.write(data);
        zipper.close();
        entity = new ByteArrayEntity(arr.toByteArray());
        entity.setContentEncoding("gzip");
    }
    return entity;
}

From source file:gobblin.metastore.MysqlStateStore.java

@Override
public void putAll(String storeName, String tableName, Collection<T> states) throws IOException {
    try (Connection connection = dataSource.getConnection();
            PreparedStatement insertStatement = connection.prepareStatement(UPSERT_JOB_STATE_SQL);
            ByteArrayOutputStream byteArrayOs = new ByteArrayOutputStream();
            OutputStream os = compressedValues ? new GZIPOutputStream(byteArrayOs) : byteArrayOs;
            DataOutputStream dataOutput = new DataOutputStream(os)) {

        int index = 0;
        insertStatement.setString(++index, storeName);
        insertStatement.setString(++index, tableName);

        for (T state : states) {
            addStateToDataOutputStream(dataOutput, state);
        }/*w  w w . j ava2  s  .  c o  m*/

        dataOutput.close();
        insertStatement.setBlob(++index, new ByteArrayInputStream(byteArrayOs.toByteArray()));

        insertStatement.executeUpdate();
        connection.commit();
    } catch (SQLException e) {
        throw new IOException("Failure storing state to store " + storeName + " table " + tableName, e);
    }
}

From source file:org.kairosdb.datastore.remote.RemoteDatastore.java

/**
 Compresses the given file and removes the uncompressed file
 @param file//w w  w. j av a2 s  .c  om
 @return Size of the zip file
 */
private long zipFile(String file) throws IOException {
    String zipFile = file + ".gz";

    FileInputStream is = new FileInputStream(file);
    GZIPOutputStream gout = new GZIPOutputStream(new FileOutputStream(zipFile));

    byte[] buffer = new byte[1024];
    int readSize = 0;
    while ((readSize = is.read(buffer)) != -1)
        gout.write(buffer, 0, readSize);

    is.close();
    gout.flush();
    gout.close();

    //delete uncompressed file
    new File(file).delete();

    return (new File(zipFile).length());
}

From source file:fast.simple.download.http.DownloadHttpClient.java

private static ByteArrayOutputStream zip(byte data[]) {
    ByteArrayOutputStream arr = new ByteArrayOutputStream();
    OutputStream zipper = null;/*from w  w  w .j  a va2s  .c  om*/
    try {
        zipper = new GZIPOutputStream(arr);
        zipper.write(data);
    } catch (Exception e) {
    } finally {
        try {
            if (zipper != null) {
                zipper.close();
            }
        } catch (Exception e) {
        }
    }
    return arr;
}

From source file:csiro.pidsvc.servlet.controller.java

protected void returnAttachment(HttpServletResponse response, String filename, String outputFormat,
        String content) throws IOException {
    //      response.setContentType("application/xml"); response.getWriter().write(content); return;
    if (outputFormat.equalsIgnoreCase("xml")) {
        response.setContentType("application/xml");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        response.getOutputStream().write(content.getBytes());
    } else {/*w ww .java  2 s  .  c  om*/
        response.setContentType("application/zip");
        response.setHeader("Content-Disposition", "attachment; filename=" + filename);
        GZIPOutputStream gos = new GZIPOutputStream(response.getOutputStream());
        gos.write(content.getBytes());
        gos.close();
    }
}