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:com.sun.faces.renderkit.ResponseStateManagerImpl.java

public void writeState(FacesContext context, SerializedView view) throws IOException {

    StateManager stateManager = Util.getStateManager(context);
    ResponseWriter writer = context.getResponseWriter();

    writer.startElement("input", context.getViewRoot());
    writer.writeAttribute("type", "hidden", null);
    writer.writeAttribute("name", RIConstants.FACES_VIEW, null);
    writer.writeAttribute("id", RIConstants.FACES_VIEW, null);

    if (stateManager.isSavingStateInClient(context)) {
        GZIPOutputStream zos = null;
        ObjectOutputStream oos = null;
        boolean compress = isCompressStateSet(context);

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        if (compress) {
            if (log.isDebugEnabled()) {
                log.debug("Compressing state before saving..");
            }/*from   w w  w.  j  a  va2s.  c om*/
            zos = new GZIPOutputStream(bos);
            oos = new ObjectOutputStream(zos);
        } else {
            oos = new ObjectOutputStream(bos);
        }
        oos.writeObject(view.getStructure());
        oos.writeObject(view.getState());
        oos.close();
        if (compress) {
            zos.close();
        }
        bos.close();

        String valueToWrite = (new String(Base64.encode(bos.toByteArray()), "ISO-8859-1"));
        writer.writeAttribute("value", valueToWrite, null);
    } else {
        writer.writeAttribute("value", view.getStructure(), null);
    }
    writer.endElement("input");

}

From source file:com.couchbase.lite.DatabaseAttachmentTest.java

public void testGzippedAttachments() throws Exception {
    String attachmentName = "index.html";
    byte content[] = "This is a test attachment!".getBytes("UTF-8");

    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    GZIPOutputStream gzipOut = new GZIPOutputStream(byteOut);
    gzipOut.write(content);//  www . ja v  a 2s . c om
    gzipOut.close();
    byte contentGzipped[] = byteOut.toByteArray();

    Document doc = database.createDocument();
    UnsavedRevision rev = doc.createRevision();
    rev.setAttachment(attachmentName, "text/html", new ByteArrayInputStream(contentGzipped));
    rev.save();

    SavedRevision savedRev = doc.getCurrentRevision();
    Attachment attachment = savedRev.getAttachment(attachmentName);

    // As far as revision users are concerned their data is not gzipped
    InputStream in = attachment.getContent();
    assertNotNull(in);
    assertTrue(Arrays.equals(content, IOUtils.toByteArray(in)));
    in.close();

    Document gotDoc = database.getDocument(doc.getId());
    Revision gotRev = gotDoc.getCurrentRevision();
    Attachment gotAtt = gotRev.getAttachment(attachmentName);
    in = gotAtt.getContent();
    assertNotNull(in);
    assertTrue(Arrays.equals(content, IOUtils.toByteArray(in)));
    in.close();
}

From source file:edu.umn.cs.spatialHadoop.nasa.HDFRasterLayer.java

@Override
public void write(DataOutput out) throws IOException {
    super.write(out);
    out.writeLong(timestamp);// w  w  w . j a  v a  2s . c om
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    ByteBuffer bbuffer = ByteBuffer.allocate(getHeight() * 2 * 8 + 8);
    bbuffer.putInt(getWidth());
    bbuffer.putInt(getHeight());
    gzos.write(bbuffer.array(), 0, bbuffer.position());
    for (int x = 0; x < getWidth(); x++) {
        bbuffer.clear();
        for (int y = 0; y < getHeight(); y++) {
            bbuffer.putLong(sum[x][y]);
            bbuffer.putLong(count[x][y]);
        }
        gzos.write(bbuffer.array(), 0, bbuffer.position());
    }
    gzos.close();

    byte[] serializedData = baos.toByteArray();
    out.writeInt(serializedData.length);
    out.write(serializedData);
}

From source file:XmldapCertsAndKeys.java

/**
 * Encodes a byte array into Base64 notation.
 * <p>/* ww w .ja  v a2  s. co m*/
 * 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
 * @see Base64#GZIP
 * @see Base64#DONT_BREAK_LINES
 * @return the text node
 * @since 2.0
 */
