Example usage for java.util.zip Deflater BEST_COMPRESSION

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

Introduction

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

Prototype

int BEST_COMPRESSION

To view the source code for java.util.zip Deflater BEST_COMPRESSION.

Click Source Link

Document

Compression level for best compression.

Usage

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

private String encryptToken(String codeTokenKeyName, Gson gson, UUID refreshToken)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException,
        InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException {
    byte[] bjson = refreshToken.toString().getBytes("UTF-8");

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE,
            GlobalEntries.getGlobalEntries().getConfigManager().getSecretKey(codeTokenKeyName));

    byte[] encJson = cipher.doFinal(bjson);
    String base64d = new String(org.bouncycastle.util.encoders.Base64.encode(encJson));

    Token token = new Token();
    token.setEncryptedRequest(base64d);/*from  w ww . j  a va 2  s . c  om*/
    token.setIv(new String(org.bouncycastle.util.encoders.Base64.encode(cipher.getIV())));

    byte[] bxml = gson.toJson(token).getBytes("UTF-8");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();

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

    compressor.write(bxml);
    compressor.flush();
    compressor.close();

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

From source file:com.ibm.jaggr.core.impl.layer.LayerTest.java

@Test
public void gzipTests() throws Exception {
    replay(mockAggregator, mockRequest, mockResponse, mockDependencies);
    requestAttributes.put(IAggregator.AGGREGATOR_REQATTRNAME, mockAggregator);
    String configJson = "{paths:{p1:'p1',p2:'p2'}, packages:[{name:'foo', location:'foo'}]}";
    configRef.set(new ConfigImpl(mockAggregator, tmpdir.toURI(), configJson));
    configJson = "{paths:{p1:'p1',p2:'p2'}}";
    List<String> layerCacheInfo = new LinkedList<String>();
    configRef.set(new ConfigImpl(mockAggregator, tmpdir.toURI(), configJson));
    File cacheDir = mockAggregator.getCacheManager().getCacheDir();
    ConcurrentLinkedHashMap<String, CacheEntry> cacheMap = (ConcurrentLinkedHashMap<String, CacheEntry>) ((LayerCacheImpl) mockAggregator
            .getCacheManager().getCache().getLayers()).getLayerBuildMap();

    MockRequestedModuleNames modules = new MockRequestedModuleNames();
    modules.setModules(Arrays.asList(new String[] { "p1/a", "p1/p1" }));
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    LayerImpl layer = newLayerImpl(modules.toString(), mockAggregator);

    InputStream in = layer.getInputStream(mockRequest, mockResponse);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    CopyUtil.copy(in, bos);//from   w  w w .  j av a2 s  .  c  o  m
    byte[] unzipped = bos.toByteArray();
    assertEquals("[update_lastmod1, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    assertEquals(unzipped.length, Integer.parseInt(responseAttributes.get("Content-Length")));
    assertEquals("weighted size error", unzipped.length, cacheMap.weightedSize());
    assertEquals("cache file size error", unzipped.length, TestUtils.getDirListSize(cacheDir, layerFilter));

    bos = new ByteArrayOutputStream();
    VariableGZIPOutputStream compress = new VariableGZIPOutputStream(bos, 10240); // is 10k too big?
    compress.setLevel(Deflater.BEST_COMPRESSION);
    Writer writer = new OutputStreamWriter(compress, "UTF-8"); //$NON-NLS-1$
    CopyUtil.copy(new ByteArrayInputStream(unzipped), writer);
    byte[] zipped = bos.toByteArray();

    requestHeaders.put("Accept-Encoding", "gzip");
    in = layer.getInputStream(mockRequest, mockResponse);
    bos = new ByteArrayOutputStream();
    CopyUtil.copy(in, bos);
    assertArrayEquals(zipped, bos.toByteArray());
    assertEquals(zipped.length, Integer.parseInt(responseAttributes.get("Content-Length")));
    // ensure that the response was generated by zipping the cached unzipped  response
    assertEquals("[added, zip_unzipped, update_weights_1]", layerCacheInfo.toString());
    assertEquals("weighted size error", zipped.length + unzipped.length, cacheMap.weightedSize());
    assertEquals("cache file size error", zipped.length + unzipped.length,
            TestUtils.getDirListSize(cacheDir, layerFilter));

    requestHeaders.remove("Accept-Encoding");
    in = layer.getInputStream(mockRequest, mockResponse);
    bos = new ByteArrayOutputStream();
    CopyUtil.copy(in, bos);
    assertArrayEquals(unzipped, bos.toByteArray());
    assertEquals(unzipped.length, Integer.parseInt(responseAttributes.get("Content-Length")));
    // ensure response came from cache
    assertEquals("[hit_1]", layerCacheInfo.toString());
    assertEquals("weighted size error", zipped.length + unzipped.length, cacheMap.weightedSize());
    assertEquals("cache file size error", zipped.length + unzipped.length,
            TestUtils.getDirListSize(cacheDir, layerFilter));

    requestHeaders.put("Accept-Encoding", "gzip");
    in = layer.getInputStream(mockRequest, mockResponse);
    bos = new ByteArrayOutputStream();
    CopyUtil.copy(in, bos);
    assertArrayEquals(zipped, bos.toByteArray());
    assertEquals(zipped.length, Integer.parseInt(responseAttributes.get("Content-Length")));
    // ensure response came from cache
    assertEquals("[hit_1]", layerCacheInfo.toString());
    assertEquals("weighted size error", zipped.length + unzipped.length, cacheMap.weightedSize());
    assertEquals("cache file size error", zipped.length + unzipped.length,
            TestUtils.getDirListSize(cacheDir, layerFilter));

    mockAggregator.getCacheManager().clearCache();
    cacheMap = (ConcurrentLinkedHashMap<String, CacheEntry>) ((LayerCacheImpl) mockAggregator.getCacheManager()
            .getCache().getLayers()).getLayerBuildMap();
    requestAttributes.put(LayerImpl.LAYERCACHEINFO_PROPNAME, layerCacheInfo);
    layer = newLayerImpl(modules.toString(), mockAggregator);
    requestAttributes.put(IHttpTransport.REQUESTEDMODULENAMES_REQATTRNAME, modules);
    in = layer.getInputStream(mockRequest, mockResponse);
    bos = new ByteArrayOutputStream();
    CopyUtil.copy(in, bos);
    assertArrayEquals(zipped, bos.toByteArray());
    assertEquals(zipped.length, Integer.parseInt(responseAttributes.get("Content-Length")));
    assertEquals("[zip, update_keygen, update_key, update_add]", layerCacheInfo.toString());
    assertEquals("weighted size error", zipped.length, cacheMap.weightedSize());
    assertEquals("cache file size error", zipped.length, TestUtils.getDirListSize(cacheDir, layerFilter));

    requestHeaders.remove("Accept-Encoding");
    in = layer.getInputStream(mockRequest, mockResponse);
    bos = new ByteArrayOutputStream();
    CopyUtil.copy(in, bos);
    assertArrayEquals(unzipped, bos.toByteArray());
    assertEquals(unzipped.length, Integer.parseInt(responseAttributes.get("Content-Length")));
    // ensure response was generated by unzipping the cached zipped response
    assertEquals("[added, unzip_zipped, update_weights_1]", layerCacheInfo.toString());
    assertEquals("weighted size error", zipped.length + unzipped.length, cacheMap.weightedSize());
    assertEquals("cache file size error", zipped.length + unzipped.length,
            TestUtils.getDirListSize(cacheDir, layerFilter));

    requestHeaders.put("Accept-Encoding", "gzip");
    in = layer.getInputStream(mockRequest, mockResponse);
    bos = new ByteArrayOutputStream();
    CopyUtil.copy(in, bos);
    assertArrayEquals(zipped, bos.toByteArray());
    assertEquals(zipped.length, Integer.parseInt(responseAttributes.get("Content-Length")));
    // ensure response came from cache
    assertEquals("[hit_1]", layerCacheInfo.toString());
    assertEquals("weighted size error", zipped.length + unzipped.length, cacheMap.weightedSize());
    assertEquals("cache file size error", zipped.length + unzipped.length,
            TestUtils.getDirListSize(cacheDir, layerFilter));

    requestHeaders.remove("Accept-Encoding");
    in = layer.getInputStream(mockRequest, mockResponse);
    bos = new ByteArrayOutputStream();
    CopyUtil.copy(in, bos);
    assertArrayEquals(unzipped, bos.toByteArray());
    assertEquals(unzipped.length, Integer.parseInt(responseAttributes.get("Content-Length")));
    // ensure response came from cache
    assertEquals("[hit_1]", layerCacheInfo.toString());
    assertEquals("weighted size error", zipped.length + unzipped.length, cacheMap.weightedSize());
    assertEquals("cache file size error", zipped.length + unzipped.length,
            TestUtils.getDirListSize(cacheDir, layerFilter));
}

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);/*from  w  w w .  j  a  v a 2s . c om*/
    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:ch.randelshofer.cubetwister.HTMLExporter.java

