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:Base64.java

/**
 * Serializes an object and returns the Base64-encoded
 * version of that serialized object. If the object
 * cannot be serialized or there is another error,
 * the method will return <tt>null</tt>.
 * <p>/* w ww .  j a va  2 s. c om*/
 * Valid options:<pre>
 *   GZIP: gzip-compresses object before encoding it.
 *   DONT_BREAK_LINES: don't break lines at 76 characters
 *     <i>Note: Technically, this makes your encoding non-compliant.</i>
 * </pre>
 * <p>
 * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
 * <p>
 * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
 *
 * @param serializableObject The object to encode
 * @param options Specified options
 * @return The Base64-encoded object
 * @see Base64#GZIP
 * @see Base64#DONT_BREAK_LINES
 * @since 2.0
 */
public static String encodeObject(java.io.Serializable serializableObject, int options) {
    // Streams
    java.io.ByteArrayOutputStream baos = null;
    java.io.OutputStream b64os = null;
    java.io.ObjectOutputStream oos = null;
    java.util.zip.GZIPOutputStream gzos = null;

    // Isolate options
    int gzip = (options & GZIP);
    int dontBreakLines = (options & DONT_BREAK_LINES);

    try {
        // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
        baos = new java.io.ByteArrayOutputStream();
        b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);

        // GZip?
        if (gzip == GZIP) {
            gzos = new java.util.zip.GZIPOutputStream(b64os);
            oos = new java.io.ObjectOutputStream(gzos);
        } // end if: gzip
        else
            oos = new java.io.ObjectOutputStream(b64os);

        oos.writeObject(serializableObject);
    } // end try
    catch (java.io.IOException e) {
        e.printStackTrace();
        return null;
    } // end catch
    finally {
        try {
            oos.close();
        } catch (Exception e) {
        }
        try {
            gzos.close();
        } catch (Exception e) {
        }
        try {
            b64os.close();
        } catch (Exception e) {
        }
        try {
            baos.close();
        } catch (Exception e) {
        }
    } // end finally

    // Return value according to relevant encoding.
    try {
        return new String(baos.toByteArray(), PREFERRED_ENCODING);
    } // end try
    catch (java.io.UnsupportedEncodingException uue) {
        return new String(baos.toByteArray());
    } // end catch

}

From source file:es.mityc.firmaJava.libreria.utilidades.Base64.java

/**
 * Encodes a byte array into Base64 notation.
 * <p>//from  w w  w. j av  a  2 s.  com
 * Valid options:<pre>
 *   GZIP: gzip-compresses object before encoding it.
 *   DONT_BREAK_LINES: don't break lines at 76 characters
 *     <i>Note: Technically, this makes your encoding non-compliant.</i>
 * </pre>
 * <p>
 * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
 * <p>
 * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
 *
 *
 * @param source The data to convert
 * @param off Offset in array where conversion should begin
 * @param len Length of data to convert
 * @param options Specified options
* @param options alphabet type is pulled from this (standard, url-safe, ordered)
 * @see Base64#GZIP
 * @see Base64#DONT_BREAK_LINES
 * @since 2.0
 */