public static String encodeBytes(byte[] source, int off, int len, int options) {
    // Isolate options
    int dontBreakLines = (options & DONT_BREAK_LINES);
    int gzip = (options & GZIP);

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

        try {
            // GZip -> Base64 -> ByteArray
            baos = new java.io.ByteArrayOutputStream();
            b64os = new Base64.OutputStream(baos, ENCODE | dontBreakLines);
            gzos = new java.util.zip.GZIPOutputStream(b64os);

            gzos.write(source, off, len);
            gzos.close();
        } // end try
        catch (java.io.IOException e) {
            e.printStackTrace();
            return null;
        } // end catch
        finally {
            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
    } // 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;
        for (; d < len2; d += 3, e += 4) {
            encode3to4(source, d + off, 3, outBuff, e);

            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

        if (d < len) {
            encode3to4(source, d + off, len - d, outBuff, e);
            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 (java.io.UnsupportedEncodingException uue) {
            return new String(outBuff, 0, e);
        } // end catch

    } // end else: don't compress

}

From source file:net.cbtltd.server.UploadFileService.java

private static boolean getCompressedImage(String fn, BufferedImage image, Map<String, byte[]> images) {
    int fullsizepixels = Text.FULLSIZE_PIXELS_VALUE;
    int thumbnailpixels = Text.THUMBNAIL_PIXELS_VALUE;
    //      ByteBuffer byteArray = new ByteBuffer();
    ByteArrayOutputStream bOutputReg = new ByteArrayOutputStream();
    ByteArrayOutputStream bOutputThumb = new ByteArrayOutputStream();
    ImageIcon imageIcon = new ImageIcon(image);
    try {/*from  w  ww .  j a v a2  s .c om*/
        GZIPOutputStream zipStreamReg = new GZIPOutputStream(bOutputReg);
        GZIPOutputStream zipStreamThumb = new GZIPOutputStream(bOutputThumb);

        if (imageIcon.getImageLoadStatus() == MediaTracker.COMPLETE) {
            ImageIcon fullsizeImage = new ImageIcon(
                    imageIcon.getImage().getScaledInstance(-1, fullsizepixels, Image.SCALE_SMOOTH));
            LOG.debug("\n UploadFileService setImage image= " + imageIcon + " width="
                    + fullsizeImage.getIconWidth() + "  height=" + fullsizeImage.getIconHeight());
            BufferedImage fullsizeBufferedImage = new BufferedImage(fullsizeImage.getIconWidth(),
                    fullsizeImage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics fullsizeGraphics = fullsizeBufferedImage.getGraphics();
            fullsizeGraphics.drawImage(fullsizeImage.getImage(), 0, 0, null);
            String fullsizeFile = fn.substring(0, fn.lastIndexOf('.')) + ".jpg";

            try {
                ImageIO.write(fullsizeBufferedImage, FULLSIZE_JPEG, zipStreamReg);
                zipStreamReg.close();
                bOutputReg.close();
                images.put(fullsizeFile, bOutputReg.toByteArray());
            } catch (IOException x) {
                throw new RuntimeException("Error saving full sized image " + x.getMessage());
            }

            ImageIcon thumbnailImage = new ImageIcon(
                    imageIcon.getImage().getScaledInstance(-1, thumbnailpixels, Image.SCALE_SMOOTH));
            String thumbnailFile = fn.substring(0, fn.lastIndexOf('.')) + "Thumb.jpg";

            BufferedImage thumbnailBufferedImage = new BufferedImage(thumbnailImage.getIconWidth(),
                    thumbnailImage.getIconHeight(), BufferedImage.TYPE_INT_RGB);
            Graphics thumbnailGraphics = thumbnailBufferedImage.getGraphics();
            thumbnailGraphics.drawImage(thumbnailImage.getImage(), 0, 0, null);
            try {
                ImageIO.write(thumbnailBufferedImage, FULLSIZE_JPEG, zipStreamThumb);
                zipStreamThumb.close();
                bOutputThumb.close();
                images.put(thumbnailFile, bOutputThumb.toByteArray());
            } catch (IOException x) {
                throw new RuntimeException("Error saving thumbnail image " + x.getMessage());
            }

            return true;
        } else {
            LOG.error("\n UploadFileService setImage image= " + imageIcon + " width=" + imageIcon.getIconWidth()
                    + "  height=" + imageIcon.getIconHeight());
            return false;
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return true;
}

From source file:org.esigate.DriverTest.java

public void testGzipErrorPage() throws Exception {
    Properties properties = new Properties();
    properties.put(Parameters.REMOTE_URL_BASE.getName(), "http://localhost");
    HttpResponse response = new BasicHttpResponse(new ProtocolVersion("HTTP", 1, 1),
            HttpStatus.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    response.addHeader("Content-type", "Text/html;Charset=UTF-8");
    response.addHeader("Content-encoding", "gzip");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gzos = new GZIPOutputStream(baos);
    byte[] uncompressedBytes = "".getBytes("UTF-8");
    gzos.write(uncompressedBytes, 0, uncompressedBytes.length);
    gzos.close();
    byte[] compressedBytes = baos.toByteArray();
    ByteArrayEntity httpEntity = new ByteArrayEntity(compressedBytes);
    httpEntity.setContentType("Text/html;Charset=UTF-8");
    httpEntity.setContentEncoding("gzip");
    response.setEntity(httpEntity);/*ww w.j a  v a 2 s .co m*/
    mockConnectionManager.setResponse(response);
    Driver driver = createMockDriver(properties, mockConnectionManager);
    CloseableHttpResponse driverResponse;
    try {
        driverResponse = driver.proxy("/", request.build());
        fail("We should get an HttpErrorPage");
    } catch (HttpErrorPage e) {
        driverResponse = e.getHttpResponse();
    }
    assertEquals("", HttpResponseUtils.toString(driverResponse));
}

From source file:org.mule.util.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>/*from w w  w .  j ava2s .c o m*/
 * Valid options:
 * 
 * <pre>
 *              GZIP: gzip-compresses object before encoding it.
 *              DONT_BREAK_LINES: don't break lines at 76 characters
 *                &lt;i&gt;Note: Technically, this makes your encoding non-compliant.&lt;/i&gt;
 * </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(Serializable serializableObject, int options) throws IOException {
    // Streams
    ByteArrayOutputStream baos = null;
    OutputStream b64os = null;
    ObjectOutputStream oos = null;
    GZIPOutputStream gzos = null;

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

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

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

        oos.writeObject(serializableObject);

        if (gzos != null) {
            gzos.finish();
            gzos.close();
        }

        oos.close();
    } // end try
    catch (IOException e) {
        return null;
    } // end catch
    finally {
        IOUtils.closeQuietly(oos);
        IOUtils.closeQuietly(gzos);
        IOUtils.closeQuietly(b64os);
        IOUtils.closeQuietly(baos);
    } // 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

}

From source file:com.weibo.api.motan.protocol.rpc.CompressRpcCodec.java

public byte[] compress(byte[] org, boolean useGzip, int minGzSize) throws IOException {
    if (useGzip && org.length > minGzSize) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        GZIPOutputStream gos = new GZIPOutputStream(outputStream);
        gos.write(org);//from   ww w  . ja  v a  2s .  c om
        gos.finish();
        gos.flush();
        gos.close();
        byte[] ret = outputStream.toByteArray();
        return ret;
    } else {
        return org;
    }

}

From source file:de.mpg.escidoc.services.exportmanager.Export.java

private void generateArchiveBase(String exportFormat, String archiveFormat, byte[] exportOut, String itemList,
        File license, BufferedOutputStream bos) throws ExportManagerException, IOException {

    Utils.checkCondition(!Utils.checkVal(exportFormat) && !(exportOut == null || exportOut.length == 0),
            "Empty export format");

    Utils.checkCondition(!Utils.checkVal(itemList), "Empty item list");

    Utils.checkCondition(!Utils.checkVal(archiveFormat), "Empty archive format");

    switch (ArchiveFormats.valueOf(archiveFormat)) {
    case zip://from   w  ww  .j av a 2  s .  c o m
        try {
            ZipOutputStream zos = new ZipOutputStream(bos);

            // add export result entry
            addDescriptionEnrty(exportOut, exportFormat, zos);

            // add LICENSE AGREEMENT entry
            addLicenseAgreement(license, zos);

            // add files to the zip
            fetchComponentsDo(zos, itemList);

            zos.close();
        } catch (IOException e) {
            throw new ExportManagerException(e);
        }
        break;
    case tar:
        try {
            TarOutputStream tos = new TarOutputStream(bos);

            // add export result entry
            addDescriptionEnrty(exportOut, exportFormat, tos);

            // add LICENSE AGREEMENT entry
            addLicenseAgreement(license, tos);

            // add files to the tar
            fetchComponentsDo(tos, itemList);
            // logger.info("heapSize after  = " +
            // Runtime.getRuntime().totalMemory());
            // logger.info("heapFreeSize after = " +
            // Runtime.getRuntime().freeMemory());

            tos.close();

        } catch (IOException e) {
            throw new ExportManagerException(e);
        }
        break;
    case gzip:
        try {
            long ilfs = calculateItemListFileSizes(itemList);
            long mem = Runtime.getRuntime().freeMemory() / 2;
            if (ilfs > mem) {
                logger.info("Generate tar.gz output in tmp file: files' size = " + ilfs
                        + " > Runtime.getRuntime().freeMemory()/2: " + mem);
                File tar = generateArchiveFile(exportFormat, ArchiveFormats.tar.toString(), exportOut,
                        itemList);
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(tar));
                GZIPOutputStream gzos = new GZIPOutputStream(bos);
                writeFromStreamToStream(bis, gzos);
                bis.close();
                gzos.close();
                tar.delete();
            } else {
                byte[] tar = generateArchive(exportFormat, ArchiveFormats.tar.toString(), exportOut, itemList);
                BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(tar));
                GZIPOutputStream gzos = new GZIPOutputStream(bos);
                writeFromStreamToStream(bis, gzos);
                bis.close();
                gzos.close();
            }

        } catch (IOException e) {
            throw new ExportManagerException(e);
        }
        break;
    default:
        throw new ExportManagerException("Archive format " + archiveFormat + " is not supported");
    }

}

From source file:org.openchaos.android.fooping.service.PingService.java

private void sendMessage(final JSONObject json) {
    boolean encrypt = prefs.getBoolean("SendAES", false);
    boolean compress = prefs.getBoolean("SendGZIP", false);
    String exchangeHost = prefs.getString("ExchangeHost", null);
    int exchangePort = Integer.valueOf(prefs.getString("ExchangePort", "-1"));

    if (encrypt) {
        if (skeySpec == null) {
            try {
                skeySpec = new SecretKeySpec(MessageDigest.getInstance("SHA-256")
                        .digest(prefs.getString("ExchangeKey", null).getBytes("US-ASCII")), "AES");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();/*from  w  w  w  . j  a  v a2s . c  o  m*/
            }
        }

        if (cipher == null) {
            try {
                cipher = Cipher.getInstance("AES/CFB8/NoPadding");
            } catch (Exception e) {
                Log.e(tag, e.toString());
                e.printStackTrace();
            }
        }

        if (skeySpec == null || cipher == null) {
            Log.e(tag, "Encryption requested but not available");
            throw new AssertionError();
        }
    }

    if (exchangeHost == null || exchangePort <= 0 || exchangePort >= 65536) {
        Log.e(tag, "Invalid server name or port");
        throw new AssertionError();
    }

    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        CipherOutputStream cos = null;
        GZIPOutputStream zos = null;

        // TODO: send protocol header to signal compression & encryption

        if (encrypt) {
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            cos = new CipherOutputStream(baos, cipher);

            // write iv block
            baos.write(cipher.getIV());
        }

        final byte[] message = new JSONArray().put(json).toString().getBytes();

        if (compress) {
            zos = new GZIPOutputStream((encrypt) ? (cos) : (baos));
            zos.write(message);
            zos.finish();
            zos.close();
            if (encrypt) {
                cos.close();
            }
        } else if (encrypt) {
            cos.write(message);
            cos.close();
        } else {
            baos.write(message);
        }

        baos.flush();
        final byte[] output = baos.toByteArray();
        baos.close();

        // path MTU is the actual limit here, not only local MTU
        // TODO: make packet fragmentable (clear DF flag)
        if (output.length > 1500) {
            Log.w(tag, "Message probably too long: " + output.length + " bytes");
        }

        DatagramSocket socket = new DatagramSocket();
        // socket.setTrafficClass(0x04 | 0x02); // IPTOS_RELIABILITY | IPTOS_LOWCOST
        socket.send(
                new DatagramPacket(output, output.length, InetAddress.getByName(exchangeHost), exchangePort));
        socket.close();
        Log.d(tag, "message sent: " + output.length + " bytes (raw: " + message.length + " bytes)");
    } catch (Exception e) {
        Log.e(tag, e.toString());
        e.printStackTrace();
    }
}