Esempio n. 1
0
 // Token: 0x0600001A RID: 26 RVA: 0x00002C04 File Offset: 0x00000E04
 public static byte[] GZipCompress(byte[] data, bool isClearData = true)
 {
     byte[] result = null;
     try
     {
         using (MemoryStream memoryStream = new MemoryStream())
         {
             using (Stream stream = new GZipOutputStream(memoryStream))
             {
                 stream.Write(data, 0, data.Length);
                 stream.Flush();
             }
             result = memoryStream.ToArray();
         }
     }
     catch (SharpZipBaseException)
     {
     }
     catch (IndexOutOfRangeException)
     {
     }
     if (isClearData)
     {
         Array.Clear(data, 0, data.Length);
     }
     return(result);
 }
Esempio n. 2
0
 public void Compress(SoapMessage message)
 {
     if (tempStream.Length >= minLength)
     {
         MemoryStream     mems = new MemoryStream();
         GZipOutputStream zos  = new GZipOutputStream(mems);
         zos.Write(tempStream.GetBuffer(), 0, (int)tempStream.Length);
         zos.Finish();
         Console.WriteLine("msg len:" + tempStream.Length);
         // Convert the compressed content to a base 64 string
         string compString = Convert.ToBase64String(mems.GetBuffer(), 0, (int)mems.Length);
         byte[] compBytes  = Encoding.UTF8.GetBytes(compString);
         netStream.WriteByte((byte)'C');                     // Compressing flag
         netStream.Write(compBytes, 0, compBytes.Length);
         Console.WriteLine("cmp len:" + compBytes.Length);
         netStream.Flush();
         zos.Close();
     }
     else
     {
         netStream.WriteByte((byte)'N');                     // Not Compressing flag
         netStream.Write(tempStream.GetBuffer(), 0, (int)tempStream.Length);
         netStream.Flush();
     }
 }
Esempio n. 3
0
        override public void AddToStream(Stream stream, EventTracker tracker)
        {
            if (ChildCount > 1)
            {
                throw new Exception("Gzip file " + Uri + " has " + ChildCount + " children");
            }

            if (tracker != null)
            {
                tracker.ExpectingAdded(UriFu.UriToEscapedString(this.Uri));
            }

            UnclosableStream unclosable;

            unclosable = new UnclosableStream(stream);

            GZipOutputStream gz_out;

            gz_out = new GZipOutputStream(unclosable);

            MemoryStream memory;

            memory = new MemoryStream();
            // There should just be one child
            foreach (FileObject file in Children)
            {
                file.AddToStream(memory, tracker);
            }
            gz_out.Write(memory.ToArray(), 0, (int)memory.Length);
            memory.Close();

            gz_out.Close();
        }
Esempio n. 4
0
        //-------------------------------------------------------------------------
        public static byte[] CompressGZIP(byte[] buf)
        {
            if (null == buf || 0 == buf.Length)
            {
                Console.WriteLine("CompressGZIP buf is nil");
                return(buf);
            }

            byte[] bufCompress = buf;
            try
            {
                MemoryStream     ms        = new MemoryStream();
                GZipOutputStream outStream = new GZipOutputStream(ms);
                outStream.Write(buf, 0, buf.Length);
                outStream.Flush();
                outStream.Finish();

                bufCompress = ms.GetBuffer();
                Array.Resize(ref bufCompress, (int)outStream.Length);

                outStream.Close();
                ms.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine("CompressGZIP 错误:" + ex.Message);
            }

            return(bufCompress);
        }
Esempio n. 5
0
        private void ReadComplete(IAsyncResult res)
        {
            ReadState rs = (ReadState)res.AsyncState;

            using (rs.file)
            {
                rs.file.EndRead(res);
                if (rs.compressLevel > 0)
                {
                    byte[] data = rs.data;
                    // don't compress things which are already compressed
                    if ((data.Length > 2) && ((data[0] != 0x1f) || (data[1] != 0x8b)))
                    {
                        MemoryStream compStream = new MemoryStream(rs.data.Length);
                        using (GZipOutputStream gzOut = new GZipOutputStream(compStream))
                        {
                            gzOut.SetLevel(rs.compressLevel);
                            gzOut.Write(rs.data, 0, rs.data.Length);
                            gzOut.Finish();
                            rs.data = compStream.ToArray();
                        }
                    }
                }
                lock (writeData)
                {
                    writeData[rs.writeDataIndex] = rs.data;
                    newWriteSignal.Release(1);
                }
            }
            outstandingReads.Increment();
        }
