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:de.wpsverlinden.dupfind.FileIndexer.java

public void saveIndex() {
    File outFile = new File(userDir + "/DupFind.index.gz");
    outputPrinter.print("Saving index ... ");
    try (XMLEncoder xenc = new XMLEncoder(new GZIPOutputStream(new FileOutputStream(outFile)))) {
        xenc.writeObject(fileIndex);/*w ww . jav a2 s.  c o  m*/
        xenc.flush();
        outputPrinter.println("done.  " + fileIndex.size() + " files in index.");
    } catch (IOException e) {
        System.err.println(e);
    }
}

From source file:net.alastairwyse.methodinvocationremoting.RemoteSenderCompressor.java

/**
 * Compresses a string./*from  ww w  .j  a  v  a2 s .  co m*/
 * @param inputString  The string to compress.
 * @return             The compressed string.
 * @throws Exception   If an error occurs whilst compressing the string.
 */
private String CompressString(String inputString) throws Exception {
    /* //[BEGIN_METRICS]
    metricLogger.Begin(new StringCompressTime());
    //[END_METRICS] */

    byte[] compressedByteArray;

    try (ByteArrayOutputStream compressedStringStream = new ByteArrayOutputStream();
            GZIPOutputStream compressor = new GZIPOutputStream(compressedStringStream)) {
        byte[] inputStringBytes = inputString.getBytes(stringEncodingCharset);
        compressor.write(inputStringBytes);
        // Although close() is called as part of this try-with-resources statement, the stream is not written correctly unless it is closed before reading 
        compressor.close();
        compressedByteArray = compressedStringStream.toByteArray();
    } catch (Exception e) {
        /* //[BEGIN_METRICS]
        metricLogger.CancelBegin(new StringCompressTime());
        //[END_METRICS] */
        throw new Exception("Error compressing message.", e);
    }

    String returnString = Base64.encodeBase64String(compressedByteArray);

    /* //[BEGIN_METRICS]
    metricLogger.End(new StringCompressTime());
    metricLogger.Increment(new StringCompressed());
    metricLogger.Add(new CompressedStringSize(returnString.length()));
    //[END_METRICS] */
    /* //[BEGIN_LOGGING]
    loggingUtilities.LogCompressedString(this, returnString);
    //[END_LOGGING] */

    return returnString;
}

From source file:de.tudarmstadt.ukp.dkpro.tc.core.util.TaskUtils.java

/**
 * Saves a serializable object of type <T> to disk. Output file may be uncompressed, gzipped or
 * bz2-compressed. Compressed files must have a .gz or .bz2 suffix.
 *
 * @param serializedFile/*from w ww . j ava  2s. c  o  m*/
 *            model output file
 * @param serializableObject
 *            the object to serialize
 * @throws IOException
 */
public static void serialize(File serializedFile, Object serializableObject) throws IOException {

    FileOutputStream fos = new FileOutputStream(serializedFile);
    BufferedOutputStream bufStr = new BufferedOutputStream(fos);

    OutputStream underlyingStream = null;
    if (serializedFile.getName().endsWith(".gz")) {
        underlyingStream = new GZIPOutputStream(bufStr);
    } else if (serializedFile.getName().endsWith(".bz2")) {
        underlyingStream = new CBZip2OutputStream(bufStr);
        // manually add bz2 prefix to make it compatible to normal bz2 tools
        // prefix has to be skipped when reading the stream with CBZip2
        fos.write("BZ".getBytes("UTF-8"));
    } else {
        underlyingStream = bufStr;
    }
    ObjectOutputStream serializer = new ObjectOutputStream(underlyingStream);
    try {
        serializer.writeObject(serializableObject);

    } finally {
        serializer.flush();
        serializer.close();
    }
}

From source file:com.jaspersoft.jasperserver.core.util.StreamUtil.java

public static byte[] compress(String string) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    OutputStreamWriter osw = new OutputStreamWriter(gzos);
    osw.write(string);//from  w ww. ja va  2  s.  c  o  m
    osw.flush();
    osw.close();
    return baos.toByteArray();
}

From source file:edu.ku.brc.specify.web.HttpLargeFileTransfer.java

/**
 * @param infileName/* w w  w . j a va 2s.  c  o  m*/
 * @param outFileName
 * @param changeListener
 * @return
 */
