public override bool Execute()
        {
            if (!ValidateCompilationLevel())
                return false;

            var errorCount = 0;
            var options = new CompilerOptions();
            CompilationLevel compilationLevel = null;
            switch (CompilationLevel)
            {
                case "WHITESPACE_ONLY":
                    compilationLevel = com.google.javascript.jscomp.CompilationLevel.WHITESPACE_ONLY;
                    break;
                case "SIMPLE_OPTIMIZATIONS":
                    compilationLevel = com.google.javascript.jscomp.CompilationLevel.SIMPLE_OPTIMIZATIONS;
                    break;
                case "ADVANCED_OPTIMIZATIONS":
                    compilationLevel = com.google.javascript.jscomp.CompilationLevel.ADVANCED_OPTIMIZATIONS;
                    break;
            }
            compilationLevel.setOptionsForCompilationLevel(options);

            Log.LogMessage(String.Format("Found {0} javascript files to compile using the Closure compiler", SourceFiles.Count()));
            foreach (var t in SourceFiles)
            {
                Log.LogMessage(String.Concat("Compiling JS file: ", t.ItemSpec), null);
                var compiler = new Compiler();
                var dummy = JSSourceFile.fromCode("externs.js", "");
                var source = JSSourceFile.fromFile(t.ItemSpec);
                var thisErrorCount = 0;

                var result = compiler.compile(dummy, source, options);

                if (!result.success && IsShowErrors)
                {
                    foreach (var error in result.errors)
                    {
                        LogError(t.ItemSpec, error.lineNumber, error.getCharno(), error.description);
                        errorCount++;
                        thisErrorCount++;
                    }
                }
                if (IsShowWarnings)
                {
                    foreach (var warning in result.warnings)
                    {
                        LogWarning(t.ItemSpec, warning.lineNumber, warning.getCharno(), warning.description);
                    }
                }

                if (!MaybeWriteOutput(t.ItemSpec, compiler.toSource()))
                    return false;
            }
            return errorCount == 0;
        }
        public CompressorResults Compress(string js, string filename, ClosureCompilerJsCompressionOptions packagerOptions)
        {
            var compressorResult = new CompressorResults();
            var options = new CompilerOptions();
            CompilationLevel compilationLevel;
            switch (packagerOptions.CompressionLevel)
            {
                case ClosureCompressionLevel.SimpleOptimizations:
                    compilationLevel = CompilationLevel.SIMPLE_OPTIMIZATIONS;
                    break;
                case ClosureCompressionLevel.AdvancedOptimizations:
                    compilationLevel = CompilationLevel.ADVANCED_OPTIMIZATIONS;
                    break;
                default:
                    compilationLevel = CompilationLevel.WHITESPACE_ONLY;
                    break;
            }
            compilationLevel.setOptionsForCompilationLevel(options);

            var compiler = new Compiler();
            var dummy = JSSourceFile.fromCode("externs.js", "");
            var source = JSSourceFile.fromCode(filename, js);

            var result = compiler.compile(dummy, source, options);

            if (!result.success && packagerOptions.FailOnCompilerErrors)
            {
                if (packagerOptions.FailOnCompilerErrors)
                {
                    throw new ClosureCompilerErrorsException(result.warnings);
                }
                compressorResult.Errors = (from error in result.errors
                                           select new PackagerResultDetail { Line = error.lineNumber, Char = error.getCharno(), Description = error.description, Filename = error.sourceName }).ToList();
            }
            if (result.warnings.Length > 0)
            {
                if (packagerOptions.FailOnCompilerWarnings)
                {
                    throw new ClosureCompilerWarningsException(result.warnings);
                }
                compressorResult.Warnings = (from warning in result.warnings
                                            select new PackagerResultDetail { Line = warning.lineNumber, Char = warning.getCharno(), Description = warning.description, Filename = warning.sourceName }).ToList();
            }

            compressorResult.Output = compiler.toSource();
            return compressorResult;
        }