Esempio n. 6
0
    /* KMP message data format
     * Uncompressed data: [bool-false : data]
     * Compressed data: [bool-true : Int32-uncompressed length : compressed_data]
     */

    public static byte[] Compress(byte[] data, bool forceUncompressed = false)
    {
        if (data == null)
        {
            return(null);
        }
        byte[]           compressedData = null;
        MemoryStream     ms             = null;
        GZipOutputStream gzip           = null;

        try
        {
            ms = new MemoryStream();
            if (data.Length < MESSAGE_COMPRESSION_THRESHOLD || forceUncompressed)
            {
                //Small message, don't compress
                using (BinaryWriter writer = new BinaryWriter(ms))
                {
                    writer.Write(false);
                    writer.Write(data, 0, data.Length);
                    compressedData = ms.ToArray();
                    ms.Close();
                    writer.Close();
                }
            }
            else
            {
                //Compression enabled
                Int32 size = data.Length;
                using (BinaryWriter writer = new BinaryWriter(ms))
                {
                    writer.Write(true);
                    writer.Write(size);
                    gzip = new GZipOutputStream(ms);
                    gzip.Write(data, 0, data.Length);
                    gzip.Close();
                    compressedData = ms.ToArray();
                    ms.Close();
                    writer.Close();
                }
            }
        }
        catch (Exception e)
        {
            KMP.Log.Debug("Exception thrown in Compress(), catch 1, Exception: {0}", e.ToString());
            return(null);
        }
        finally
        {
            if (gzip != null)
            {
                gzip.Dispose();
            }
            if (ms != null)
            {
                ms.Dispose();
            }
        }
        return(compressedData);
    }
Esempio n. 7
0
        private void CreateOrModifyCacheFile(BinaryData cacheBinary, bool compress)
        {
            SN.File      f           = null;
            MemoryStream cacheStream = new MemoryStream();

            if (compress)
            {
                GZipOutputStream gzipStream = new GZipOutputStream(cacheStream);
                byte[]           buff       = Encoding.ASCII.GetBytes(this._content.ToCharArray());
                gzipStream.Write(buff, 0, buff.Length);
                gzipStream.Flush();
                gzipStream.Close();

                // set compressed binary
                byte[] compressedData = cacheStream.ToArray();
                cacheBinary.SetStream(new MemoryStream(compressedData));
            }
            else
            {
                cacheBinary.SetStream(Tools.GetStreamFromString(_content));
            }

            // gets cache file or creates a new one, the new stream will be saved in both cases
            if (!Node.Exists(FullCacheFilePath))
            {
                f      = SN.File.CreateByBinary(this.CacheFolder, cacheBinary);
                f.Name = _cacheFile;
            }
            else
            {
                f        = Node.Load <SN.File>(this.FullCacheFilePath);
                f.Binary = cacheBinary;
            }
            f.Save();
        }
Esempio n. 8
0
        /// <summary>
        /// 지정된 데이타를 압축한다.
        /// </summary>
        /// <param name="input">압축할 Data</param>
        /// <returns>압축된 Data</returns>
        public override byte[] Compress(byte[] input)
        {
            if (IsDebugEnabled)
            {
                log.Debug(CompressorTool.SR.CompressStartMsg);
            }

            // check input data
            if (input.IsZeroLength())
            {
                if (IsDebugEnabled)
                {
                    log.Debug(CompressorTool.SR.InvalidInputDataMsg);
                }

                return(CompressorTool.EmptyBytes);
            }

            byte[] output;
            using (var compressedStream = new MemoryStream(input.Length)) {
                using (var gzs = new GZipOutputStream(compressedStream)) {
                    gzs.SetLevel(ZipLevel);
                    gzs.Write(input, 0, input.Length);
                    gzs.Finish();
                }
                output = compressedStream.ToArray();
            }

            if (IsDebugEnabled)
            {
                log.Debug(CompressorTool.SR.CompressResultMsg, input.Length, output.Length, output.Length / (double)input.Length);
            }

            return(output);
        }
Esempio n. 9
0
        /// <summary>
        /// Gzip压缩缓存文件
        /// </summary>
        /// <param name="filePath">缓存文件路径</param>
        /// <returns>压缩后的二进制</returns>
        public static byte[] GZipStress(string filePath)
        {
            string path = filePath;

            if (!File.Exists(path))
            {
                path = string.Format("{0}/Config/{1}.boxcache", AppDomain.CurrentDomain.BaseDirectory, typeof(T).FullName);
            }
            using (FileStream ms = new FileStream(path, FileMode.Open))
            {
                using (MemoryStream stream = new MemoryStream())
                {
                    GZipOutputStream outStream = new GZipOutputStream(stream);
                    int    readed;
                    byte[] buffer = new byte[2048];
                    do
                    {
                        readed = ms.Read(buffer, 0, buffer.Length);
                        outStream.Write(buffer, 0, readed);
                    }while (readed != 0);
                    outStream.Flush();
                    outStream.Finish();
                    return(stream.GetBuffer());
                }
            }
        }
