Example usage for java.util.zip Deflater end

List of usage examples for java.util.zip Deflater end

Introduction

In this page you can find the example usage for java.util.zip Deflater end.

Prototype

public void end() 

Source Link

Document

Closes the compressor and discards any unprocessed input.

Usage

From source file:org.jbpm.bpel.persistence.db.type.ElementType.java

public void nullSafeSet(PreparedStatement st, Object value, int index) throws HibernateException, SQLException {
    // easy way out: null value
    if (value == null) {
        st.setNull(index, SQL_TYPES[0]);
        if (log.isTraceEnabled())
            log.trace("binding null to parameter: " + index);
    } else {/*from www  . j  ava  2s .c  om*/
        Element element = (Element) value;
        try {
            // create identity transformer
            Transformer idTransformer = XmlUtil.getTransformerFactory().newTransformer();

            // allocate memory result stream
            ByteArrayOutputStream byteStream = new ByteArrayOutputStream();

            // deflate if requested
            Integer deflateLevel = getXmlDeflateLevel();
            if (deflateLevel != null) {
                // introduce deflater stream
                Deflater deflater = new Deflater(deflateLevel.intValue());
                OutputStream deflaterStream = new DeflaterOutputStream(byteStream, deflater);
                // write element to stream
                idTransformer.transform(new DOMSource(element), new StreamResult(deflaterStream));
                // release resources
                try {
                    deflaterStream.close();
                } catch (IOException e) {
                    // should not happen
                    throw new AssertionError(e);
                }
                deflater.end();
            } else {
                // write element to stream
                idTransformer.transform(new DOMSource(element), new StreamResult(byteStream));
                // noop
                // byteStream.close();
            }

            // extract contents of result stream
            st.setBytes(index, byteStream.toByteArray());
            if (log.isTraceEnabled())
                log.trace("binding '" + byteStream + "' to parameter: " + index);
        } catch (TransformerException e) {
            throw new HibernateException("could not transform to xml stream: " + element, e);
        }
    }
}

From source file:org.ajax4jsf.resource.ResourceBuilderImpl.java

protected byte[] encrypt(byte[] src) {
    try {/*from   w w w. ja  v  a2s.c  o  m*/
        Deflater compressor = new Deflater(Deflater.BEST_SPEED);
        byte[] compressed = new byte[src.length + 100];
        compressor.setInput(src);
        compressor.finish();
        int totalOut = compressor.deflate(compressed);
        byte[] zipsrc = new byte[totalOut];
        System.arraycopy(compressed, 0, zipsrc, 0, totalOut);
        compressor.end();
        return codec.encode(zipsrc);
    } catch (Exception e) {
        throw new FacesException("Error encode resource data", e);
    }
}

From source file:com.itude.mobile.android.util.DataUtil.java

/**
 * Compress byte array /*from w w w.  j  av  a  2s . c  o  m*/
 * 
 * @param uncompressed byte array
 * @return compressed byte array
 */
public byte[] compress(byte[] uncompressed) {
    byte[] result = null;

    Deflater deflater = new Deflater();
    deflater.setInput(uncompressed);
    deflater.finish();

    // Create an expandable byte array to hold the compressed data. 
    // You cannot use an array that's the same size as the original because 
    // there is no guarantee that the compressed data will be smaller than 
    // the uncompressed data. 

    ByteArrayOutputStream bos = new ByteArrayOutputStream(uncompressed.length);

    // Compress the data 
    byte[] buf = new byte[1024];
    while (!deflater.finished()) {
        int count = deflater.deflate(buf);
        bos.write(buf, 0, count);
    }
    deflater.end();

    try {
        bos.close();
    } catch (IOException e) {
        MBLog.w(TAG, "Unable to close stream");
    }

    // Get the compressed data 

    result = bos.toByteArray();

    return result;
}

From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.unsafe.DeflateJsonQueryHandler.java