/**
 * Processes a pack200 template, by writing it both as a pack200 file and
 * a Jar file to the output stream.//from  ww  w  .  ja  v  a 2  s . co  m
 *
 * @param filename The name of the template. Must end with ".jar.pack.gz".
 * @param in An input stream for reading the contents of the template.
 */
private void processPack200Template(String filename, InputStream in) throws IOException {
    p.setNote("Exporting " + filename + " ...");
    p.setProgress(p.getProgress() + 1);

    // Determine whether we can skip this file
    boolean skip = true;
    int pos1 = filename.lastIndexOf('/');
    int pos2 = filename.lastIndexOf("Player.jar.pack.gz");
    if (pos2 != -1) {
        for (CubeKind ck : playerCubeKinds) {
            if (ck.isNameOfKind(filename.substring(pos1 + 1, pos2))) {
                skip = false;
                break;
            }
        }
        if (skip)
            for (CubeKind ck : virtualCubeKinds) {
                if (ck.isNameOfKind(filename.substring(pos1 + 1, pos2))) {
                    skip = false;
                    break;
                }
            }
    }
    if (skip) {
        pos1 = filename.lastIndexOf("Virtual");
        pos2 = filename.lastIndexOf(".jar.pack.gz");
        if (pos2 != -1) {
            for (CubeKind ck : virtualCubeKinds) {
                if (ck.isNameOfKind(filename.substring(pos1 + 7, pos2))) {
                    skip = false;
                    break;
                }
            }
        }
    }
    if (skip) {
        return;
    }

    byte[] buf = new byte[1024];
    int len;

    // Write the pack200 file into the output and into a temporary buffer
    putNextEntry(filename);
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    while (-1 != (len = in.read(buf, 0, buf.length))) {
        tmp.write(buf, 0, len);
        entryOut.write(buf, 0, len);
    }
    closeEntry();
    tmp.close();

    // Uncompress the pack200 file from the temporary buffer into the output
    putNextEntry(filename.substring(0, filename.length() - 8));
    InputStream itmp = new GZIPInputStream(new ByteArrayInputStream(tmp.toByteArray()));
    JarOutputStream jout = new JarOutputStream(entryOut);
    jout.setLevel(Deflater.BEST_COMPRESSION);
    Unpacker unpacker = Pack200.newUnpacker();
    unpacker.unpack(itmp, jout);

    jout.finish();
    closeEntry();
}

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 {/*from   w w  w . ja  v a2s . 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.portfolio.data.provider.MysqlAdminProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read)
        return "faux";

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {//w  ww .  j a  v a2  s .  c o  m
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("3");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        Element metawad = document.createElement("metadata-wad");
        metawad.setAttribute("prog", "main.jsp");
        metawad.setAttribute("owner", "N");
        root.appendChild(metawad);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, groupId);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {

            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                PrintWriter ecri;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    String fileName = portfolioUuid + ".zip";

                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;

                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();

                } catch (IOException io) {

                    io.printStackTrace();
                }
            }
        }

        return stw.toString();

    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}

From source file:com.portfolio.data.provider.MysqlDataProvider.java

@Override
public Object getPortfolio(MimeType outMimeType, String portfolioUuid, int userId, int groupId, String label,
        String resource, String files, int substid) throws Exception {
    String rootNodeUuid = getPortfolioRootNode(portfolioUuid);
    String header = "";
    String footer = "";
    NodeRight nodeRight = credential.getPortfolioRight(userId, groupId, portfolioUuid, Credential.READ);
    if (!nodeRight.read) {
        userId = credential.getPublicUid();
        //         NodeRight nodeRight = new NodeRight(false,false,false,false,false,false);
        /// Vrifie les droits avec le compte publique (dernire chance)
        nodeRight = credential.getPublicRight(userId, 123, rootNodeUuid, "dummy");
        if (!nodeRight.read)
            return "faux";
    }//  w  w w . j ava2s.c  o m

    if (outMimeType.getSubType().equals("xml")) {
        //         header = "<portfolio xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' schemaVersion='1.0'>";
        //         footer = "</portfolio>";

        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder;
        Document document = null;
        try {
            documentBuilder = documentBuilderFactory.newDocumentBuilder();
            document = documentBuilder.newDocument();
            document.setXmlStandalone(true);
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        }

        Element root = document.createElement("portfolio");
        root.setAttribute("id", portfolioUuid);
        root.setAttribute("code", "0");

        //// Noeuds supplmentaire pour WAD
        // Version
        Element verNode = document.createElement("version");
        Text version = document.createTextNode("4");
        verNode.appendChild(version);
        root.appendChild(verNode);
        // metadata-wad
        //         Element metawad = document.createElement("metadata-wad");
        //         metawad.setAttribute("prog", "main.jsp");
        //         metawad.setAttribute("owner", "N");
        //         root.appendChild(metawad);
        int owner = credential.getOwner(userId, portfolioUuid);
        String isOwner = "N";
        if (owner == userId)
            isOwner = "Y";
        root.setAttribute("owner", isOwner);

        //          root.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
        //          root.setAttribute("schemaVersion", "1.0");
        document.appendChild(root);

        getLinearXml(portfolioUuid, rootNodeUuid, root, true, null, userId, nodeRight.groupId,
                nodeRight.groupLabel);

        StringWriter stw = new StringWriter();
        Transformer serializer = TransformerFactory.newInstance().newTransformer();
        serializer.transform(new DOMSource(document), new StreamResult(stw));

        if (resource != null && files != null) {
            if (resource.equals("true") && files.equals("true")) {
                String adressedufichier = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".xml";
                String adresseduzip = System.getProperty("user.dir") + "/tmp_getPortfolio_" + new Date()
                        + ".zip";

                File file = null;
                PrintWriter ecrire;
                try {
                    file = new File(adressedufichier);
                    ecrire = new PrintWriter(new FileOutputStream(adressedufichier));
                    ecrire.println(stw.toString());
                    ecrire.flush();
                    ecrire.close();
                    System.out.print("fichier cree ");
                } catch (IOException ioe) {
                    System.out.print("Erreur : ");
                    ioe.printStackTrace();
                }

                try {
                    ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(adresseduzip));
                    zip.setMethod(ZipOutputStream.DEFLATED);
                    zip.setLevel(Deflater.BEST_COMPRESSION);
                    File dataDirectories = new File(file.getName());
                    FileInputStream fis = new FileInputStream(dataDirectories);
                    byte[] bytes = new byte[fis.available()];
                    fis.read(bytes);

                    ZipEntry entry = new ZipEntry(file.getName());
                    entry.setTime(dataDirectories.lastModified());
                    zip.putNextEntry(entry);
                    zip.write(bytes);
                    zip.closeEntry();
                    fis.close();
                    //zipDirectory(dataDirectories, zip);
                    zip.close();

                    file.delete();

                    return adresseduzip;
                } catch (FileNotFoundException fileNotFound) {
                    fileNotFound.printStackTrace();
                } catch (IOException io) {
                    io.printStackTrace();
                }
            }
        }

        return stw.toString();
    } else if (outMimeType.getSubType().equals("json")) {
        header = "{\"portfolio\": { \"-xmlns:xsi\": \"http://www.w3.org/2001/XMLSchema-instance\",\"-schemaVersion\": \"1.0\",";
        footer = "}}";
    }

    return header + getNode(outMimeType, rootNodeUuid, true, userId, groupId, label).toString() + footer;
}

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

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