Example usage for java.util.zip DeflaterOutputStream DeflaterOutputStream

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

Introduction

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

Prototype

public DeflaterOutputStream(OutputStream out, boolean syncFlush) 

Source Link

Document

Creates a new output stream with a default compressor, a default buffer size and the specified flush mode.

Usage

From source file:com.tremolosecurity.idp.providers.OpenIDConnectIdP.java

private void postResponse(OpenIDConnectTransaction transaction, HttpServletRequest request,
        HttpServletResponse response, AuthInfo authInfo, UrlHolder holder) throws Exception {
    //first generate a lastmile token
    OpenIDConnectTrust trust = trusts.get(transaction.getClientID());

    ConfigManager cfgMgr = (ConfigManager) request.getAttribute(ProxyConstants.TREMOLO_CFG_OBJ);

    DateTime now = new DateTime();
    DateTime notBefore = now.minus(trust.getCodeTokenTimeToLive());
    DateTime notAfter = now.plus(trust.getCodeTokenTimeToLive());

    com.tremolosecurity.lastmile.LastMile lmreq = new com.tremolosecurity.lastmile.LastMile(
            request.getRequestURI(), notBefore, notAfter, authInfo.getAuthLevel(), authInfo.getAuthMethod());
    lmreq.getAttributes().add(new Attribute("dn", authInfo.getUserDN()));
    Attribute attr = new Attribute("scope");
    attr.getValues().addAll(transaction.getScope());
    lmreq.getAttributes().add(attr);//ww  w . j  av  a  2s.  co  m
    if (transaction.getNonce() != null) {
        lmreq.getAttributes().add(new Attribute("nonce", transaction.getNonce()));
    }
    SecretKey key = cfgMgr.getSecretKey(trust.getCodeLastmileKeyName());

    String codeToken = lmreq.generateLastMileToken(key);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    DeflaterOutputStream compressor = new DeflaterOutputStream(baos,
            new Deflater(Deflater.BEST_COMPRESSION, true));

    compressor.write(org.bouncycastle.util.encoders.Base64.decode(codeToken.getBytes("UTF-8")));
    compressor.flush();
    compressor.close();

    String b64 = new String(org.bouncycastle.util.encoders.Base64.encode(baos.toByteArray()));

    StringBuffer b = new StringBuffer();
    b.append(transaction.getRedirectURI()).append("?").append("code=").append(URLEncoder.encode(b64, "UTF-8"))
            .append("&state=").append(URLEncoder.encode(transaction.getState(), "UTF-8"));

    response.sendRedirect(b.toString());

}

From source file:com.enonic.esl.xml.XMLTool.java

public static byte[] documentToDeflatedBytes(Document doc) {
    ByteArrayOutputStream out = new ByteArrayOutputStream(4096);
    Deflater deflater = new Deflater(Deflater.BEST_COMPRESSION);
    DeflaterOutputStream dos = new DeflaterOutputStream(out, deflater);
    printDocument(dos, doc, null, 0, false);
    try {/*w ww  .  j  av  a  2 s .  c o m*/
        dos.close();
    } catch (IOException e) {
        throw new XMLToolException("Failed to close deflater output stream", e);
    }
    return out.toByteArray();
}

From source file:com.twinsoft.convertigo.beans.connectors.SiteClipperConnector.java