public boolean compressFile(final String infileName, final String outFileName,
        final PropertyChangeListener propChgListener) {
    final File file = new File(infileName);
    if (file.exists()) {
        long fileSize = file.length();
        if (fileSize > 0) {
            SwingWorker<Integer, Integer> backupWorker = new SwingWorker<Integer, Integer>() {
                protected String errorMsg = null;
                protected FileInputStream fis = null;
                protected GZIPOutputStream fos = null;

                /* (non-Javadoc)
                 * @see javax.swing.SwingWorker#doInBackground()
                 */
                @Override
                protected Integer doInBackground() throws Exception {
                    try {
                        Thread.sleep(100);

                        long totalSize = file.length();
                        long bytesCnt = 0;

                        FileInputStream fis = new FileInputStream(infileName);
                        GZIPOutputStream fos = new GZIPOutputStream(new FileOutputStream(outFileName));

                        byte[] bytes = new byte[BUFFER_SIZE * 10];

                        while (true) {
                            int len = fis.read(bytes);
                            if (len > 0) {
                                fos.write(bytes, 0, len);
                                bytesCnt += len;
                                firePropertyChange("MEGS", 0,
                                        (int) (((double) bytesCnt / (double) totalSize) * 100.0));
                            } else {
                                break;
                            }
                        }

                        fis.close();
                        fos.close();

                    } catch (Exception ex) {
                        ex.printStackTrace();
                        errorMsg = ex.toString();

                    } finally {
                        try {
                            if (fis != null) {
                                fis.close();
                            }
                            if (fos != null) {
                                fos.close();
                            }
                        } catch (IOException ex) {
                            errorMsg = ex.toString();
                        }
                    }
                    firePropertyChange("MEGS", 0, 100);
                    return null;
                }

                @Override
                protected void done() {
                    super.done();

                    UIRegistry.getStatusBar().setProgressDone(HttpLargeFileTransfer.class.toString());

                    //UIRegistry.clearSimpleGlassPaneMsg();

                    if (StringUtils.isNotEmpty(errorMsg)) {
                        UIRegistry.showError(errorMsg);
                    }

                    if (propChgListener != null) {
                        propChgListener.propertyChange(
                                new PropertyChangeEvent(HttpLargeFileTransfer.this, "Done", 0, 1));
                    }
                }
            };

            final JStatusBar statusBar = UIRegistry.getStatusBar();
            statusBar.setIndeterminate(HttpLargeFileTransfer.class.toString(), true);

            UIRegistry.writeSimpleGlassPaneMsg(getLocalizedMessage("Compressing Backup..."), 24);

            backupWorker.addPropertyChangeListener(new PropertyChangeListener() {
                public void propertyChange(final PropertyChangeEvent evt) {
                    if ("MEGS".equals(evt.getPropertyName())) {
                        Integer value = (Integer) evt.getNewValue();
                        double val = value / 10.0;
                        statusBar
                                .setText(UIRegistry.getLocalizedMessage("MySQLBackupService.BACKUP_MEGS", val));
                    }
                }
            });
            backupWorker.execute();

        } else {
            // file doesn't exist
        }
    } else {
        // file doesn't exist
    }
    return false;
}

From source file:com.rest4j.impl.ApiResponseImpl.java

@Override
public void outputBody(HttpServletResponse response) throws IOException {
    if (statusMessage == null)
        response.setStatus(status);/*from  ww  w.  ja v  a  2  s  . com*/
    else
        response.setStatus(status, statusMessage);
    headers.outputHeaders(response);
    if (this.response == null)
        return;
    response.addHeader("Content-type", this.response.getContentType());
    if (addEtag) {
        String etag = this.response.getETag();
        if (etag != null)
            response.addHeader("ETag", etag);
    }

    OutputStream outputStream;
    byte[] resourceBytes = ((JSONResource) this.response).getJSONObject().toString().getBytes();
    int contentLength = resourceBytes.length;
    if (compress) {
        response.addHeader("Content-encoding", "gzip");
        ByteArrayOutputStream outputByteStream = new ByteArrayOutputStream();
        GZIPOutputStream gzipOutputStream = new GZIPOutputStream(outputByteStream);
        gzipOutputStream.write(resourceBytes);
        gzipOutputStream.finish(); //     ??!
        contentLength = outputByteStream.toByteArray().length;
        gzipOutputStream.close();
        outputByteStream.close();

        outputStream = new GZIPOutputStream(response.getOutputStream());
    } else {
        outputStream = response.getOutputStream();
    }
    response.addHeader("Content-Length", String.valueOf(contentLength));

    if (this.response instanceof JSONResource) {
        ((JSONResource) this.response).setPrettify(prettify);
    }
    if (callbackFunctionName == null) {
        this.response.write(outputStream);
    } else {
        this.response.writeJSONP(outputStream, callbackFunctionName);
    }
    outputStream.close();
}