Пример #3
0
        // Конструктор класса. Ему нужно передавать принятого клиента от TcpListener
        public HttpClient(TcpClient Client)
        {
            // Объявим строку, в которой будет хранится запрос клиента
            string Request = "";
            // Буфер для хранения принятых от клиента данных
            byte[] Buffer = new byte[1024];
            // Переменная для хранения количества байт, принятых от клиента
            int Count;
            // Читаем из потока клиента до тех пор, пока от него поступают данные
            while ((Count = Client.GetStream().Read(Buffer, 0, Buffer.Length)) > 0)
            {
                // Преобразуем эти данные в строку и добавим ее к переменной Request
                Request += Encoding.ASCII.GetString(Buffer, 0, Count);
                // Запрос должен обрываться последовательностью \r\n\r\n
                // Либо обрываем прием данных сами, если длина строки Request превышает 4 килобайта
                // Нам не нужно получать данные из POST-запроса (и т. п.), а обычный запрос
                // по идее не должен быть больше 4 килобайт
                if (Request.IndexOf("\r\n\r\n") >= 0 || Request.Length > 4096)
                {
                    break;
                }
            }

            string basePath = "../../";

            // Парсим строку запроса с использованием регулярных выражений
            // При этом отсекаем все переменные GET-запроса
            Match ReqMatch = Regex.Match(Request, @"^\w+\s+([^\s\?]+)[^\s]*\s+HTTP/.*|");

            // Если запрос не удался
            if (ReqMatch == Match.Empty)
            {
                // Передаем клиенту ошибку 400 - неверный запрос
                SendError(Client, 400);
                return;
            }

            // Получаем строку запроса
            string RequestUri = ReqMatch.Groups[1].Value;

            // Приводим ее к изначальному виду, преобразуя экранированные символы
            // Например, "%20" -> " "
            RequestUri = Uri.UnescapeDataString(RequestUri);

            // Если в строке содержится двоеточие, передадим ошибку 400
            // Это нужно для защиты от URL типа http://example.com/../../file.txt
            if (RequestUri.IndexOf("..") >= 0)
            {
                SendError(Client, 400);
                return;
            }

            string ContentType = "";

            // Если строка запроса оканчивается на "/", то добавим к ней index.html
            if (RequestUri.EndsWith(".js"))
            {
                basePath += "Client/";
                string dirPath = basePath + RequestUri.Split('.')[0];
                if (!Directory.Exists(dirPath))
                {
                    SendError(Client, 404);
                    return;
                }
                DirectoryInfo dir = new DirectoryInfo(dirPath);
                ContentType = "text/javascript";
                // Посылаем заголовки
                string Headers = "HTTP/1.1 200 OK\nContent-Type: " + ContentType + "\n\n";
                byte[] HeadersBuffer = Encoding.ASCII.GetBytes(Headers);
                Client.GetStream().Write(HeadersBuffer, 0, HeadersBuffer.Length);

                string totaljs = "";
                List<string> fileList = new List<string>();
                ScanDir(dir, "*.js",ref fileList);

                foreach (var file in fileList)
                {
                    if (ConfigurationManager.AppSettings["enable closure compiler"] == "false")
                    {
                        FileStream FS = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
                        while (FS.Position < FS.Length)
                        {
                            // Читаем данные из файла
                            Count = FS.Read(Buffer, 0, Buffer.Length);
                            // И передаем их клиенту
                            Client.GetStream().Write(Buffer, 0, Count);
                        }
                        FS.Close();
                    }
                    else
                    {
                        Compiler compiler = new Compiler();
                        CompilerOptions options = new CompilerOptions();

                        var dummy = JSSourceFile.fromCode(dir.Name + ".wcjs", "");
                        var source = JSSourceFile.fromFile(file);
                        var result = compiler.compile(dummy, source, options);
                        String str = compiler.toSource();
                        totaljs += str;
                    }
                }

            }
            else if (RequestUri.EndsWith(".css"))
            {
                basePath += "Client/";
                string dirPath = basePath + RequestUri.Split('.')[0];
                if (!Directory.Exists(dirPath))
                {
                    SendError(Client, 404);
                    return;
                }
                DirectoryInfo dir = new DirectoryInfo(dirPath + "/Style");
                ContentType = "text/stylesheet";
                // Посылаем заголовки
                string Headers = "HTTP/1.1 200 OK\nContent-Type: " + ContentType + "\n\n";
                byte[] HeadersBuffer = Encoding.ASCII.GetBytes(Headers);
                Client.GetStream().Write(HeadersBuffer, 0, HeadersBuffer.Length);

                string totaljs = "";
                List<string> fileList = new List<string>();
                ScanDir(dir, "*.css", ref fileList);
                ScanDir(dir, "*.less", ref fileList);

                foreach (var file in fileList)
                {
                    if (file.EndsWith(".less"))
                    {
                        string fileText = "";
                        fileText = File.ReadAllText(file);
                        fileText = Less.Parse(fileText);
                        byte[] b1 = Encoding.UTF8.GetBytes (fileText);
                        Client.GetStream().Write(b1, 0, b1.Length);
                    }
                    else
                    {
                        FileStream FS = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read);
                        while (FS.Position < FS.Length)
                        {
                            // Читаем данные из файла
                            Count = FS.Read(Buffer, 0, Buffer.Length);
                            // И передаем их клиенту
                            Client.GetStream().Write(Buffer, 0, Count);
                        }
                        FS.Close();
                    }
                }
            }
            else
            {
                if (RequestUri.EndsWith("/"))
                {
                    RequestUri = "index.html";
                }

                string FilePath = basePath + RequestUri;

                // Если в папке www не существует данного файла, посылаем ошибку 404
                if (!File.Exists(FilePath))
                {
                    SendError(Client, 404);
                    return;
                }

                // Получаем расширение файла из строки запроса
                string Extension = RequestUri.Substring(RequestUri.LastIndexOf('.'));

                // Тип содержимого

                // Пытаемся определить тип содержимого по расширению файла
                switch (Extension)
                {
                    case ".htm":
                    case ".html":
                        ContentType = "text/html";
                        break;
                    case ".css":
                        ContentType = "text/stylesheet";
                        break;
                    case ".js":
                        ContentType = "text/javascript";
                        break;
                    case ".jpg":
                        ContentType = "image/jpeg";
                        break;
                    case ".jpeg":
                    case ".png":
                    case ".gif":
                        ContentType = "image/" + Extension.Substring(1);
                        break;
                    default:
                        if (Extension.Length > 1)
                        {
                            ContentType = "application/" + Extension.Substring(1);
                        }
                        else
                        {
                            ContentType = "application/unknown";
                        }
                        break;
                }

                // Открываем файл, страхуясь на случай ошибки
                FileStream FS;
                try
                {
                    FS = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                }
                catch (Exception)
                {
                    // Если случилась ошибка, посылаем клиенту ошибку 500
                    SendError(Client, 500);
                    return;
                }
                // Посылаем заголовки
                string Headers = "HTTP/1.1 200 OK\nContent-Type: " + ContentType + "\nContent-Length: " + FS.Length + "\n\n";
                byte[] HeadersBuffer = Encoding.ASCII.GetBytes(Headers);
                Client.GetStream().Write(HeadersBuffer, 0, HeadersBuffer.Length);

                // Пока не достигнут конец файла
                while (FS.Position < FS.Length)
                {
                    // Читаем данные из файла
                    Count = FS.Read(Buffer, 0, Buffer.Length);
                    // И передаем их клиенту
                    Client.GetStream().Write(Buffer, 0, Count);
                }

                // Закроем файл и соединение
                FS.Close();
            }

            Client.Close();
            Core.Logger.Log.Info(RequestUri);
        }