public static String encodeBytes(byte[] source, int off, int len, int options) {
    // Isolate options
    int dontBreakLines = (options & ConstantesXADES.DONT_BREAK_LINES);
    int gzip = (options & ConstantesXADES.GZIP);

    // Compress?
    if (gzip == ConstantesXADES.GZIP) {
        ByteArrayOutputStream baos = null;
        GZIPOutputStream gzos = null;
        Base64.OutputStream b64os = null;

        try {
            // GZip -> Base64 -> ByteArray
            baos = new ByteArrayOutputStream();
            b64os = new Base64.OutputStream(baos, ConstantesXADES.ENCODE | options);
            gzos = new GZIPOutputStream(b64os);

            gzos.write(source, off, len);
            //gzos.close();
        } // end try
        catch (IOException e) {
            log.error(e);
            return null;
        } // end catch
        finally {
            try {
                gzos.close();
            } catch (Exception e) {
                log.error(e);
            }
            try {
                b64os.close();
            } catch (Exception e) {
                log.error(e);
            }
            try {
                baos.close();
            } catch (Exception e) {
                log.error(e);
            }
        } // end finally

        // Return value according to relevant encoding.
        try {
            return new String(baos.toByteArray(), PREFERRED_ENCODING);
        } // end try
        catch (UnsupportedEncodingException uue) {
            return new String(baos.toByteArray());
        } // end catch
    } // end if: compress

    // Else, don't compress. Better not to use streams at all then.
    else {
        // Convert option to boolean in way that code likes it.
        boolean breakLines = dontBreakLines == 0;

        int len43 = len * 4 / 3;
        byte[] outBuff = new byte[(len43) // Main 4:3
                + ((len % 3) > 0 ? 4 : 0) // Account for padding
                + (breakLines ? (len43 / MAX_LINE_LENGTH) : 0)]; // New lines      
        int d = 0;
        int e = 0;
        int len2 = len - 2;
        int lineLength = 0;
        int maxLineLength = MAX_LINE_LENGTH;
        byte newLine = NEW_LINE;
        //            for( ; d < len2; d+=3, e+=4 )
        //            {
        //                encode3to4( source, d+off, 3, outBuff, e, options );
        //
        //                lineLength += 4;
        //                if( breakLines && lineLength == MAX_LINE_LENGTH )
        //                {   
        //                    outBuff[e+4] = NEW_LINE;
        //                    e++;
        //                    lineLength = 0;
        //                }   // end if: end of line
        //            }   // en dfor: each piece of array
        while (d < len2) {
            encode3to4(source, d + off, 3, outBuff, e, options);

            lineLength += 4;
            if (breakLines && lineLength == maxLineLength) {
                outBuff[e + 4] = newLine;
                e++;
                lineLength = 0;
            } // end if: end of line
            d += 3;
            e += 4;
        }

        if (d < len) {
            encode3to4(source, d + off, len - d, outBuff, e, options);
            e += 4;
        } // end if: some padding needed

        // Return value according to relevant encoding.
        try {
            return new String(outBuff, 0, e, PREFERRED_ENCODING);
        } // end try
        catch (UnsupportedEncodingException uue) {
            return new String(outBuff, 0, e);
        } // end catch

    } // end else: don't compress

}

From source file:de.zib.scalaris.TransactionSingleOpTest.java

