Example usage for java.util.zip DeflaterOutputStream finish

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

Introduction

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

Prototype

public void finish() throws IOException 

Source Link

Document

Finishes writing compressed data to the output stream without closing the underlying stream.

Usage

From source file:zipB64.java

protected static String encodeMessage(String messageStr) {
    try {/*from  w  ww . j  a v a2 s  .  c o m*/
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        Deflater deflater = new Deflater(Deflater.DEFLATED);
        DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
        deflaterStream.write(messageStr.getBytes("UTF-8"));
        deflaterStream.finish();

        Base64 b = new Base64(-1);
        return new String(b.encode(bytesOut.toByteArray()));
    } catch (Exception e) {
        return "crotte";
    }
}

From source file:com.eviware.soapui.impl.wsdl.support.CompressionSupport.java

private static byte[] DeflaterCompress(byte[] requestContent) throws IOException {
    ByteArrayOutputStream compressedContent = new ByteArrayOutputStream();
    DeflaterOutputStream defstream = new DeflaterOutputStream(compressedContent);
    defstream.write(requestContent);/*from   w ww .  j  a v a  2  s  .  c  o m*/
    defstream.finish();

    // get the compressed content
    return compressedContent.toByteArray();
}

From source file:ch.cern.security.saml2.utils.xml.XMLUtils.java

/**
 * Compress the xml string and encodes it in Base64
 * /*  ww  w  . java2  s . c  om*/
 * @param xmlString
 * @param isDebugEnabled 
 * @return xml string encoded
 * @throws IOException
 * @throws UnsupportedEncodingException
 */
public static String xmlDeflateAndEncode(String xmlString, boolean isDebugEnabled)
        throws IOException, UnsupportedEncodingException {

    if (isDebugEnabled)
        nc.notice(xmlString);

    // Deflate the SAMLResponse value
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    DeflaterOutputStream deflaterStream = new DeflaterOutputStream(bytesOut, deflater);
    deflaterStream.write(xmlString.getBytes());
    deflaterStream.finish();

    // Encoded the deflatedResponse in base64
    Base64 base64encoder = new Base64();
    String base64response = new String(base64encoder.encode(bytesOut.toByteArray()), "UTF-8");

    if (isDebugEnabled)
        nc.notice(base64response);

    return base64response;
}

From source file:ZipUtil.java

public static void zipFileToFile(File flSource, File flTarget) throws IOException {
    Deflater oDeflate = new Deflater(Deflater.DEFLATED, false);

    FileInputStream stmFileIn = new FileInputStream(flSource);
    FileOutputStream stmFileOut = new FileOutputStream(flTarget);
    DeflaterOutputStream stmDeflateOut = new DeflaterOutputStream(stmFileOut, oDeflate);
    try {// w w  w  . j  a  v a 2  s. c o m
        // FileUtil.inputStreamToOutputStream(stmFileIn, stmDeflateOut);
    } //end try
    finally {
        stmDeflateOut.finish();
        stmDeflateOut.flush();
        stmDeflateOut.close();
        stmFileOut.close();
        stmFileIn.close();
    }
}

From source file:fr.mby.saml2.sp.impl.helper.SamlHelper.java

/**
 * Encode a SAML2 request for the HTTP-redirect binding. The encoded message is not URL encoded !
 * /*from  ww w .j av a  2 s  .  c o m*/
 * @param request
 *            the request
 * @return the encoded request
 * @throws IOException
 */
public static String httpRedirectEncode(final String samlMessage) throws IOException {
    String deflatedRequest = null;
    ByteArrayOutputStream byteArrayOutputStream = null;
    DeflaterOutputStream deflaterOutputStream = null;

    try {
        final Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        byteArrayOutputStream = new ByteArrayOutputStream();
        deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);

        // Deflated then Base 64 encoded then Url Encoded for HTTP REDIRECT Binding
        deflaterOutputStream.write(samlMessage.getBytes());
        deflaterOutputStream.finish();
        deflater.finish();

        deflatedRequest = Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);

        if (SamlHelper.LOGGER.isDebugEnabled()) {
            SamlHelper.LOGGER.debug(String.format("SAML 2.0 Request: %s", samlMessage));
            SamlHelper.LOGGER.debug(String.format("Encoded HTTP-Redirect Request: %s", deflatedRequest));
        }
    } finally {
        if (byteArrayOutputStream != null) {
            byteArrayOutputStream.close();
        }
        if (deflaterOutputStream != null) {
            deflaterOutputStream.close();
        }
    }

    return deflatedRequest;
}