@Override
public ByteBuffer encode(final WebsockQuery query) throws EncodeException {
    ByteBuffer result = null;/*w  w  w  . ja v  a  2  s .  co m*/

    try {
        final JSONObject obj = JsonConverter.toJson(query);
        byte[] data = obj.toString().getBytes();

        //compress
        final Deflater deflater = new Deflater(fCompression, true);
        deflater.setInput(data);
        deflater.finish();

        int totalSize = 0;

        int read = deflater.deflate(fBuffer, 0, BUFFER_SIZE, Deflater.SYNC_FLUSH);
        while (true) {
            totalSize += read;

            if (deflater.finished()) {
                //if finished, directly add buffer
                fBuffers.add(fBuffer);
                break;
            } else {
                //make a copy, reuse buffer
                fBuffers.add(Arrays.copyOf(fBuffer, read));
                read = deflater.deflate(fBuffer, 0, BUFFER_SIZE, Deflater.SYNC_FLUSH);
            }
        }

        result = fuse(totalSize);

        deflater.end();

        if (fDebug) {
            fTotalBytesOut += totalSize;
            fLogger.log(Level.FINEST, "encoded compressed JSON message: " + totalSize + " bytes\n"
                    + "total bytes sent: " + fTotalBytesOut);
        }
    } catch (JSONException e) {
        e.printStackTrace();
        throw new EncodeException(query, "failed to encode JSON", e);
    }

    return result;
}

From source file:org.adeptnet.auth.saml.SAMLClient.java

private byte[] deflate(final byte[] input) throws IOException {
    // deflate and base-64 encode it
    final Deflater deflater = new Deflater(Deflater.DEFAULT_COMPRESSION, true);
    deflater.setInput(input);/*from w  w w  .j av  a2  s .  com*/
    deflater.finish();

    byte[] tmp = new byte[8192];
    int count;

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    while (!deflater.finished()) {
        count = deflater.deflate(tmp);
        bos.write(tmp, 0, count);
    }
    bos.close();
    deflater.end();

    return bos.toByteArray();
}

From source file:org.apache.flex.swf.io.SWFWriter.java

/**
 * This method does not close the {@code output} stream.
 *///from  w w  w.j  a v  a 2s .c om
