Example usage for java.util.zip DeflaterOutputStream write

List of usage examples for java.util.zip DeflaterOutputStream write

Introduction

In this page you can find the example usage for java.util.zip DeflaterOutputStream write.

Prototype

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

Source Link

Document

Writes an array of bytes to the compressed output stream.

Usage

From source file:org.jasig.cas.authentication.principal.GoogleAccountsServiceTests.java

protected static String encodeMessage(final String xmlString) throws IOException {
    byte[] xmlBytes = xmlString.getBytes("UTF-8");
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteOutputStream);
    deflaterOutputStream.write(xmlBytes, 0, xmlBytes.length);
    deflaterOutputStream.close();/*from   www . j a v a 2s  .  c om*/

    // next, base64 encode it
    Base64 base64Encoder = new Base64();
    byte[] base64EncodedByteArray = base64Encoder.encode(byteOutputStream.toByteArray());
    return new String(base64EncodedByteArray);
}

From source file:com.integrareti.integraframework.util.RequestUtil.java

/**
 * Generates an encoded and compressed String from the specified
 * XML-formatted String. The String is encoded in the following order:
 * <p>/*from   w w w  .  ja  v  a2 s.  c  o  m*/
 * 1. URL encode <br>
 * 2. Base64 encode <br>
 * 3. Deflate <br>
 * 
 * @param xmlString
 *            XML-formatted String that is to be encoded
 * @return String containing the encoded contents of the specified XML
 *         String
 */
public static String encodeMessage(String xmlString) throws IOException, UnsupportedEncodingException {
    // first DEFLATE compress the document (saml-bindings-2.0,
    // section 3.4.4.1)
    byte[] xmlBytes = xmlString.getBytes("UTF-8");
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteOutputStream);
    deflaterOutputStream.write(xmlBytes, 0, xmlBytes.length);
    deflaterOutputStream.close();
    // next, base64 encode it
    Base64 base64Encoder = new Base64();
    byte[] base64EncodedByteArray = base64Encoder.encode(byteOutputStream.toByteArray());
    String base64EncodedMessage = new String(base64EncodedByteArray);
    // finally, URL encode it
    String urlEncodedMessage = URLEncoder.encode(base64EncodedMessage, "UTF-8");
    return urlEncodedMessage;
}

From source file:net.paygate.saml.util.RequestUtil.java

/**
 * Generates an encoded and compressed String from the specified XML-formatted
 * String. The String is encoded in the following order:
 * <p>//from  www.  java  2  s .  co  m
 * 1. URL encode <br>
 * 2. Base64 encode <br>
 * 3. Deflate <br>
 * 
 * @param xmlString XML-formatted String that is to be encoded
 * @return String containing the encoded contents of the specified XML String
 */
public static String encodeMessage(String xmlString) throws IOException, UnsupportedEncodingException {
    // first DEFLATE compress the document (saml-bindings-2.0,
    // section 3.4.4.1)
    byte[] xmlBytes = xmlString.getBytes("UTF-8");
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteOutputStream);
    deflaterOutputStream.write(xmlBytes, 0, xmlBytes.length);
    deflaterOutputStream.close();

    // next, base64 encode it
    Base64 base64Encoder = new Base64();
    byte[] base64EncodedByteArray = base64Encoder.encode(byteOutputStream.toByteArray());
    String base64EncodedMessage = new String(base64EncodedByteArray);

    // finally, URL encode it
    String urlEncodedMessage = URLEncoder.encode(base64EncodedMessage);

    return urlEncodedMessage;
}

From source file:com.jzboy.couchdb.DatabaseDocUpdateTest.java

@BeforeClass
public static void setUpClass() throws Exception {
    dbName = "jzboy_test_db_" + System.currentTimeMillis();
    instance = new Database(dbName);
    instance.create();//from  www.ja  va 2  s. c  o  m

    // create a gzipped attachment
    final String inputString = "blahblahblah??";
    byte[] input = inputString.getBytes("utf-8");
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DeflaterOutputStream deflater = new DeflaterOutputStream(os);
    deflater.write(input, 0, input.length);
    deflater.close();
    attachment = os.toByteArray();
}

From source file:com.ichi2.anki.SyncClient.java