From source file:com.autonomy.aci.client.transport.impl.AbstractEncryptionCodec.java

/**
 * Deflates the passed in <tt>String</tt> and prefixes the result with <tt>AUTN:</tt> before returning.
 * @param bytes The byte array to deflate
 * @return The deflated string prefixed with <tt>AUTN:</tt> as a byte array
 * @throws EncryptionCodecException If an error occurred during processing
 *//*w  ww.  j a va2s  .  c  o  m*/
protected byte[] deflateInternal(final byte[] bytes) throws EncryptionCodecException {
    LOGGER.trace("deflateInternal() called...");

    // This is what will deflate for us...
    DeflaterOutputStream deflater = null;

    try {
        // Create the output container...
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();

        // Create the deflater...
        deflater = new DeflaterOutputStream(baos);

        LOGGER.debug("Deflating content...");

        // Deflate the input string...
        deflater.write(bytes);
        deflater.finish();

        // Get the deflated bytes...
        final byte[] deflated = baos.toByteArray();

        LOGGER.debug("Adding prefix to deflated content...");

        // Get The deflated array prefix of AUTN: in bytes...
        final byte[] prefix = "AUTN:".getBytes("UTF-8");

        // Copy both the prefix and the deflated query string into a new array...
        final byte[] toEncrypt = new byte[prefix.length + deflated.length];
        System.arraycopy(prefix, 0, toEncrypt, 0, prefix.length);
        System.arraycopy(deflated, 0, toEncrypt, prefix.length, deflated.length);

        LOGGER.debug("Returning deflated and prefixed string...");

        // Return the deflated query string...
        return toEncrypt;
    } catch (final IOException ioe) {
        throw new EncryptionCodecException("Unable to deflate the input.", ioe);
    } finally {
        IOUtils.getInstance().closeQuietly(deflater);
    }
}

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

public static void fullSyncFromLocal(String password, String username, String deckName, String deckPath) {
    URL url;/*from  www .  ja  va  2s.com*/
    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

/**
 * Writes the IDAT (Image data) chunks to the output stream.
 *
 * @param out the OutputStream to write the chunk to
 * @param csum the Checksum that is updated as data is written
 *             to the passed-in OutputStream
 * @throws IOException if a problem is encountered writing the output
 *///www  .  j a  v a 2 s. c om
private void writeIdatChunks(OutputStream out, Checksum csum) throws IOException {
    int rowWidth = width * outputBpp; // size of image data in a row in bytes.

    int row = 0;

    Deflater deflater = new Deflater(compressionLevel);
    ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
    DeflaterOutputStream defOut = new DeflaterOutputStream(byteOut, deflater);

    byte[] filteredPixelQueue = new byte[rowWidth];

    // Output Pixel Queues
    byte[][] outputPixelQueue = new byte[2][rowWidth];
    Arrays.fill(outputPixelQueue[1], (byte) 0);
    int outputPixelQueueRow = 0;
    int outputPixelQueuePrevRow = 1;

    while (row < height) {
        if (filter == null) {
            defOut.write(0);
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            defOut.write(outputPixelQueue[outputPixelQueueRow], 0, rowWidth);
        } else {
            defOut.write(filter.getType());
            translator.translate(outputPixelQueue[outputPixelQueueRow], row);
            filter.filter(filteredPixelQueue, outputPixelQueue[outputPixelQueueRow],
                    outputPixelQueue[outputPixelQueuePrevRow], outputBpp);
            defOut.write(filteredPixelQueue, 0, rowWidth);
        }

        ++row;
        outputPixelQueueRow = row & 1;
        outputPixelQueuePrevRow = outputPixelQueueRow ^ 1;
    }
    defOut.finish();
    byteOut.close();

    writeInt(out, byteOut.size());
    csum.reset();
    out.write(IDAT);
    byteOut.writeTo(out);
    writeInt(out, (int) csum.getValue());
}

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 {//from w w w.  j a  v a 2  s.c om
        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  ww . j a  va  2s  . co 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);
    }
}