@Override
public void writeTo(OutputStream output) {
    assert output != null;

    writtenTags = new HashSet<ITag>();

    // The SWF data after the first 8 bytes can be compressed. At this
    // moment, we only encode the "compressible" part.
    writeCompressibleHeader();

    // FileAttributes must be the first tag.
    writeTag(SWF.getFileAttributes(swf));

    // Raw Metadata
    String metadata = swf.getMetadata();

    if (metadata != null)
        writeTag(new MetadataTag(metadata));

    // SetBackgroundColor tag
    final RGB backgroundColor = swf.getBackgroundColor();
    if (backgroundColor != null)
        writeTag(new SetBackgroundColorTag(backgroundColor));

    // EnableDebugger2 tag        
    if (enableDebug)
        writeTag(new EnableDebugger2Tag("NO-PASSWORD"));

    // ProductInfo tag for Flex compatibility
    ProductInfoTag productInfo = swf.getProductInfo();
    if (productInfo != null)
        writeTag(productInfo);

    // ScriptLimits tag
    final ScriptLimitsTag scriptLimitsTag = swf.getScriptLimits();
    if (scriptLimitsTag != null)
        writeTag(scriptLimitsTag);

    // Frames and enclosed tags.
    writeFrames();

    // End of SWF
    writeTag(new EndTag());

    writtenTags = null;

    // Compute the size of the SWF file.
    long length = outputBuffer.size() + 8;
    try {
        // write the first 8 bytes
        switch (useCompression) {
        case LZMA:
            output.write('Z');
            break;
        case ZLIB:
            output.write('C');
            break;
        case NONE:
            output.write('F');
            break;
        default:
            assert false;
        }

        output.write('W');
        output.write('S');
        output.write(swf.getVersion());

        writeInt(output, (int) length);

        // write the "compressible" part
        switch (useCompression) {
        case LZMA: {
            LZMACompressor compressor = new LZMACompressor();
            compressor.compress(outputBuffer);
            // now write the compressed length
            final long compressedLength = compressor.getLengthOfCompressedPayload();
            assert compressedLength <= 0xffffffffl;

            writeInt(output, (int) compressedLength);

            // now write the LZMA props
            compressor.writeLZMAProperties(output);

            // Normally LZMA (7zip) would write an 8 byte length here, but we don't, because the
            // SWF header already has this info

            // now write the n bytes of LZMA data, followed by the 6 byte EOF
            compressor.writeDataAndEnd(output);
            output.flush();
        }
            break;
        case ZLIB: {
            int compressionLevel = enableDebug ? Deflater.BEST_SPEED : Deflater.BEST_COMPRESSION;
            Deflater deflater = new Deflater(compressionLevel);
            DeflaterOutputStream deflaterStream = new DeflaterOutputStream(output, deflater);
            deflaterStream.write(outputBuffer.getBytes(), 0, outputBuffer.size());
            deflaterStream.finish();
            deflater.end();
            deflaterStream.flush();
            break;
        }
        case NONE: {
            output.write(outputBuffer.getBytes(), 0, outputBuffer.size());
            output.flush();
            break;
        }
        default:
            assert false;
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:edu.umass.cs.gigapaxos.SQLPaxosLogger.java

/**
 * @param data//from   ww w.  java2  s .c  om
 * @return Compressed form.
 * @throws IOException
 */
public static byte[] deflate(byte[] data) throws IOException {
    if (!DB_COMPRESSION)
        return data;
    byte[] compressed = null;
    double inflation = 1;
    int compressedLength = data.length;
    do {
        Deflater deflator = new Deflater();
        compressed = new byte[(int) ((inflation *= 1.1) * data.length + 16)];
        deflator.setInput(data);
        deflator.finish();
        compressedLength = deflator.deflate(compressed);
        deflator.end();
    } while (compressedLength == compressed.length);
    return Arrays.copyOf(compressed, compressedLength);
}

From source file:PngEncoder.java

/**
 * Write the image data into the pngBytes array.
 * This will write one or more PNG "IDAT" chunks. In order
 * to conserve memory, this method grabs as many rows as will
 * fit into 32K bytes, or the whole image; whichever is less.
 *
 *
 * @return true if no errors; false if error grabbing pixels
 *///from www .j  a va 2s  .  co  m
protected boolean writeImageData() {
    int rowsLeft = this.height; // number of rows remaining to write
    int startRow = 0; // starting row to process this time through
    int nRows; // how many rows to grab at a time

    byte[] scanLines; // the scan lines to be compressed
    int scanPos; // where we are in the scan lines
    int startPos; // where this line's actual pixels start (used
                  // for filtering)

    byte[] compressedLines; // the resultant compressed lines
    int nCompressed; // how big is the compressed area?

    //int depth;              // color depth ( handle only 8 or 32 )

    PixelGrabber pg;

    this.bytesPerPixel = (this.encodeAlpha) ? 4 : 3;

    Deflater scrunch = new Deflater(this.compressionLevel);
    ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024);

    DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes, scrunch);
    try {
        while (rowsLeft > 0) {
            nRows = Math.min(32767 / (this.width * (this.bytesPerPixel + 1)), rowsLeft);
            nRows = Math.max(nRows, 1);

            int[] pixels = new int[this.width * nRows];

            pg = new PixelGrabber(this.image, 0, startRow, this.width, nRows, pixels, 0, this.width);
            try {
                pg.grabPixels();
            } catch (Exception e) {
                System.err.println("interrupted waiting for pixels!");
                return false;
            }
            if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
                System.err.println("image fetch aborted or errored");
                return false;
            }

            /*
             * Create a data chunk. scanLines adds "nRows" for
             * the filter bytes.
             */
            scanLines = new byte[this.width * nRows * this.bytesPerPixel + nRows];

            if (this.filter == FILTER_SUB) {
                this.leftBytes = new byte[16];
            }
            if (this.filter == FILTER_UP) {
                this.priorRow = new byte[this.width * this.bytesPerPixel];
            }

            scanPos = 0;
            startPos = 1;
            for (int i = 0; i < this.width * nRows; i++) {
                if (i % this.width == 0) {
                    scanLines[scanPos++] = (byte) this.filter;
                    startPos = scanPos;
                }
                scanLines[scanPos++] = (byte) ((pixels[i] >> 16) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i] >> 8) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i]) & 0xff);
                if (this.encodeAlpha) {
                    scanLines[scanPos++] = (byte) ((pixels[i] >> 24) & 0xff);
                }
                if ((i % this.width == this.width - 1) && (this.filter != FILTER_NONE)) {
                    if (this.filter == FILTER_SUB) {
                        filterSub(scanLines, startPos, this.width);
                    }
                    if (this.filter == FILTER_UP) {
                        filterUp(scanLines, startPos, this.width);
                    }
                }
            }

            /*
             * Write these lines to the output area
             */
            compBytes.write(scanLines, 0, scanPos);

            startRow += nRows;
            rowsLeft -= nRows;
        }
        compBytes.close();

        /*
         * Write the compressed bytes
         */
        compressedLines = outBytes.toByteArray();
        nCompressed = compressedLines.length;

        this.crc.reset();
        this.bytePos = writeInt4(nCompressed, this.bytePos);
        this.bytePos = writeBytes(IDAT, this.bytePos);
        this.crc.update(IDAT);
        this.bytePos = writeBytes(compressedLines, nCompressed, this.bytePos);
        this.crc.update(compressedLines, 0, nCompressed);

        this.crcValue = this.crc.getValue();
        this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
        scrunch.finish();
        scrunch.end();
        return true;
    } catch (IOException e) {
        System.err.println(e.toString());
        return false;
    }
}