Esempio n. 10
0
 public static void Main(string[] args)
 {
     if (args[0] == "-d")           // decompress
     {
         Stream     s         = new GZipInputStream(File.OpenRead(args[1]));
         FileStream fs        = File.Create(Path.GetFileNameWithoutExtension(args[1]));
         int        size      = 2048;
         byte[]     writeData = new byte[2048];
         while (true)
         {
             size = s.Read(writeData, 0, size);
             if (size > 0)
             {
                 fs.Write(writeData, 0, size);
             }
             else
             {
                 break;
             }
         }
         s.Close();
     }
     else             // compress
     {
         Stream     s         = new GZipOutputStream(File.Create(args[0] + ".gz"));
         FileStream fs        = File.OpenRead(args[0]);
         byte[]     writeData = new byte[fs.Length];
         fs.Read(writeData, 0, (int)fs.Length);
         s.Write(writeData, 0, writeData.Length);
         s.Close();
     }
 }
Esempio n. 11
0
    public void firstTest()
    {
        MemoryStream     ms   = new MemoryStream();
        GZipOutputStream gzip = new GZipOutputStream(ms);

        byte[] binary = Encoding.UTF8.GetBytes("sddddddddd");
        gzip.Write(binary, 0, binary.Length);
        gzip.Close();
        byte[] press = ms.ToArray();
        Debug.Log(Convert.ToBase64String(press) + "  " + press.Length);


        GZipInputStream gzi = new GZipInputStream(new MemoryStream(press));

        MemoryStream re    = new MemoryStream();
        int          count = 0;

        byte[] data = new byte[4096];
        while ((count = gzi.Read(data, 0, data.Length)) != 0)
        {
            re.Write(data, 0, count);
        }
        byte[] depress = re.ToArray();
        Debug.Log(Encoding.UTF8.GetString(depress));
    }
Esempio n. 12
0
    public static byte[] Compress(byte[] bytesToCompress)
    {
        byte[]       rebyte = null;
        MemoryStream ms     = new MemoryStream();

        GZipOutputStream s = new GZipOutputStream(ms);

        try
        {
            s.Write(bytesToCompress, 0, bytesToCompress.Length);
            s.Flush();
            s.Finish();
        }
        catch (System.Exception ex)
        {
#if UNITY_EDITOR
            Debug.Log(ex);
#endif
        }

        ms.Seek(0, SeekOrigin.Begin);

        rebyte = ms.ToArray();

        s.Close();
        ms.Close();

        s.Dispose();
        ms.Dispose();

        return(rebyte);
    }
Esempio n. 13
0
        public void TestGZip()
        {
            MemoryStream     ms        = new MemoryStream();
            GZipOutputStream outStream = new GZipOutputStream(ms);

            byte[]        buf = new byte[100000];
            System.Random rnd = new Random();
            rnd.NextBytes(buf);

            outStream.Write(buf, 0, buf.Length);
            outStream.Flush();
            outStream.Finish();

            ms.Seek(0, SeekOrigin.Begin);

            GZipInputStream inStream = new GZipInputStream(ms);

            byte[] buf2 = new byte[buf.Length];
            int    pos  = 0;

            while (true)
            {
                int numRead = inStream.Read(buf2, pos, 4096);
                if (numRead <= 0)
                {
                    break;
                }
                pos += numRead;
            }

            for (int i = 0; i < buf.Length; ++i)
            {
                Assert.AreEqual(buf2[i], buf[i]);
            }
        }
Esempio n. 14
0
        /// <summary>
        /// 压缩数据。
        /// </summary>
        /// <param name="bytes">要压缩的数据。</param>
        /// <returns>压缩后的数据。</returns>
        public byte[] Compress(byte[] bytes)
        {
            if (bytes == null || bytes.Length <= 0)
            {
                return(bytes);
            }

            MemoryStream memoryStream = null;

            try
            {
                memoryStream = new MemoryStream();
                using (GZipOutputStream gZipOutputStream = new GZipOutputStream(memoryStream))
                {
                    gZipOutputStream.Write(bytes, 0, bytes.Length);
                }

                return(memoryStream.ToArray());
            }
            finally
            {
                if (memoryStream != null)
                {
                    memoryStream.Dispose();
                    memoryStream = null;
                }
            }
        }