From source file:net.sf.ehcache.constructs.web.PageInfo.java

/**
 * @param ungzipped the bytes to be gzipped
 * @return gzipped bytes/*from   www  .j  a va2 s. com*/
 */
private byte[] gzip(byte[] ungzipped) throws IOException, AlreadyGzippedException {
    if (isGzipped(ungzipped)) {
        throw new AlreadyGzippedException("The byte[] is already gzipped. It should not be gzipped again.");
    }
    final ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(bytes);
    gzipOutputStream.write(ungzipped);
    gzipOutputStream.close();
    return bytes.toByteArray();
}

From source file:org.hawkular.apm.tests.dist.AbstractITest.java

public byte[] gzipCompression(byte[] bytes) throws IOException {
    if (bytes == null) {
        return null;
    }/*  w w  w  .j  a  va 2 s .  com*/

    ByteArrayOutputStream obj = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(obj);

    gzip.write(bytes);
    gzip.close();
    return obj.toByteArray();
}

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();/*  w ww .  j  a v a 2 s. c o m*/
    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);
    return httpResponse;
}

From source file:truesculpt.ui.panels.WebFilePanel.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    getManagers().getUtilsManager().updateFullscreenWindowStatus(getWindow());

    setContentView(R.layout.webfile);//from   ww w. java 2s  .c  om

    getManagers().getUsageStatisticsManager().TrackEvent("OpenFromWeb", "", 1);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.setWebViewClient(new MyWebViewClient());
    WebSettings webSettings = mWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    mWebView.addJavascriptInterface(new JavaScriptInterface(this, getManagers()), "Android");

    int nVersionCode = getManagers().getUpdateManager().getCurrentVersionCode();
    mWebView.loadUrl(mStrBaseWebSite + "?version=" + nVersionCode);

    mPublishToWebBtn = (Button) findViewById(R.id.publish_to_web);
    mPublishToWebBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final String name = getManagers().getMeshManager().getName();
            final File imagefile = new File(getManagers().getFileManager().GetImageFileName());
            final File objectfile = new File(getManagers().getFileManager().GetObjectFileName());

            getManagers().getUsageStatisticsManager().TrackEvent("PublishToWeb", name, 1);

            if (imagefile.exists() && objectfile.exists()) {
                try {
                    final File zippedObject = File.createTempFile("object", "zip");
                    zippedObject.deleteOnExit();

                    BufferedReader in = new BufferedReader(new FileReader(objectfile));
                    BufferedOutputStream out = new BufferedOutputStream(
                            new GZIPOutputStream(new FileOutputStream(zippedObject)));
                    System.out.println("Compressing file");
                    int c;
                    while ((c = in.read()) != -1) {
                        out.write(c);
                    }
                    in.close();
                    out.close();

                    long size = 0;

                    size = new FileInputStream(imagefile).getChannel().size();
                    size += new FileInputStream(zippedObject).getChannel().size();
                    size /= 1000;

                    final SpannableString msg = new SpannableString(
                            "You will upload your latest saved version of this scupture representing " + size
                                    + " ko of data\n\n"
                                    + "When clicking the yes button you accept to publish your sculpture under the terms of the creative commons share alike, non commercial license\n"
                                    + "http://creativecommons.org/licenses/by-nc-sa/3.0"
                                    + "\n\nDo you want to proceed ?");
                    Linkify.addLinks(msg, Linkify.ALL);

                    AlertDialog.Builder builder = new AlertDialog.Builder(WebFilePanel.this);
                    builder.setMessage(msg).setCancelable(false)
                            .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int id) {
                                    PublishPicture(imagefile, zippedObject, name);
                                }
                            }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                    AlertDialog dlg = builder.create();
                    dlg.show();

                    // Make the textview clickable. Must be called after
                    // show()
                    ((TextView) dlg.findViewById(android.R.id.message))
                            .setMovementMethod(LinkMovementMethod.getInstance());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                AlertDialog.Builder builder = new AlertDialog.Builder(WebFilePanel.this);
                builder.setMessage(
                        "File has not been saved, you need to save it before publishing\nDo you want to proceed to save window ?")
                        .setCancelable(false)
                        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                                ((FileSelectorPanel) getParent()).getTabHost().setCurrentTab(2);
                            }
                        }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int id) {
                            }
                        });
                builder.show();
            }
        }
    });
}