From source file:org.pentaho.reporting.libraries.base.util.PngEncoder.java

/**
 * Write the image data into the pngBytes array. This will write one or more PNG "IDAT" chunks. In order to conserve
 * memory, this method grabs as many rows as will fit into 32K bytes, or the whole image; whichever is less.
 *
 * @return true if no errors; false if error grabbing pixels
 *///  ww w .j  a v  a  2 s. c o m
protected boolean writeImageData() {

    this.bytesPerPixel = (this.encodeAlpha) ? 4 : 3;

    final Deflater scrunch = new Deflater(this.compressionLevel);
    final ByteArrayOutputStream outBytes = new ByteArrayOutputStream(1024);
    final DeflaterOutputStream compBytes = new DeflaterOutputStream(outBytes, scrunch);
    try {
        int startRow = 0; // starting row to process this time through
        //noinspection SuspiciousNameCombination
        int rowsLeft = this.height; // number of rows remaining to write
        while (rowsLeft > 0) {
            final int nRows = Math.max(Math.min(32767 / (this.width * (this.bytesPerPixel + 1)), rowsLeft), 1);

            final int[] pixels = new int[this.width * nRows];

            final PixelGrabber pg = new PixelGrabber(this.image, 0, startRow, this.width, nRows, pixels, 0,
                    this.width);
            try {
                pg.grabPixels();
            } catch (Exception e) {
                logger.error("interrupted waiting for pixels!", e);
                return false;
            }
            if ((pg.getStatus() & ImageObserver.ABORT) != 0) {
                logger.error("image fetch aborted or errored");
                return false;
            }

            /*
            * Create a data chunk. scanLines adds "nRows" for
            * the filter bytes.
            */
            final byte[] scanLines = new byte[this.width * nRows * this.bytesPerPixel + nRows];

            if (this.filter == PngEncoder.FILTER_SUB) {
                this.leftBytes = new byte[16];
            }
            if (this.filter == PngEncoder.FILTER_UP) {
                this.priorRow = new byte[this.width * this.bytesPerPixel];
            }

            int scanPos = 0;
            int startPos = 1;
            for (int i = 0; i < this.width * nRows; i++) {
                if (i % this.width == 0) {
                    scanLines[scanPos++] = (byte) this.filter;
                    startPos = scanPos;
                }
                scanLines[scanPos++] = (byte) ((pixels[i] >> 16) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i] >> 8) & 0xff);
                scanLines[scanPos++] = (byte) ((pixels[i]) & 0xff);
                if (this.encodeAlpha) {
                    scanLines[scanPos++] = (byte) ((pixels[i] >> 24) & 0xff);
                }
                if ((i % this.width == this.width - 1) && (this.filter != PngEncoder.FILTER_NONE)) {
                    if (this.filter == PngEncoder.FILTER_SUB) {
                        filterSub(scanLines, startPos, this.width);
                    }
                    if (this.filter == PngEncoder.FILTER_UP) {
                        filterUp(scanLines, startPos, this.width);
                    }
                }
            }

            /*
            * Write these lines to the output area
            */
            compBytes.write(scanLines, 0, scanPos);

            startRow += nRows;
            rowsLeft -= nRows;
        }
        compBytes.close();

        /*
        * Write the compressed bytes
        */
        final byte[] compressedLines = outBytes.toByteArray();
        final int nCompressed = compressedLines.length;

        this.crc.reset();
        this.bytePos = writeInt4(nCompressed, this.bytePos);
        this.bytePos = writeBytes(PngEncoder.IDAT, this.bytePos);
        this.crc.update(PngEncoder.IDAT);
        this.bytePos = writeBytes(compressedLines, nCompressed, this.bytePos);
        this.crc.update(compressedLines, 0, nCompressed);

        this.crcValue = this.crc.getValue();
        this.bytePos = writeInt4((int) this.crcValue, this.bytePos);
        return true;
    } catch (IOException e) {
        logger.error("Failed to write PNG Data", e);
        return false;
    } finally {
        scrunch.finish();
        scrunch.end();
    }
}