Esempio n. 15
0
 /// <summary>
 /// 压缩字节流数据
 /// <para>注意:</para>
 /// <para>要压缩的字节流数据如果过小则有可能会起到反效果</para>
 /// </summary>
 /// <param name="fromBytes">要压缩的字节流数据</param>
 /// <returns></returns>
 public static byte[] Compress(this byte[] fromBytes)
 {
     //初始化返回值
     byte[] result = fromBytes;
     try
     {
         //声明一个内存流,在内存中压缩
         using (MemoryStream resultStream = new MemoryStream())
         {
             //声明一个GZip输出压缩流
             using (GZipOutputStream gZip = new GZipOutputStream(resultStream))
             {
                 //设置压缩等级为6级(等级越高效果越好)
                 gZip.SetLevel(6);
                 //将压缩好的数据输出到内存流中
                 gZip.Write(fromBytes, 0, fromBytes.Length);
             }
             result = resultStream.ToArray();
         }
     }catch (Exception ex)
     {
         //如果发生异常就认为压缩失败,返回原字节流数据
         LogUtil.WriteException(ex.ToString());
     }
     return(result);
 }
Esempio n. 16
0
        ///--------------------------------------------------------------------------------------------------------
        ///
        public bool SetPassword(string pwd)
        {
            string hdmasterkeyid = QtumHandler.GetHDMasterKeyId();

            if (string.IsNullOrEmpty(hdmasterkeyid))
            {
                Logger.Log("퀀텀 지갑의 구동 상태를 확인 해 주세요.");
                return(false);
            }

            try
            {
                byte[] pwdBytes = Encoding.UTF8.GetBytes(Encrypt(pwd, Encrypt(hdmasterkeyid, Config.RPCPassword)));

                using (FileStream fs = File.Open(passwordFile, FileMode.Create))
                {
                    using (GZipOutputStream gzs = new GZipOutputStream(fs))
                    {
                        using (MemoryStream c = new MemoryStream())
                        {
                            gzs.Write(pwdBytes, 0, pwdBytes.Length);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.Log(e.ToString());
                return(false);
            }

            return(true);
        }
Esempio n. 17
0
        public void OriginalFilename()
        {
            var content = "FileContents";


            using var ms = new MemoryStream();
            using (var outStream = new GZipOutputStream(ms)
            {
                IsStreamOwner = false
            })
            {
                outStream.FileName = "/path/to/file.ext";

                var writeBuffer = Encoding.ASCII.GetBytes(content);
                outStream.Write(writeBuffer, 0, writeBuffer.Length);
                outStream.Flush();
                outStream.Finish();
            }

            ms.Seek(0, SeekOrigin.Begin);

            using (var inStream = new GZipInputStream(ms))
            {
                var readBuffer = new byte[content.Length];
                inStream.Read(readBuffer, 0, readBuffer.Length);
                Assert.AreEqual(content, Encoding.ASCII.GetString(readBuffer));
                Assert.AreEqual("file.ext", inStream.GetFilename());
            }
        }
Esempio n. 18
0
        public TcpRawMessage Compress(CompressionLevel compressionLevel)
        {
            CheckDisposed();
            TcpRawMessage compressedMessage = new TcpRawMessage(this.memoryStreamPool, (int)this.stream.Length);

            compressedMessage.Flags = this.Flags;
            this.stream.Position    = 0;

            byte[] buffer = null;
            try
            {
                buffer = ArrayPool <byte> .Shared.Rent(BUFFER_SIZE);

                using (GZipOutputStream gzip = new GZipOutputStream(compressedMessage.stream, BUFFER_SIZE))
                {
                    gzip.SetLevel(6);
                    gzip.IsStreamOwner = false;
                    int readBytes;
                    while ((readBytes = this.stream.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        gzip.Write(buffer, 0, readBytes);
                    }
                }
            }
            finally
            {
                if (buffer != null)
                {
                    ArrayPool <byte> .Shared.Return(buffer);
                }
            }

            compressedMessage.Position = 0;
            return(compressedMessage);
        }
Esempio n. 19
0
        public byte[] Compress(byte[] buffer, long index, long count)
        {
            byte[]           arrBuffer = null;
            MemoryStream     ms        = new MemoryStream();
            GZipOutputStream objGzip   = new GZipOutputStream(ms);

            #region copy
            //const int BUFFER_SIZE = 1024 * 10;
            //byte[] arrBuffer = new byte[BUFFER_SIZE];
            //int nGetedCount = 0;
            //do
            //{
            //    nGetedCount = ms.Read(arrBuffer, 0, BUFFER_SIZE);
            //    objGzip.Write(arrBuffer, 0, nGetedCount);
            //} while (nGetedCount > 0);
            #endregion
            objGzip.Write(buffer, 0, buffer.Length);
            //objGzip.SetLevel(level);
            objGzip.Finish();
            arrBuffer = ms.ToArray();
            ms.Close();
            objGzip.Close();

            return(arrBuffer);
        }
Esempio n. 20
0
        /// <summary>
        /// GZip压缩
        /// </summary>
        /// <param name="data">待压缩数据</param>
        /// <param name="offset">数据起始位置</param>
        /// <param name="len">数据长度</param>
        /// <param name="os">压缩后的数据输出流</param>
        public static void GZipCompress(byte[] data, int offset, int len, Stream os)
        {
            GZipOutputStream gos = new GZipOutputStream(os, 1024 * 4);

            gos.Write(data, offset, len);
            gos.Finish();
        }
Esempio n. 21
0
 /// <summary>
 /// 压缩字节数组
 /// </summary>
 /// <param name="data">待压缩的字节数组</param>
 /// <param name="isClearData">压缩完成后,是否清除待压缩字节数组里面的内容</param>
 /// <returns>已压缩的字节数组</returns>
 public byte[] GZipCompress(byte[] data, bool isClearData = true)
 {
     byte[] bytes = null;
     try
     {
         using (MemoryStream o = new MemoryStream())
         {
             using (Stream s = new GZipOutputStream(o))
             {
                 s.Write(data, 0, data.Length);
                 s.Flush();
             }
             bytes = o.ToArray();
         }
     }
     catch (SharpZipBaseException)
     {
     }
     catch (IndexOutOfRangeException)
     {
     }
     if (isClearData)
     {
         Array.Clear(data, 0, data.Length);
     }
     return(bytes);
 }
Esempio n. 22
0
        public static byte[] CtorErrMsg(string msg, NameValueCollection requestParam)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                //包总长度
                int  len = 0;
                long pos = 0;
                //包总长度,占位
                WriteValue(ms, len);
                int actionid = Convert.ToInt32(requestParam["actionid"]);
                //StatusCode
                WriteValue(ms, 10001);
                //msgid
                WriteValue(ms, Convert.ToInt32(requestParam["msgid"]));
                WriteValue(ms, msg);
                WriteValue(ms, actionid);
                WriteValue(ms, "st");
                //playerdata
                WriteValue(ms, 0);
                //固定0
                WriteValue(ms, 0);
                ms.Seek(pos, SeekOrigin.Begin);
                WriteValue(ms, (int)ms.Length);

                using (var gms = new MemoryStream())
                    using (var gzs = new GZipOutputStream(gms))
                    {
                        gzs.Write(ms.GetBuffer(), 0, (int)ms.Length);
                        gzs.Flush();
                        gzs.Close();
                        return(gms.ToArray());
                    }
            }
        }
        private readonly byte[] m_BytesCache = new byte[0x10000];   //十六进行表示,4096字节缓存

        /// <summary>
        /// 压缩数据
        /// </summary>
        /// <param name="bytes">要压缩的二进制流数据</param>
        /// <param name="offset">要压缩的数据的二进制流的偏移</param>
        /// <param name="length">要压缩的数据的二进制流的长度</param>
        /// <param name="compressedStream">压缩后的数据的二进制流</param>
        /// <returns>是否压缩数据成功</returns>
        public bool Compress(byte[] bytes, int offset, int length, Stream compressedStream)
        {
            if (bytes == null || offset < 0 || length > bytes.Length || compressedStream == null)
            {
                Debug.LogError("压缩数据失败......");
                return(false);
            }

            try
            {
                //压缩到内存流中
                using (GZipOutputStream gZipOutputStream = new GZipOutputStream(compressedStream))
                {
                    gZipOutputStream.Write(bytes, offset, length);
                    if (compressedStream.Length >= 8L)
                    {
                        //强制转换5-8字节???
                        long current = compressedStream.Position;
                        compressedStream.Position = 4L;
                        compressedStream.WriteByte(25);
                        compressedStream.WriteByte(134);
                        compressedStream.WriteByte(2);
                        compressedStream.WriteByte(32);
                        compressedStream.Position = current;
                    }
                }
                return(true);
            }
            catch (Exception e)
            {
                Debug.LogError("压缩数据异常 -> " + e.ToString());
                return(false);
            }
        }
Esempio n. 24
0
        public byte[] Compress(string message)
        {
            if (message == null)
            {
                return(null);
            }

            using (var dataStream = new MemoryStream())
                using (var zipStream = new GZipOutputStream(dataStream))
                {
                    zipStream.SetLevel((int)CompressionLevel);
                    var rawBytes = Encoding.UTF8.GetBytes(message);

                    zipStream.Write(rawBytes, 0, rawBytes.Length);

                    zipStream.Flush();
                    zipStream.Finish();

                    var compressedBytes = new byte[dataStream.Length];
                    dataStream.Seek(0, SeekOrigin.Begin);
                    dataStream.Read(compressedBytes, 0, compressedBytes.Length);

                    return(compressedBytes);
                }
        }
Esempio n. 25
0
        public static byte[] GZip(byte[] input, int size, out int length)
        {
            if (size == 0)
            {
                var memory = new MemoryStream();
                deflater.Reset();
                using (var stream = new GZipOutputStream(memory, deflater, 4096, deflaterBuffer))
                {
                    stream.Write(input, 0, input.Length);
                }

                var array = memory.ToArray();
                length = array.Length;
                return(array);
            }
            else
            {
                if (size > decompressBuffer.Length)
                {
                    decompressBuffer = new byte[size];
                }

                inflater.Reset();
                using (var stream = new GZipInputStream(new MemoryStream(input), inflater, 4096, inflaterBuffer))
                {
                    stream.Read(decompressBuffer, 0, size);
                }

                length = size;
                return(decompressBuffer);
            }
        }
Esempio n. 26
0
        // write manifest & checksum of manifest
        private static void WriteManifest(PackageBuildInfo buildInfo, Manifest manifest)
        {
            var json                 = JsonUtility.ToJson(manifest);
            var bytes                = Encoding.UTF8.GetBytes(json);
            var manifestRawPath      = Path.Combine(buildInfo.packagePath, Manifest.ManifestFileName + ".json");
            var manifestChecksumPath = Path.Combine(buildInfo.packagePath, Manifest.ChecksumFileName);

            byte[] zData;
            using (var zStream = new MemoryStream())
            {
                using (var outputStream = new GZipOutputStream(zStream))
                {
                    outputStream.SetLevel(Deflater.BEST_COMPRESSION);
                    outputStream.Write(bytes, 0, bytes.Length);
                    outputStream.Flush();
                }

                zStream.Flush();
                zData = zStream.ToArray();
            }

            buildInfo.filelist.Add(Manifest.ManifestFileName);
            buildInfo.filelist.Add(Manifest.ManifestFileName + ".json");
            var fileEntry = AsManifestEntry(EncryptData(buildInfo, Manifest.ManifestFileName, zData),
                                            buildInfo.data.chunkSize);
            var fileEntryJson = JsonUtility.ToJson(fileEntry);

            Debug.LogFormat("write manifest: {0}", fileEntryJson);
            File.WriteAllBytes(manifestRawPath, bytes);
            File.WriteAllText(manifestChecksumPath, fileEntryJson);
        }
Esempio n. 27
0
 /// <summary>
 /// 圧縮します
 /// </summary>
 private static void CompressImpl(Stream stream, byte[] rawData)
 {
     using (var gzipOutputStream = new GZipOutputStream(stream))
     {
         gzipOutputStream.Write(rawData, 0, rawData.Length);
     }
 }
Esempio n. 28
0
        /// <summary>
        /// 压缩数据。
        /// </summary>
        /// <param name="stream">要压缩的数据的二进制流。</param>
        /// <param name="compressedStream">压缩后的数据的二进制流。</param>
        /// <returns>是否压缩数据成功。</returns>
        public bool Compress(Stream stream, Stream compressedStream)
        {
            if (stream == null)
            {
                return(false);
            }

            if (compressedStream == null)
            {
                return(false);
            }

            try
            {
                GZipOutputStream gZipOutputStream = new GZipOutputStream(compressedStream);
                int bytesRead = 0;
                while ((bytesRead = stream.Read(m_CachedBytes, 0, CachedBytesLength)) > 0)
                {
                    gZipOutputStream.Write(m_CachedBytes, 0, bytesRead);
                }

                gZipOutputStream.Finish();
                ProcessHeader(compressedStream);
                return(true);
            }
            catch
            {
                return(false);
            }
            finally
            {
                Array.Clear(m_CachedBytes, 0, CachedBytesLength);
            }
        }
Esempio n. 29
0
        /// <summary>
        /// 压缩数据。
        /// </summary>
        /// <param name="bytes">要压缩的数据的二进制流。</param>
        /// <param name="offset">要压缩的数据的二进制流的偏移。</param>
        /// <param name="length">要压缩的数据的二进制流的长度。</param>
        /// <param name="compressedStream">压缩后的数据的二进制流。</param>
        /// <returns>是否压缩数据成功。</returns>
        public bool Compress(byte[] bytes, int offset, int length, Stream compressedStream)
        {
            if (bytes == null)
            {
                return(false);
            }

            if (offset < 0 || length < 0 || offset + length > bytes.Length)
            {
                return(false);
            }

            if (compressedStream == null)
            {
                return(false);
            }

            try
            {
                GZipOutputStream gZipOutputStream = new GZipOutputStream(compressedStream);
                gZipOutputStream.Write(bytes, offset, length);
                gZipOutputStream.Finish();
                ProcessHeader(compressedStream);
                return(true);
            }
            catch
            {
                return(false);
            }
        }
Esempio n. 30
0
        public static string EncodeBase64(byte[] input)
        {
            using (var compressedStream = new MemoryStream())
            {
                // mono requires an installed zlib library for GZipStream to work :(
                // using (Stream csStream = new GZipStream(compressedStream, CompressionMode.Compress))
                using (Stream csStream = new GZipOutputStream(compressedStream))
                {
                    csStream.Write(input, 0, input.Length);
                }

                string returnValue = Convert.ToBase64String(compressedStream.ToArray());

                // Added the following to fix issue #429:  Base64 content can include the slash character '/', and
                // if it happens to have two of them contiguously, it forms a comment in the persistence file and
                // truncates the value.  So change them to a different character to protect the file.
                // The comma ',' char is not used by base64 so it's a safe alternative to use as we'll be able to
                // swap all of the commas back to slashes on reading, knowing that commas can only appear as the
                // result of this swap on writing:
                returnValue = returnValue.Replace('/', ',');

                //SafeHouse.Logger.SuperVerbose("About to store the following Base64 string:\n" + returnValue);

                return(returnValue);
            }
        }
Esempio n. 31
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void Compress(HttpRequest request, HttpResponse response)
        {
            Encoding encoding = Encoding.GetEncoding("windows-1252");
            string enc, cacheFile = null, cacheKey = null, content = "";
            StringWriter writer = new StringWriter();
            byte[] buff = new byte[1024];
            GZipOutputStream gzipStream;
            bool supportsGzip;

            // Set response headers
            response.ContentType = "text/javascript";
            response.Charset = this.charset;
            response.Buffer = false;

            // Setup cache
            response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset));

            // Check if it supports gzip
            enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower();
            supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null;
            enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip";

            // Setup cache info
            if (this.diskCache) {
                cacheKey = "";

                foreach (JSCompressItem item in this.items) {
                    // Get last mod
                    if (item.Type == JSItemType.File) {
                        DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value));

                        if (fileMod > this.lastUpdate)
                            this.lastUpdate = fileMod;
                    }

                    cacheKey += item.Value;
                }

                cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey);

                if (this.gzipCompress)
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz");
                else
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".js");
            }

            // Use cached file disk cache
            if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                response.WriteFile(cacheFile);
                return;
            }

            foreach (JSCompressItem item in this.items) {
                if (item.Type == JSItemType.File) {
                    if (!File.Exists(request.MapPath(item.Value))) {
                        writer.WriteLine("alert('Could not load file: " + StringUtils.Escape(item.Value) + "');");
                        continue;
                    }

                    StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8);

                    if (item.RemoveWhiteSpace) {
                        JavaScriptMinifier jsMin = new JavaScriptMinifier(reader, writer);
                        jsMin.Compress();
                    } else {
                        writer.Write('\n');
                        writer.Write(reader.ReadToEnd());
                        writer.Write(";\n");
                    }

                    reader.Close();
                } else {
                    if (item.RemoveWhiteSpace) {
                        JavaScriptMinifier jsMin = new JavaScriptMinifier(new StringReader(item.Value), writer);
                        jsMin.Compress();
                    } else {
                        writer.Write('\n');
                        writer.Write(item.Value);
                        writer.Write('\n');
                    }
                }
            }

            content = writer.ToString();

            // Generate GZIP'd content
            if (supportsGzip) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                if (this.diskCache && cacheKey != null) {
                    try {
                        // Gzip compress
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(File.Create(cacheFile));
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        } else {
                            StreamWriter sw = File.CreateText(cacheFile);
                            sw.Write(content);
                            sw.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        }

                        // Write to stream
                        response.WriteFile(cacheFile);
                    } catch (Exception) {
                        content = "/* Not cached */" + content;
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(response.OutputStream);
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();
                        } else {
                            response.Write(content);
                        }
                    }
                } else {
                    content = "/* Not cached */" + content;
                    gzipStream = new GZipOutputStream(response.OutputStream);
                    buff = encoding.GetBytes(content.ToCharArray());
                    gzipStream.Write(buff, 0, buff.Length);
                    gzipStream.Close();
                }
            } else {
                content = "/* Not cached */" + content;
                response.Write(content);
            }
        }