public static void fullSyncFromLocal(String password, String username, String deckName, String deckPath) {
    URL url;/*w  w  w.  j ava  2  s.  c o m*/
    try {
        Log.i(AnkiDroidApp.TAG, "Fullup");
        url = new URL(AnkiDroidProxy.SYNC_URL + "fullup");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();

        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setRequestMethod("POST");

        conn.setRequestProperty("Connection", "close");
        conn.setRequestProperty("Charset", "UTF-8");
        // conn.setRequestProperty("Content-Length", "8494662");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + MIME_BOUNDARY);
        conn.setRequestProperty("Host", AnkiDroidProxy.SYNC_HOST);

        DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
        Log.i(AnkiDroidApp.TAG, "Pass");
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END);
        ds.writeBytes("Content-Disposition: form-data; name=\"p\"" + END + END + password + END);
        Log.i(AnkiDroidApp.TAG, "User");
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END);
        ds.writeBytes("Content-Disposition: form-data; name=\"u\"" + END + END + username + END);
        Log.i(AnkiDroidApp.TAG, "DeckName");
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END);
        ds.writeBytes("Content-Disposition: form-data; name=\"d\"" + END + END + deckName + END);
        Log.i(AnkiDroidApp.TAG, "Deck");
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + END);
        ds.writeBytes("Content-Disposition: form-data; name=\"deck\";filename=\"deck\"" + END);
        ds.writeBytes("Content-Type: application/octet-stream" + END);
        ds.writeBytes(END);

        FileInputStream fStream = new FileInputStream(deckPath);
        byte[] buffer = new byte[Utils.CHUNK_SIZE];
        int length = -1;

        Deflater deflater = new Deflater(Deflater.BEST_SPEED);
        DeflaterOutputStream dos = new DeflaterOutputStream(ds, deflater);

        Log.i(AnkiDroidApp.TAG, "Writing buffer...");
        while ((length = fStream.read(buffer)) != -1) {
            dos.write(buffer, 0, length);
            Log.i(AnkiDroidApp.TAG, "Length = " + length);
        }
        dos.finish();
        fStream.close();

        ds.writeBytes(END);
        ds.writeBytes(TWO_HYPHENS + MIME_BOUNDARY + TWO_HYPHENS + END);
        Log.i(AnkiDroidApp.TAG, "Closing streams...");

        ds.flush();
        ds.close();

        // Ensure we got the HTTP 200 response code
        int responseCode = conn.getResponseCode();
        if (responseCode != 200) {
            Log.i(AnkiDroidApp.TAG, "Response code = " + responseCode);
            // throw new Exception(String.format("Received the response code %d from the URL %s", responseCode,
            // url));
        } else {
            Log.i(AnkiDroidApp.TAG, "Response code = 200");
        }

        // Read the response
        InputStream is = conn.getInputStream();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int bytesRead;
        while ((bytesRead = is.read(bytes)) != -1) {
            baos.write(bytes, 0, bytesRead);
        }
        byte[] bytesReceived = baos.toByteArray();
        baos.close();

        is.close();
        String response = new String(bytesReceived);

        Log.i(AnkiDroidApp.TAG, "Finished!");
    } catch (MalformedURLException e) {
        Log.i(AnkiDroidApp.TAG, "MalformedURLException = " + e.getMessage());
    } catch (IOException e) {
        Log.i(AnkiDroidApp.TAG, "IOException = " + e.getMessage());
    }
}

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 .ja v a  2  s .  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.apache.flex.compiler.internal.embedding.transcoders.JPEGTranscoder.java

public static byte[] deflate(byte[] buf) throws IOException {
    Deflater deflater = new Deflater(Deflater.BEST_SPEED);
    DAByteArrayOutputStream out = new DAByteArrayOutputStream();
    DeflaterOutputStream deflaterStream = new DeflaterOutputStream(out, deflater);
    try {/*ww  w  .j  a v  a 2  s .  c  o  m*/
        deflaterStream.write(buf, 0, buf.length);
        deflaterStream.finish();
        deflater.end();
    } finally {
        IOUtils.closeQuietly(deflaterStream);
    }
    return out.getDirectByteArray();
}

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

/**
 * This method does not close the {@code output} stream.
 *//*  w  w w . ja  v  a 2s.c o m*/
@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:org.apache.pdfbox.filter.FlateFilter.java

/**
 * {@inheritDoc}//  ww w .java2 s . com
 */
public void encode(InputStream rawData, OutputStream result, COSDictionary options, int filterIndex)
        throws IOException {
    DeflaterOutputStream out = new DeflaterOutputStream(result);
    int amountRead = 0;
    int mayRead = rawData.available();
    if (mayRead > 0) {
        byte[] buffer = new byte[Math.min(mayRead, BUFFER_SIZE)];
        while ((amountRead = rawData.read(buffer, 0, Math.min(mayRead, BUFFER_SIZE))) != -1) {
            out.write(buffer, 0, amountRead);
        }
    }
    out.close();
    result.flush();
}

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
 */// w ww . ja  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();
    }
}