/**
 * Tests how long it takes to read a large string with different compression
 * schemes./*from  ww w .j  a  v a2 s .c  o m*/
 *
 * @param compressed
 *            how to compress
 * @param key
 *            the key to append to the {@link #testTime}
 *
 * @throws ConnectionException
 * @throws UnknownException
 * @throws AbortException
 * @throws NotFoundException
 * @throws IOException
 */
protected void testReadLargeString(final int compression, final String key)
        throws ConnectionException, UnknownException, AbortException, NotFoundException, IOException {
    final StringBuilder sb = new StringBuilder(testData.length * 8 * 100);
    for (int i = 0; i < 100; ++i) {
        for (final String data : testData) {
            sb.append(data);
        }
    }
    final String expected = sb.toString();

    final TransactionSingleOp conn = new TransactionSingleOp();
    conn.setCompressed(true);
    switch (compression) {
    case 1:
        conn.setCompressed(false);
    case 2:
        conn.write(testTime + key, expected);
        break;
    case 3:
        conn.setCompressed(false);
    case 4:
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        final GZIPOutputStream gos = new GZIPOutputStream(bos);
        gos.write(expected.getBytes("UTF-8"));
        gos.flush();
        gos.close();
        conn.write(testTime + key, new Base64(0).encodeToString(bos.toByteArray()));
        break;
    default:
        return;
    }

    try {
        for (int i = 0; i < 500; ++i) {
            String actual = conn.read(testTime + key).stringValue();
            if (compression >= 3) {
                final byte[] packed = new Base64(0).decode(actual);
                final ByteArrayOutputStream unpacked = new ByteArrayOutputStream();
                final ByteArrayInputStream bis = new ByteArrayInputStream(packed);
                final GZIPInputStream gis = new GZIPInputStream(bis);
                final byte[] bbuf = new byte[256];
                int read = 0;
                while ((read = gis.read(bbuf)) >= 0) {
                    unpacked.write(bbuf, 0, read);
                }
                gis.close();
                actual = new String(unpacked.toString("UTF-8"));
            }
            assertEquals(expected, actual);
        }
    } finally {
        conn.closeConnection();
    }
}

From source file:com.ichi2.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;/*from  w  ww.jav  a 2 s. c  o m*/
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    mPostVars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(AnkiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Consts.SYNC_BASE;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = syncURL() + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "AnkiDroid-" + VersionUtils.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

From source file:website.openeng.libanki.sync.HttpSyncer.java

public HttpResponse req(String method, InputStream fobj, int comp, JSONObject registerData,
        Connection.CancelCallback cancelCallback) throws UnknownHttpResponseException {
    File tmpFileBuffer = null;//w w  w. j av a  2s  .c  o m
    try {
        String bdry = "--" + BOUNDARY;
        StringWriter buf = new StringWriter();
        // post vars
        mPostVars.put("c", comp != 0 ? 1 : 0);
        for (String key : mPostVars.keySet()) {
            buf.write(bdry + "\r\n");
            buf.write(String.format(Locale.US, "Content-Disposition: form-data; name=\"%s\"\r\n\r\n%s\r\n", key,
                    mPostVars.get(key)));
        }
        tmpFileBuffer = File.createTempFile("syncer", ".tmp",
                new File(KanjiDroidApp.getCacheStorageDirectory()));
        FileOutputStream fos = new FileOutputStream(tmpFileBuffer);
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        GZIPOutputStream tgt;
        // payload as raw data or json
        if (fobj != null) {
            // header
            buf.write(bdry + "\r\n");
            buf.write(
                    "Content-Disposition: form-data; name=\"data\"; filename=\"data\"\r\nContent-Type: application/octet-stream\r\n\r\n");
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
            // write file into buffer, optionally compressing
            int len;
            BufferedInputStream bfobj = new BufferedInputStream(fobj);
            byte[] chunk = new byte[65536];
            if (comp != 0) {
                tgt = new GZIPOutputStream(bos);
                while ((len = bfobj.read(chunk)) >= 0) {
                    tgt.write(chunk, 0, len);
                }
                tgt.close();
                bos = new BufferedOutputStream(new FileOutputStream(tmpFileBuffer, true));
            } else {
                while ((len = bfobj.read(chunk)) >= 0) {
                    bos.write(chunk, 0, len);
                }
            }
            bos.write(("\r\n" + bdry + "--\r\n").getBytes("UTF-8"));
        } else {
            buf.close();
            bos.write(buf.toString().getBytes("UTF-8"));
        }
        bos.flush();
        bos.close();
        // connection headers
        String url = Consts.SYNC_BASE;
        if (method.equals("register")) {
            url = url + "account/signup" + "?username=" + registerData.getString("u") + "&password="
                    + registerData.getString("p");
        } else if (method.startsWith("upgrade")) {
            url = url + method;
        } else {
            url = syncURL() + method;
        }
        HttpPost httpPost = new HttpPost(url);
        HttpEntity entity = new ProgressByteEntity(tmpFileBuffer);

        // body
        httpPost.setEntity(entity);
        httpPost.setHeader("Content-type", "multipart/form-data; boundary=" + BOUNDARY);

        // HttpParams
        HttpParams params = new BasicHttpParams();
        params.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 30);
        params.setParameter(ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE, new ConnPerRouteBean(30));
        params.setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
        params.setParameter(CoreProtocolPNames.USER_AGENT, "KanjiDroid-" + VersionUtils.getPkgVersionName());
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpConnectionParams.setSoTimeout(params, Connection.CONN_TIMEOUT);

        // Registry
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        registry.register(new Scheme("https", new EasySSLSocketFactory(), 443));
        ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
        if (cancelCallback != null) {
            cancelCallback.setConnectionManager(cm);
        }

        try {
            HttpClient httpClient = new DefaultHttpClient(cm, params);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            // we assume badAuthRaises flag from Anki Desktop always False
            // so just throw new RuntimeException if response code not 200 or 403
            assertOk(httpResponse);
            return httpResponse;
        } catch (SSLException e) {
            Timber.e(e, "SSLException while building HttpClient");
            throw new RuntimeException("SSLException while building HttpClient");
        }
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        Timber.e(e, "BasicHttpSyncer.sync: IOException");
        throw new RuntimeException(e);
    } catch (JSONException e) {
        throw new RuntimeException(e);
    } finally {
        if (tmpFileBuffer != null && tmpFileBuffer.exists()) {
            tmpFileBuffer.delete();
        }
    }
}

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

/**
 * @param infileName/*from  www. ja v  a 2 s .  c om*/
 * @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:tvbrowserdataservice.file.ChannelList.java

public void writeToStream(OutputStream stream) throws IOException, FileFormatException {
    GZIPOutputStream gOut = new GZIPOutputStream(stream);

    OutputStreamWriter writer = new OutputStreamWriter(gOut, "ISO-8859-15");
    for (int i = 0; i < getChannelCount(); i++) {
        ChannelItem channelItem = mChannelList.get(i);
        Channel channel = channelItem.getChannel();
        StringBuilder line = new StringBuilder();
        line.append(channel.getCountry()).append(';').append(channel.getTimeZone().getID());
        line.append(';').append(channel.getId());
        line.append(';').append(channel.getUnescapedName());
        line.append(';').append(channel.getCopyrightNotice());
        line.append(';').append(channel.getWebpage() == null ? "http://tvbrowser.org" : channel.getWebpage());
        line.append(';').append(channelItem.getIconUrl() == null ? "" : channelItem.getIconUrl());
        line.append(';').append(channel.getCategories());
        line.append(";\"").append(StringEscapeUtils.escapeHtml(channel.getName())).append('"');
        writer.write(line.toString());//  ww  w .jav a 2  s  .  com
        writer.write('\n');
    }
    writer.close();

    gOut.close();
}

From source file:com.panet.imeta.trans.steps.blockingstep.BlockingStep.java

private boolean addBuffer(RowMetaInterface rowMeta, Object[] r) {
    if (r != null) {
        data.buffer.add(r); // Save row
    }/*from  w  w w  . j av a2  s.co  m*/

    // Time to write to disk: buffer in core is full!
    if (data.buffer.size() == meta.getCacheSize() // Buffer is full: dump to disk 
            || (data.files.size() > 0 && r == null && data.buffer.size() > 0) // No more records: join from disk 
    ) {
        // Then write them to disk...
        DataOutputStream dos;
        GZIPOutputStream gzos;
        int p;

        try {
            FileObject fileObject = KettleVFS.createTempFile(meta.getPrefix(), ".tmp",
                    environmentSubstitute(meta.getDirectory()));

            data.files.add(fileObject); // Remember the files!
            OutputStream outputStream = KettleVFS.getOutputStream(fileObject, false);
            if (meta.getCompress()) {
                gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
                dos = new DataOutputStream(gzos);
            } else {
                dos = new DataOutputStream(outputStream);
                gzos = null;
            }

            // How many records do we have?
            dos.writeInt(data.buffer.size());

            for (p = 0; p < data.buffer.size(); p++) {
                // Just write the data, nothing else
                rowMeta.writeData(dos, (Object[]) data.buffer.get(p));
            }
            // Close temp-file
            dos.close(); // close data stream
            if (gzos != null) {
                gzos.close(); // close gzip stream
            }
            outputStream.close(); // close file stream
        } catch (Exception e) {
            logError("Error processing tmp-file: " + e.toString());
            return false;
        }

        data.buffer.clear();
    }

    return true;
}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

private void writeResponse(HttpServletRequest request, HttpServletResponse response, String responsePayload)
        throws IOException {

    byte[] reply = responsePayload.getBytes(CHARSET_UTF8);
    String contentType = CONTENT_TYPE_TEXT_PLAIN_UTF8;

    if (acceptsGzipEncoding(request) && shouldCompressResponse(request, response, responsePayload)) {
        // Compress the reply and adjust headers.
        ///*from   www  .jav a 2  s . c o m*/
        ByteArrayOutputStream output = null;
        GZIPOutputStream gzipOutputStream = null;
        Throwable caught = null;
        try {
            output = new ByteArrayOutputStream(reply.length);
            gzipOutputStream = new GZIPOutputStream(output);
            gzipOutputStream.write(reply);
            gzipOutputStream.finish();
            gzipOutputStream.flush();
            response.setHeader(CONTENT_ENCODING, CONTENT_ENCODING_GZIP);
            reply = output.toByteArray();
        } catch (UnsupportedEncodingException e) {
            caught = e;
        } catch (IOException e) {
            caught = e;
        } finally {
            if (null != gzipOutputStream) {
                gzipOutputStream.close();
            }
            if (null != output) {
                output.close();
            }
        }

        if (caught != null) {
            /**
             * Our logger will not be servlet context's log (we don't have
             * direct access to it at this point)
             * @author rlogman@gmail.com
             */
            logger.error("Unable to compress response", caught);
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }
    }

    // Send the reply.
    //
    response.setContentLength(reply.length);
    response.setContentType(contentType);
    response.setStatus(HttpServletResponse.SC_OK);
    response.getOutputStream().write(reply);
}

From source file:org.pentaho.di.trans.steps.blockingstep.BlockingStep.java

private boolean addBuffer(RowMetaInterface rowMeta, Object[] r) {
    if (r != null) {
        data.buffer.add(r); // Save row
    }//from w  ww.  ja v  a2s. co  m

    // Time to write to disk: buffer in core is full!
    if (data.buffer.size() == meta.getCacheSize() // Buffer is full: dump to disk
            || (data.files.size() > 0 && r == null && data.buffer.size() > 0) // No more records: join from disk
    ) {
        // Then write them to disk...
        DataOutputStream dos;
        GZIPOutputStream gzos;
        int p;

        try {
            FileObject fileObject = KettleVFS.createTempFile(meta.getPrefix(), ".tmp",
                    environmentSubstitute(meta.getDirectory()), getTransMeta());

            data.files.add(fileObject); // Remember the files!
            OutputStream outputStream = KettleVFS.getOutputStream(fileObject, false);
            if (meta.getCompress()) {
                gzos = new GZIPOutputStream(new BufferedOutputStream(outputStream));
                dos = new DataOutputStream(gzos);
            } else {
                dos = new DataOutputStream(outputStream);
                gzos = null;
            }

            // How many records do we have?
            dos.writeInt(data.buffer.size());

            for (p = 0; p < data.buffer.size(); p++) {
                // Just write the data, nothing else
                rowMeta.writeData(dos, data.buffer.get(p));
            }
            // Close temp-file
            dos.close(); // close data stream
            if (gzos != null) {
                gzos.close(); // close gzip stream
            }
            outputStream.close(); // close file stream
        } catch (Exception e) {
            logError("Error processing tmp-file: " + e.toString());
            return false;
        }

        data.buffer.clear();
    }

    return true;
}