Пример #4
0
        protected void DoJs(string modulePath, string moduleName)
        {
            var jsFiles = new List<string>();
            ScanDir(new DirectoryInfo(modulePath),"*.js",ref jsFiles);
            FileStream file = new FileStream(_pathBuild+"/"+moduleName+".js",FileMode.Create);

            // Буфер для хранения принятых от клиента данных
            byte[] buffer = new byte[1024];
            // Переменная для хранения количества байт, принятых от клиента
            int Count;

            foreach (string jsFile in jsFiles )
            {
                Compiler compiler = new Compiler();
                CompilerOptions options = new CompilerOptions();
                //options.removeDeadCode = true;
                //options.removeUnusedLocalVars = true;
                //options.inlineFunctions = true;
                Set set = new HashSet();
                set.add("console");
                options.setStripTypes(set);

                var dummy = JSSourceFile.fromCode(_pathBuild+"/tmp" + ".wcjs", "");
                var source = JSSourceFile.fromFile(jsFile);
                var result = compiler.compile(dummy, source, options);
                String str = compiler.toSource();
                //totaljs += str;
                //Console.WriteLine(str);

                buffer = Encoding.UTF8.GetBytes(str);
                file.Write(buffer,0,buffer.Length);
                Console.WriteLine(jsFile);
            }
            file.Close();
        }