private void doProcessRequest(Shuttle shuttle) throws IOException, ServletException, EngineException {
    shuttle.statisticsTaskID = context.statistics.start(EngineStatistics.GET_DOCUMENT);
    try {/*w w  w. j  a  v  a 2s. co m*/
        shuttle.sharedScope = context.getSharedScope();

        String domain = shuttle.getRequest(QueryPart.host) + shuttle.getRequest(QueryPart.port);
        Engine.logSiteClipper.trace("(SiteClipperConnector) Prepare the request for the domain " + domain);
        if (!shouldRewrite(domain)) {
            Engine.logSiteClipper.info(
                    "(SiteClipperConnector) The domain " + domain + " is not allowed with this connector");
            shuttle.response.sendError(HttpServletResponse.SC_FORBIDDEN,
                    "The domain " + domain + " is not allowed with this connector");
            return;
        }

        String uri = shuttle.getRequest(QueryPart.uri);

        Engine.logSiteClipper.info("Preparing " + shuttle.request.getMethod() + " " + shuttle.getRequestUrl());

        HttpMethod httpMethod = null;
        XulRecorder xulRecorder = context.getXulRecorder();
        if (xulRecorder != null) {
            httpMethod = shuttle.httpMethod = xulRecorder.getRecord(shuttle.getRequestUrlAndQuery());
        }
        if (httpMethod == null) {
            try {
                switch (shuttle.getRequestHttpMethodType()) {
                case GET:
                    httpMethod = new GetMethod(uri);
                    break;
                case POST:
                    httpMethod = new PostMethod(uri);
                    ((PostMethod) httpMethod)
                            .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream()));
                    break;
                case PUT:
                    httpMethod = new PutMethod(uri);
                    ((PutMethod) httpMethod)
                            .setRequestEntity(new InputStreamRequestEntity(shuttle.request.getInputStream()));
                    break;
                case DELETE:
                    httpMethod = new DeleteMethod(uri);
                    break;
                case HEAD:
                    httpMethod = new HeadMethod(uri);
                    break;
                case OPTIONS:
                    httpMethod = new OptionsMethod(uri);
                    break;
                case TRACE:
                    httpMethod = new TraceMethod(uri);
                    break;
                default:
                    throw new ServletException(
                            "(SiteClipperConnector) unknown http method " + shuttle.request.getMethod());
                }
                httpMethod.setFollowRedirects(false);
            } catch (Exception e) {
                throw new ServletException(
                        "(SiteClipperConnector) unexpected exception will building the http method : "
                                + e.getMessage());
            }
            shuttle.httpMethod = httpMethod;

            SiteClipperScreenClass screenClass = getCurrentScreenClass();
            Engine.logSiteClipper.info("Request screen class: " + screenClass.getName());

            for (String name : Collections
                    .list(GenericUtils.<Enumeration<String>>cast(shuttle.request.getHeaderNames()))) {
                if (requestHeadersToIgnore.contains(HeaderName.parse(name))) {
                    Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring request header " + name);
                } else {
                    String value = shuttle.request.getHeader(name);
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) Copying request header " + name + "=" + value);
                    shuttle.setRequestCustomHeader(name, value);
                }
            }

            Engine.logSiteClipper.debug("(SiteClipperConnector) applying request rules for the screenclass "
                    + screenClass.getName());
            for (IRequestRule rule : screenClass.getRequestRules()) {
                if (rule.isEnabled()) {
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) applying request rule " + rule.getName());
                    rule.fireEvents();
                    boolean done = rule.applyOnRequest(shuttle);
                    Engine.logSiteClipper.debug("(SiteClipperConnector) the request rule " + rule.getName()
                            + " is " + (done ? "well" : "not") + " applied");
                } else {
                    Engine.logSiteClipper
                            .trace("(SiteClipperConnector) skip the disabled request rule " + rule.getName());
                }
            }

            for (Entry<String, String> header : shuttle.requestCustomHeaders.entrySet()) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) Push request header " + header.getKey()
                        + "=" + header.getValue());
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }

            String queryString = shuttle.request.getQueryString();

            if (queryString != null) {
                try {
                    // Fake test in order to check query string validity
                    new URI("http://localhost/index?" + queryString, true,
                            httpMethod.getParams().getUriCharset());
                } catch (URIException e) {
                    // Bugfix #2103
                    StringBuffer newQuery = new StringBuffer();
                    for (String part : RegexpUtils.pattern_and.split(queryString)) {
                        String[] pair = RegexpUtils.pattern_equals.split(part, 2);
                        try {
                            newQuery.append('&')
                                    .append(URLEncoder.encode(URLDecoder.decode(pair[0], "UTF-8"), "UTF-8"));
                            if (pair.length > 1) {
                                newQuery.append('=').append(
                                        URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8"));
                            }
                        } catch (UnsupportedEncodingException ee) {
                            Engine.logSiteClipper
                                    .trace("(SiteClipperConnector) failed to encode query part : " + part);
                        }
                    }

                    queryString = newQuery.length() > 0 ? newQuery.substring(1) : newQuery.toString();
                    Engine.logSiteClipper.trace("(SiteClipperConnector) re-encode query : " + queryString);
                }
            }

            Engine.logSiteClipper.debug("(SiteClipperConnector) Copying the query string : " + queryString);
            httpMethod.setQueryString(queryString);

            //            if (context.httpState == null) {
            //               Engine.logSiteClipper.debug("(SiteClipperConnector) Creating new HttpState for context id " + context.contextID);
            //               context.httpState = new HttpState();
            //            } else {
            //               Engine.logSiteClipper.debug("(SiteClipperConnector) Using HttpState of context id " + context.contextID);
            //            }

            getHttpState(shuttle);

            HostConfiguration hostConfiguration = getHostConfiguration(shuttle);

            HttpMethodParams httpMethodParams = httpMethod.getParams();
            httpMethodParams.setBooleanParameter("http.connection.stalecheck", true);
            httpMethodParams.setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, true));

            Engine.logSiteClipper.info("Requesting " + httpMethod.getName() + " "
                    + hostConfiguration.getHostURL() + httpMethod.getURI().toString());

            HttpClient httpClient = context.getHttpClient3(shuttle.getHttpPool());
            HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, shuttle.getHttpPool());
            httpClient.executeMethod(hostConfiguration, httpMethod, context.httpState);
        } else {
            Engine.logSiteClipper.info("Retrieve recorded response from Context");
        }

        int status = httpMethod.getStatusCode();

        shuttle.processState = ProcessState.response;

        Engine.logSiteClipper.info("Request terminated with status " + status);
        shuttle.response.setStatus(status);

        if (Engine.isStudioMode() && status == HttpServletResponse.SC_OK
                && shuttle.getResponseMimeType().startsWith("text/")) {
            fireDataChanged(new ConnectorEvent(this, shuttle.getResponseAsString()));
        }

        SiteClipperScreenClass screenClass = getCurrentScreenClass();
        Engine.logSiteClipper.info("Response screen class: " + screenClass.getName());

        if (Engine.isStudioMode()) {
            Engine.theApp.fireObjectDetected(new EngineEvent(screenClass));
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            String name = header.getName();
            if (responseHeadersToIgnore.contains(HeaderName.parse(name))) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) Ignoring response header " + name);
            } else {
                String value = header.getValue();
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) Copying response header " + name + "=" + value);
                shuttle.responseCustomHeaders.put(name, value);
            }
        }

        Engine.logSiteClipper.debug(
                "(SiteClipperConnector) applying response rules for the screenclass " + screenClass.getName());
        for (IResponseRule rule : screenClass.getResponseRules()) {
            if (rule.isEnabled()) {
                Engine.logSiteClipper.trace("(SiteClipperConnector) applying response rule " + rule.getName());
                rule.fireEvents();
                boolean done = rule.applyOnResponse(shuttle);
                Engine.logSiteClipper.debug("(SiteClipperConnector) the response rule " + rule.getName()
                        + " is " + (done ? "well" : "not") + " applied");
            } else {
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) skip the disabled response rule " + rule.getName());
            }
        }

        for (Entry<String, String> header : shuttle.responseCustomHeaders.entrySet()) {
            Engine.logSiteClipper.trace(
                    "(SiteClipperConnector) Push request header " + header.getKey() + "=" + header.getValue());
            shuttle.response.addHeader(header.getKey(), header.getValue());
        }

        if (shuttle.postInstructions != null) {
            JSONArray instructions = new JSONArray();
            for (IClientInstruction instruction : shuttle.postInstructions) {
                try {
                    instructions.put(instruction.getInstruction());
                } catch (JSONException e) {
                    Engine.logSiteClipper.error(
                            "(SiteClipperConnector) Failed to add a post instruction due to a JSONException",
                            e);
                }
            }
            String codeToInject = "<script>C8O_postInstructions = " + instructions.toString() + "</script>\n"
                    + "<script src=\"" + shuttle.getRequest(QueryPart.full_convertigo_path)
                    + "/scripts/jquery.min.js\"></script>\n" + "<script src=\""
                    + shuttle.getRequest(QueryPart.full_convertigo_path)
                    + "/scripts/siteclipper.js\"></script>\n";

            String content = shuttle.getResponseAsString();
            Matcher matcher = HtmlLocation.head_top.matcher(content);
            String newContent = RegexpUtils.inject(matcher, codeToInject);
            if (newContent == null) {
                matcher = HtmlLocation.body_top.matcher(content);
                newContent = RegexpUtils.inject(matcher, codeToInject);
            }
            if (newContent != null) {
                shuttle.setResponseAsString(newContent);
            } else {
                Engine.logSiteClipper.info(
                        "(SiteClipperConnector) Failed to find a head or body tag in the response content");
                Engine.logSiteClipper.trace("(SiteClipperConnector) Response content : \"" + content + "\"");
            }
        }

        long nbBytes = 0L;
        if (shuttle.responseAsString != null
                && shuttle.responseAsString.hashCode() != shuttle.responseAsStringOriginal.hashCode()) {
            OutputStream os = shuttle.response.getOutputStream();
            switch (shuttle.getResponseContentEncoding()) {
            case gzip:
                os = new GZIPOutputStream(os);
                break;
            case deflate:
                os = new DeflaterOutputStream(os,
                        new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
                break;
            default:
                break;
            }
            nbBytes = shuttle.responseAsByte.length;
            IOUtils.write(shuttle.responseAsString, os, shuttle.getResponseCharset());
            os.close();
        } else {
            InputStream is = (shuttle.responseAsByte == null) ? httpMethod.getResponseBodyAsStream()
                    : new ByteArrayInputStream(shuttle.responseAsByte);
            if (is != null) {
                nbBytes = 0;
                OutputStream os = shuttle.response.getOutputStream();
                int read = is.read();
                while (read >= 0) {
                    os.write(read);
                    os.flush();
                    read = is.read();
                    nbBytes++;
                }
                is.close();
                //               nbBytes = IOUtils.copyLarge(is, shuttle.response.getOutputStream());
                Engine.logSiteClipper
                        .trace("(SiteClipperConnector) Response body copyied (" + nbBytes + " bytes)");
            }
        }
        shuttle.response.getOutputStream().close();

        shuttle.score = getScore(nbBytes);
        Engine.logSiteClipper
                .debug("(SiteClipperConnector) Request terminated with a score of " + shuttle.score);
    } finally {
        long duration = context.statistics.stop(shuttle.statisticsTaskID);
        if (context.requestedObject != null) {
            try {
                Engine.theApp.billingManager.insertBilling(context, Long.valueOf(duration),
                        Long.valueOf(shuttle.score));
            } catch (Exception e) {
                Engine.logContext.warn("Unable to insert billing ticket (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
    }
}

From source file:org.wso2.carbon.identity.sso.saml.util.SAMLSSOUtil.java

/**
 * Compresses the response String//from   w  w w.j  a v  a 2  s  .co  m
 *
 * @param response
 * @return
 * @throws IOException
 */
public static String compressResponse(String response) throws IOException {

    Deflater deflater = new Deflater(Deflater.DEFLATED, true);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
    try {
        deflaterOutputStream.write(response.getBytes(StandardCharsets.UTF_8));
        return Base64.encodeBytes(byteArrayOutputStream.toByteArray(), Base64.DONT_BREAK_LINES);
    } finally {
        deflaterOutputStream.close();
    }
}

From source file:com.newrelic.agent.transport.DataSenderImpl.java

private OutputStream getOutputStream(OutputStream out, String encoding)
        /* 966:    */ throws IOException
/* 967:    */ {/*w w  w.j av  a  2  s.co  m*/
    /* 968:776 */ if ("deflate".equals(encoding)) {
        /* 969:777 */ return new DeflaterOutputStream(out, new Deflater(-1));
        /* 970:    */ }
    /* 971:779 */ return out;
    /* 972:    */ }

From source file:org.wso2.carbon.appmgt.gateway.handlers.security.saml2.SAML2AuthenticationHandler.java

private String encodeRequestMessage(RequestAbstractType requestMessage) {

    try {/*from   ww  w  .j av  a 2s  .  co m*/
        DefaultBootstrap.bootstrap();
    } catch (ConfigurationException e) {
        log.error("Error while initializing opensaml library", e);
        return null;
    }
    Marshaller marshaller = Configuration.getMarshallerFactory().getMarshaller(requestMessage);
    Element authDOM = null;
    try {
        authDOM = marshaller.marshall(requestMessage);

        /* Compress the message */
        Deflater deflater = new Deflater(Deflater.DEFLATED, true);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        DeflaterOutputStream deflaterOutputStream = new DeflaterOutputStream(byteArrayOutputStream, deflater);
        StringWriter rspWrt = new StringWriter();
        XMLHelper.writeNode(authDOM, rspWrt);
        deflaterOutputStream.write(rspWrt.toString().getBytes());
        deflaterOutputStream.close();

        /* Encoding the compressed message */
        String encodedRequestMessage = Base64.encodeBytes(byteArrayOutputStream.toByteArray(),
                Base64.DONT_BREAK_LINES);
        return URLEncoder.encode(encodedRequestMessage, "UTF-8").trim();

    } catch (MarshallingException e) {
        log.error("Error occurred while encoding SAML request", e);
    } catch (UnsupportedEncodingException e) {
        log.error("Error occurred while encoding SAML request", e);
    } catch (IOException e) {
        log.error("Error occurred while encoding SAML request", e);
    }
    return null;
}

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

public static void fullSyncFromLocal(String password, String username, String deckName, String deckPath) {
    URL url;//from  w w w . ja v a  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:org.apache.flex.swf.io.SWFWriter.java

/**
 * This method does not close the {@code output} stream.
 *//*from   www . ja  v a  2 s . 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);
    }
}