Esempio n. 32
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="response"></param>
        public void Compress(HttpRequest request, HttpResponse response)
        {
            Encoding encoding = Encoding.GetEncoding("windows-1252");
            string enc, cacheFile = null, cacheKey = null, content = "";
            StringWriter writer = new StringWriter();
            byte[] buff = new byte[1024];
            GZipOutputStream gzipStream;
            bool supportsGzip;

            // Set response headers
            response.ContentType = "text/css";
            response.Charset = this.charset;
            response.Buffer = false;

            // Setup cache
            response.Cache.SetExpires(DateTime.Now.AddSeconds(this.ExpiresOffset));

            // Check if it supports gzip
            enc = Regex.Replace("" + request.Headers["Accept-Encoding"], @"\s+", "").ToLower();
            supportsGzip = enc.IndexOf("gzip") != -1 || request.Headers["---------------"] != null;
            enc = enc.IndexOf("x-gzip") != -1 ? "x-gzip" : "gzip";

            // Setup cache info
            if (this.diskCache) {
                cacheKey = "";

                foreach (CSSCompressItem item in this.items) {
                    // Get last mod
                    if (item.Type == CSSItemType.File) {
                        DateTime fileMod = File.GetLastWriteTime(request.MapPath(item.Value));

                        if (fileMod > this.lastUpdate)
                            this.lastUpdate = fileMod;
                    }

                    cacheKey += item.Value;
                }

                cacheKey = this.cacheFileName != null ? this.cacheFileName : MD5(cacheKey);

                if (this.gzipCompress)
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".gz");
                else
                    cacheFile = request.MapPath(this.cacheDir + "/" + cacheKey + ".css");
            }

            // Use cached file disk cache
            if (this.diskCache && supportsGzip && File.Exists(cacheFile) && this.lastUpdate == File.GetLastWriteTime(cacheFile)) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                response.WriteFile(cacheFile);
                return;
            }

            foreach (CSSCompressItem item in this.items) {
                if (item.Type == CSSItemType.File) {
                    StreamReader reader = new StreamReader(File.OpenRead(request.MapPath(item.Value)), System.Text.Encoding.UTF8);
                    string data;

                    if (item.RemoveWhiteSpace)
                        data = this.TrimWhiteSpace(reader.ReadToEnd());
                    else
                        data = reader.ReadToEnd();

                    if (this.convertUrls)
                        data = Regex.Replace(data, "url\\(['\"]?(?!\\/|http)", "$0" + PathUtils.ToUnixPath(Path.GetDirectoryName(item.Value)) + "/");

                    writer.Write(data);

                    reader.Close();
                } else {
                    if (item.RemoveWhiteSpace)
                        writer.Write(this.TrimWhiteSpace(item.Value));
                    else
                        writer.Write(item.Value);
                }
            }

            content = writer.ToString();

            // Generate GZIP'd content
            if (supportsGzip) {
                if (this.gzipCompress)
                    response.AppendHeader("Content-Encoding", enc);

                if (this.diskCache && cacheKey != null) {
                    try {
                        // Gzip compress
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(File.Create(cacheFile));
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        } else {
                            StreamWriter sw = File.CreateText(cacheFile);
                            sw.Write(content);
                            sw.Close();

                            File.SetLastWriteTime(cacheFile, this.lastUpdate);
                        }

                        // Write to stream
                        response.WriteFile(cacheFile);
                    } catch (Exception) {
                        content = "/* Not cached */" + content;
                        if (this.gzipCompress) {
                            gzipStream = new GZipOutputStream(response.OutputStream);
                            buff = encoding.GetBytes(content.ToCharArray());
                            gzipStream.Write(buff, 0, buff.Length);
                            gzipStream.Close();
                        } else {
                            response.Write(content);
                        }
                    }
                } else {
                    content = "/* Not cached */" + content;
                    gzipStream = new GZipOutputStream(response.OutputStream);
                    buff = encoding.GetBytes(content.ToCharArray());
                    gzipStream.Write(buff, 0, buff.Length);
                    gzipStream.Close();
                }
            } else {
                content = "/* Not cached */" + content;
                response.Write(content);
            }
        }