コード例 #1
0
ファイル: IirFilter.cs プロジェクト: Faham/emophiz
        /// <summary>
        /// Creates an IIR filter from zeros and poles.  The zeros and poles must be made up of real and complex conjugate pairs.
        /// </summary>
        public IirFilter(ZeroPoleGain zeroPoleGain)
        {
            Debug.Assert(zeroPoleGain.Zeros.Length == zeroPoleGain.Poles.Length);

            this.zeroPoleGain = zeroPoleGain;

            transferFunction = FilterModifiers.ConvertSosToTransferFunction(sosGain);
            sosGain = FilterModifiers.ConvertZeroPoleToSosFilter(zeroPoleGain);

            this.sections = new FilterChain(sosGain.Sections);
            this.order = sosGain.Sections.Sum(x => x.Order);

            //Check whether this is linear phase
            double[] b = transferFunction.B;
            isLinearPhase = true;
            for (int i = 0; i < b.Length; i++)
            {
                if (b[i] != b[b.Length - 1 - i] && b[i] != -b[b.Length - 1 - i])
                {
                    isLinearPhase = false;
                    break;
                }
            }

            return;
        }
コード例 #2
0
ファイル: FilterChainTests.cs プロジェクト: ldvip/Core
        public void TestFilterChainT1()
        {
            var chain = new FilterChain <string>();

            var data   = "123";
            var isCall = false;

            chain.Add((inData, next) =>
            {
                if (inData == data)
                {
                    isCall = true;
                }
                next(inData);
            });
            chain.Add((in1Data, next) =>
            {
                next(in1Data);
            });
            var completeCall = false;

            chain.Do(data, (in1) =>
            {
                completeCall = true;
            });

            Assert.AreEqual(2, chain.FilterList.Length);
            Assert.AreEqual(true, isCall);
            Assert.AreEqual(true, completeCall);
        }
コード例 #3
0
ファイル: FilterBase.cs プロジェクト: harmstyler/Ellis
        public static FilterBase GetFilter(XmlNode settingsNode, FilterChain parentChain)
        {
            if (settingsNode.Attributes["name"] == null)
            {
                throw new Exception(String.Format("Filter \"{0}\" in chain \"{1}\" has no \"name\" attribute", settingsNode.Name, parentChain.Name));
            }

            FilterBase thisFilter = (FilterBase)Utils.CreateObject("Blend.Ellis.Filters." + Utils.ConvertToMixedCase(settingsNode.Name));

            //If we're still null, then this filter doesn't exist.  Life is hard that way.  People are mean, dogs bite, and cheeseburgers make you fat...
            if (thisFilter == null)
            {
                throw new Exception(String.Format("Cannot load filter \"{0}\" in chain \"{1}\"", settingsNode.Name));
            }

            //Load up its settings
            SettingsIndex settings = new SettingsIndex();
            foreach (XmlAttribute attribute in settingsNode.Attributes)
            {
                settings.Add(attribute.Name, attribute.Value);
            }
            thisFilter.Settings = settings;

            thisFilter.Name = settingsNode.Attributes["name"].Value;

            //Run the initialization
            thisFilter.Initialize();

            return thisFilter;
        }
コード例 #4
0
ファイル: FilterChainTests.cs プロジェクト: ldvip/Core
        public void TestNullThen()
        {
            var chain1 = new FilterChain <string>();

            chain1.Add((str, next) => { });
            chain1.Add((str, next) => { });

            ExceptionAssert.DoesNotThrow(() =>
            {
                chain1.Do(null);
            });

            var chain2 = new FilterChain <string, string>();

            chain2.Add((str, str1, next) => { });
            chain2.Add((str, str1, next) => { });

            ExceptionAssert.DoesNotThrow(() =>
            {
                chain2.Do(null, null);
            });

            var chain3 = new FilterChain <string, string, string>();

            chain3.Add((str, str1, str2, next) => { });
            chain3.Add((str, str1, str2, next) => { });

            ExceptionAssert.DoesNotThrow(() =>
            {
                chain3.Do(null, null, null);
            });
        }
コード例 #5
0
ファイル: FilterChainTests.cs プロジェクト: ldvip/Core
        public void TestFilterChainT1T2T3()
        {
            var chain = new FilterChain <string, string, string>();

            var data1 = "123";
            var data2 = "222";
            var data3 = "333";

            var isCall = false;

            chain.Add((in1Data, in2Data, in3Data, next) =>
            {
                if (in1Data == data1 && in2Data == data2 && in3Data == data3)
                {
                    isCall = true;
                }
                next(in1Data, in2Data, in3Data);
            });

            chain.Add((in1Data, in2Data, in3Data, next) =>
            {
                next(in1Data, in2Data, in3Data);
            });

            var completeCall = false;

            chain.Do(data1, data2, data3, (in1, in2, in3) =>
            {
                completeCall = true;
            });

            Assert.AreEqual(2, chain.FilterList.Length);
            Assert.AreEqual(true, isCall);
            Assert.AreEqual(true, completeCall);
        }
コード例 #6
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: @Override public void doFilter(final ServletRequest req, final ServletResponse resp, FilterChain chain) throws java.io.IOException, ServletException
//JAVA TO C# CONVERTER WARNING: 'final' parameters are not available in .NET:
	  public override void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
	  {

//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final boolean isContentTypeJson = CONTENT_TYPE_JSON_PATTERN.matcher(req.getContentType() == null ? "" : req.getContentType()).find();
		bool isContentTypeJson = CONTENT_TYPE_JSON_PATTERN.matcher(req.ContentType == null ? "" : req.ContentType).find();

		if (isContentTypeJson)
		{
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final java.io.PushbackInputStream requestBody = new java.io.PushbackInputStream(req.getInputStream());
		  PushbackInputStream requestBody = new PushbackInputStream(req.InputStream);
		  int firstByte = requestBody.read();
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final boolean isBodyEmpty = firstByte == -1;
		  bool isBodyEmpty = firstByte == -1;
		  requestBody.unread(firstByte);

		  HttpServletRequestWrapper wrappedRequest = new HttpServletRequestWrapperAnonymousInnerClass(this, (HttpServletRequest) req, requestBody, isBodyEmpty);

		  chain.doFilter(wrappedRequest, resp);
		}
		else
		{
		  chain.doFilter(req, resp);
		}
	  }
コード例 #7
0
        /// <summary>
        /// Reads a file filtering its content through the filter chain.
        /// </summary>
        /// <param name="fileName">The file to read.</param>
        /// <param name="filterChain">Chain of filters to apply when reading, or <see langword="null" /> is no filters should be applied.</param>
        /// <param name="inputEncoding">The encoding used to read the file.</param>
        /// <remarks>
        /// If <paramref name="inputEncoding" /> is <see langword="null" />,
        /// then the system's ANSI code page will be used to read the file.
        /// </remarks>
        public static string ReadFile(string fileName, FilterChain filterChain, Encoding inputEncoding)
        {
            string content = null;

            // determine character encoding to use
            Encoding encoding = (inputEncoding != null) ? inputEncoding : Encoding.Default;

            // read file
            using (StreamReader sr = new StreamReader(fileName, encoding, true)) {
                if (filterChain == null || filterChain.Filters.Count == 0)
                {
                    content = sr.ReadToEnd();
                }
                else
                {
                    Filter baseFilter = filterChain.GetBaseFilter(
                        new PhysicalTextReader(sr));

                    StringWriter sw = new StringWriter();
                    while (true)
                    {
                        int character = baseFilter.Read();
                        if (character == -1)
                        {
                            break;
                        }
                        sw.Write((char)character);
                    }
                    content = sw.ToString();
                }
            }

            return(content);
        }
コード例 #8
0
        /// <summary>
        /// Moves a file filtering its content through the filter chain.
        /// </summary>
        /// <param name="sourceFileName">
        /// The file to move.
        /// </param>
        /// <param name="destFileName">
        /// The file to move move to.
        /// </param>
        /// <param name="filterChain">
        /// Chain of filters to apply when moving, or <see langword="null" /> is no
        /// filters should be applied.
        /// </param>
        /// <param name="inputEncoding">
        /// The encoding used to read the soure file.
        /// </param>
        /// <param name="outputEncoding">
        /// The encoding used to write the destination file.
        /// </param>
        public static void MoveFile(
            string sourceFileName,
            string destFileName,
            FilterChain filterChain,
            Encoding inputEncoding,
            Encoding outputEncoding)
        {
            // If the source file does not exist, throw an exception.
            if (!File.Exists(sourceFileName))
            {
                throw new BuildException(
                          String.Format("Cannot move file: Source File {0} does not exist",
                                        sourceFileName));
            }

            // if no filters have been defined, and no input or output encoding
            // is set, we can just use the File.Move method
            if (FilterChain.IsNullOrEmpty(filterChain) &&
                inputEncoding == null && outputEncoding == null)
            {
                File.Move(sourceFileName, destFileName);
            }
            else
            {
                CopyFile(sourceFileName, destFileName, filterChain, inputEncoding, outputEncoding);
                File.Delete(sourceFileName);
            }
        }
コード例 #9
0
        private void LoadFile(FilterChain filterChain)
        {
            string content = null;

            try {
                content = FileUtils.ReadFile(File.FullName, filterChain,
                                             Encoding);
            } catch (IOException ex) {
                throw new BuildException("The properties file could not be read.",
                                         Location, ex);
            }

            PropertyDictionary properties = Project.Properties;

            PropertyTask propertyTask = new PropertyTask();

            propertyTask.Parent  = this;
            propertyTask.Project = Project;

            using (StringReader sr = new StringReader(content)) {
                string line         = sr.ReadLine();
                int    current_line = 0;

                while (line != null)
                {
                    current_line++;

                    // skip empty lines and comments
                    if (String.IsNullOrEmpty(line) || line.StartsWith("#"))
                    {
                        line = sr.ReadLine();
                        continue;
                    }

                    int equals_pos = line.IndexOf('=');
                    if (equals_pos == -1)
                    {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                               "Invalid property defined on line {0}.", current_line),
                                                 Location);
                    }

                    string name  = line.Substring(0, equals_pos).Trim();
                    string value = line.Substring(equals_pos + 1,
                                                  line.Length - equals_pos - 1).Trim();

                    string expandedValue = properties.ExpandProperties(value,
                                                                       Location);

                    propertyTask.PropertyName = name;
                    propertyTask.Value        = expandedValue;
                    propertyTask.Execute();

                    line = sr.ReadLine();
                }
            }
        }
コード例 #10
0
        private IFilter <MediaInstance> ConstructFilter(SearchMediaData searchMediaData, IGraph <Tag> tagGraph)
        {
            var tagFilter          = new TagFilter(searchMediaData.IncludedTags, searchMediaData.ExcludedTags, tagGraph);
            var timeRangeFilter    = new TimeRangeFilter(searchMediaData.TimeRangeStart, searchMediaData.TimeRangeEnd);
            var privateMediaFilter = new PrivateMediaFilter(searchMediaData.UserId);
            var filterChain        = new FilterChain <MediaInstance>(tagFilter, timeRangeFilter, privateMediaFilter);

            return(filterChain);
        }
コード例 #11
0
ファイル: Apu.cs プロジェクト: wensioness/EmuNes
        public Apu()
        {
            Pulse1   = new PulseGenerator(1);
            Pulse2   = new PulseGenerator(2);
            Triangle = new TriangleGenerator();
            Noise    = new NoiseGenerator();
            Dmc      = new DmcGenerator();

            filterChain = new FilterChain();
        }
コード例 #12
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="sourceFile"></param>
        /// <param name="targetFile"></param>
        /// <param name="filterChain"></param>
        public void ProcessFile(string sourceFile, string targetFile, FilterChain filterChain)
        {
            if (File.Exists(sourceFile))
            {
                //--------------------------------------------------------------------------
                //    Get handler for the file type
                //--------------------------------------------------------------------------

                IColorFileHandler <string> schemeHandler;
                IColorFileHandler <Bitmap> bitmapHandler;
                try {
                    schemeHandler = _schemeHandlerRegister.GetHandlerForFile(sourceFile);
                    bitmapHandler = _bitmapHandlerRegister.GetHandlerForFile(sourceFile);
                } catch (Exception e) {
                    Console.WriteLine($"Multiple file processing units found for: {sourceFile}");
                    return;
                }

                if (schemeHandler == null && bitmapHandler == null)
                {
                    Console.WriteLine($"{sourceFile} is not supported color scheme format");
                    return;
                }

                if (schemeHandler != null && bitmapHandler != null)
                {
                    Console.WriteLine($"Multiple file processing units found for: {sourceFile}");
                    return;
                }

                //--------------------------------------------------------------------------
                //    Process file
                //--------------------------------------------------------------------------

                if (bitmapHandler != null)
                {
                    var processor = new ColorFileProcessor <Bitmap>(bitmapHandler);
                    processor.ProcessFile(sourceFile, targetFile, filterChain);
                }
                else if (schemeHandler != null)
                {
                    var processor = new ColorFileProcessor <string>(schemeHandler);
                    processor.ProcessFile(sourceFile, targetFile, filterChain);
                }
                else
                {
                    Console.WriteLine($"{sourceFile} is not supported color scheme format");
                    return;
                }
            }
            else
            {
                Console.Error.WriteLine(sourceFile + " does not exist");
            }
        }
コード例 #13
0
        public static LiquidExpressionResult Eval(
            LiquidExpression expression,
            IEnumerable <Option <ILiquidValue> > leaves,
            ITemplateContext templateContext)
        {
            // calculate the first part of the expression
            var objResult = expression.Expression == null?
                            LiquidExpressionResult.Success(new None <ILiquidValue>()) :
                                expression.Expression.Eval(templateContext, leaves);

            if (objResult.IsError)
            {
                return(objResult);
            }

            // Compose a chain of filters, making sure type-casting
            // is done between them.
            //IEnumerable<Tuple<FilterSymbol, IFilterExpression>> filterExpressionTuples;
//            try
//            {
            var filterExpressionTuples = expression.FilterSymbols.Select(symbol =>
                                                                         new Tuple <FilterSymbol, Try <IFilterExpression> >(symbol, InstantiateFilter(templateContext, symbol)))
                                         .ToList();

            //}
            //catch (Exception ex)
            //{
            //   return LiquidExpressionResult.Error(ex.Message);
            //}
            if (filterExpressionTuples.Any(x => x.Item2.IsFailure))
            {
                // just return the first error.
                return(LiquidExpressionResult.Error(filterExpressionTuples.First().Item2.Exception.Message));
            }

            var erroringFilternames = filterExpressionTuples.Where(x => x.Item2 == null).Select(x => x.Item1).ToList();

            if (erroringFilternames.Any())
            {
                //throw new Exception("Missing filters...");
                //return ConstantFactory.CreateError<LiquidString>();
                return(LiquidExpressionResult.Error("Missing filters: " + String.Join(", ", erroringFilternames.Select(x => x.Name))));
            }

            var filterChain = FilterChain.CreateChain(
                objResult.GetType(),
                templateContext,
                filterExpressionTuples.Select(x => x.Item2.Value));

            // apply the composed function to the object

            var result = filterChain(objResult.SuccessResult);

            return(result);
        }
コード例 #14
0
        public int ReplaceStringCount(String refID)
        {
            if (!this.Project.DataTypeReferences.Contains(refID))
            {
                throw new BuildException(String.Format("The refid {0} is not defined.", refID));
            }

            FilterChain RefFilterChain = (FilterChain)this.Project.DataTypeReferences[refID];

            return(RefFilterChain.Filters.Count);
        }
        private void RequestHandler(object sender, EventArgs e)
        {
            HttpApplication httpApplication = (HttpApplication)sender;

            if (httpApplication.Request.RawUrl.IndexOf("/") > 0)
            {
                FilterChain chain = new FilterChain(new HttpUrlFilter());
                chain.DoFilter(httpApplication.Request, httpApplication.Response);
                httpApplication.Context.RemapHandler(handler);
            }
        }
コード例 #16
0
 /// <exception cref="System.IO.IOException"/>
 /// <exception cref="Javax.Servlet.ServletException"/>
 public void DoFilter(ServletRequest request, ServletResponse response, FilterChain
                      chain)
 {
     if (authorized)
     {
         chain.DoFilter(request, response);
     }
     else
     {
         ((HttpServletResponse)response).SendError(HttpServletResponse.ScForbidden);
     }
 }
コード例 #17
0
        private void buildChainOfFilters(out FilterChain o_ImageFilter)
        {
            NegativeFilter negativeFilter = new NegativeFilter();
            RedFilter      redFilter      = new RedFilter();
            GreenFilter    greenFilter    = new GreenFilter();
            BlueFilter     blueFilter     = new BlueFilter();

            negativeFilter.SetNextChain(redFilter);
            redFilter.SetNextChain(greenFilter);
            greenFilter.SetNextChain(blueFilter);
            o_ImageFilter = negativeFilter;
        }
コード例 #18
0
ファイル: NoCacheFilter.cs プロジェクト: orf53975/hadoop.net
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Javax.Servlet.ServletException"/>
        public virtual void DoFilter(ServletRequest req, ServletResponse res, FilterChain
                                     chain)
        {
            HttpServletResponse httpRes = (HttpServletResponse)res;

            httpRes.SetHeader("Cache-Control", "no-cache");
            long now = Runtime.CurrentTimeMillis();

            httpRes.AddDateHeader("Expires", now);
            httpRes.AddDateHeader("Date", now);
            httpRes.AddHeader("Pragma", "no-cache");
            chain.DoFilter(req, res);
        }
コード例 #19
0
ファイル: FileUtils.cs プロジェクト: GerHobbelt/nant
 /// <summary>
 /// Moves a file filtering its content through the filter chain.
 /// </summary>
 /// <param name="sourceFileName">The file to move.</param>
 /// <param name="destFileName">The file to move move to.</param>
 /// <param name="filterChain">Chain of filters to apply when moving, or <see langword="null" /> is no filters should be applied.</param>
 /// <param name="inputEncoding">The encoding used to read the soure file.</param>
 /// <param name="outputEncoding">The encoding used to write the destination file.</param>
 public static void MoveFile(string sourceFileName, string destFileName, FilterChain filterChain, Encoding inputEncoding, Encoding outputEncoding)
 {
     // if no filters have been defined, and no input or output encoding
     // is set, we can just use the File.Move method
     if ((filterChain == null || filterChain.Filters.Count == 0) && inputEncoding == null && outputEncoding == null)
     {
         File.Move(sourceFileName, destFileName);
     }
     else
     {
         CopyFile(sourceFileName, destFileName, filterChain, inputEncoding, outputEncoding);
         File.Delete(sourceFileName);
     }
 }
コード例 #20
0
        public void AddReplaceString(String refID, String oldValue, String newValue)
        {
            if (!this.Project.DataTypeReferences.Contains(refID))
            {
                throw new BuildException(String.Format("The refid {0} is not defined.", refID));
            }

            FilterChain   RefFilterChain      = (FilterChain)this.Project.DataTypeReferences[refID];
            ReplaceString ReplaceStringFilter = new ReplaceString();

            ReplaceStringFilter.From = oldValue;
            ReplaceStringFilter.To   = newValue;
            RefFilterChain.Filters.Add(ReplaceStringFilter);
        }
コード例 #21
0
        public void NoFilterChainCallT1()
        {
            var chain = new FilterChain <string>();

            var isCall = false;

            chain.Do("", (i) =>
            {
                isCall = !isCall;
            });

            chain.Do("");
            Assert.AreEqual(true, isCall);
        }
コード例 #22
0
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Javax.Servlet.ServletException"/>
        protected override void DoFilter(FilterChain filterChain, HttpServletRequest request
                                         , HttpServletResponse response)
        {
            bool requestCompleted          = false;
            UserGroupInformation ugi       = null;
            AuthenticationToken  authToken = (AuthenticationToken)request.GetUserPrincipal();

            if (authToken != null && authToken != AuthenticationToken.Anonymous)
            {
                // if the request was authenticated because of a delegation token,
                // then we ignore proxyuser (this is the same as the RPC behavior).
                ugi = (UserGroupInformation)request.GetAttribute(DelegationTokenAuthenticationHandler
                                                                 .DelegationTokenUgiAttribute);
                if (ugi == null)
                {
                    string realUser = request.GetUserPrincipal().GetName();
                    ugi = UserGroupInformation.CreateRemoteUser(realUser, handlerAuthMethod);
                    string doAsUser = GetDoAs(request);
                    if (doAsUser != null)
                    {
                        ugi = UserGroupInformation.CreateProxyUser(doAsUser, ugi);
                        try
                        {
                            ProxyUsers.Authorize(ugi, request.GetRemoteHost());
                        }
                        catch (AuthorizationException ex)
                        {
                            HttpExceptionUtils.CreateServletExceptionResponse(response, HttpServletResponse.ScForbidden
                                                                              , ex);
                            requestCompleted = true;
                        }
                    }
                }
                UgiTl.Set(ugi);
            }
            if (!requestCompleted)
            {
                UserGroupInformation ugiF = ugi;
                try
                {
                    request = new _HttpServletRequestWrapper_269(this, ugiF, request);
                    base.DoFilter(filterChain, request, response);
                }
                finally
                {
                    UgiTl.Remove();
                }
            }
        }
コード例 #23
0
ファイル: Program.cs プロジェクト: eoryl/DiscordAudioStream
        static void Main(string[] args)
        {
            if (args.Length < 0)
            {
                return;
            }

            PeakMeter   peakMeter1 = new PeakMeter();
            Amplifier   amplifier  = new Amplifier(AudioTools.dBFSToLinearf(12f));
            PeakLimiter limiter    = new PeakLimiter(20, 20, AudioTools.dBFSToLinearf(-3.0f));
            PeakMeter   peakMeter2 = new PeakMeter();

            FilterChain filterChain = new FilterChain();

            filterChain.Filters.Add(peakMeter1);
            filterChain.Filters.Add(amplifier);
            filterChain.Filters.Add(limiter);
            filterChain.Filters.Add(peakMeter2);

            WaveFileReader waveFileReader = new WaveFileReader(args[0]);

            waveFileReader.Position = 0;
            byte[]   byteBuffer = new byte[10 * 1024];
            float [] floatBuffer = null;
            int      bytesRead = 0, samplesAvailable = 0;

            filterChain.Init(waveFileReader.WaveFormat.SampleRate, waveFileReader.WaveFormat.Channels);

            int processed = 0;

            while (true)
            {
                bytesRead = waveFileReader.Read(byteBuffer, 0, 10 * 1024);

                if (bytesRead == 0)
                {
                    break;
                }
                AudioBufferConverter.ConvertByteArrayToFloatArray(byteBuffer, bytesRead, waveFileReader.WaveFormat.BitsPerSample, ref floatBuffer, ref samplesAvailable);

                filterChain.ProcessFrames(floatBuffer, samplesAvailable);
                processed += bytesRead;
            }
            System.Console.WriteLine("processed: " + processed);
            System.Console.WriteLine("peak1: " + peakMeter1.GlobalPeakSinceStartdBFS);
            System.Console.WriteLine("peak2: " + peakMeter2.GlobalPeakSinceStartdBFS);

            System.Console.ReadKey();
        }
コード例 #24
0
        /// <summary>
        /// Ends receive operation.
        /// </summary>
        /// <param name="buf">the buffer received in last receive operation</param>
        protected void EndReceive(IoBuffer buf)
        {
            if (ReadSuspended)
            {
                _pendingReceivedMessage = buf;
            }
            else
            {
                FilterChain.FireMessageReceived(buf);

                if (Socket.Connected)
                {
                    BeginReceive();
                }
            }
        }
コード例 #25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldPassThroughRequestsWithNullServletPath() throws Exception
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in C#:
        public virtual void ShouldPassThroughRequestsWithNullServletPath()
        {
            // given
            HttpServletRequest request = mock(typeof(HttpServletRequest));

            when(request.ServletPath).thenReturn(null);
            HttpServletResponse response    = mock(typeof(HttpServletResponse));
            FilterChain         filterChain = mock(typeof(FilterChain));

            // when
            (new StaticContentFilter()).DoFilter(request, response, filterChain);

            // then
            verifyZeroInteractions(response);
            verify(filterChain).doFilter(request, response);
        }
コード例 #26
0
//JAVA TO C# CONVERTER WARNING: Method 'throws' clauses are not available in .NET:
//ORIGINAL LINE: public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws java.io.IOException, ServletException
        public virtual void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        {
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final javax.servlet.http.HttpServletRequest request = (javax.servlet.http.HttpServletRequest) req;
            HttpServletRequest request = (HttpServletRequest)req;
//JAVA TO C# CONVERTER WARNING: The original Java variable was marked 'final':
//ORIGINAL LINE: final javax.servlet.http.HttpServletResponse response = (javax.servlet.http.HttpServletResponse) resp;
            HttpServletResponse response = (HttpServletResponse)resp;

            if ("GET".Equals(request.Method) && !request.RequestURI.EndsWith("xml"))
            {
                response.setHeader("Cache-Control", "no-cache");
            }

            chain.doFilter(req, resp);
        }
コード例 #27
0
        public void ProcessFile(string sourceFile, string targetFile, FilterChain filters)
        {
            Console.WriteLine("Applying filters:");

            var data = _handler.ReadFile(sourceFile);
            T   filteredData;

            try {
                filteredData = ApplyFilters(data, filters);
            } catch (Exception ex) {
                Console.WriteLine(GetType().FullName + " : " + ex.Message);
                throw;
            }

            _handler.WriteFile(filteredData, targetFile);
        }
コード例 #28
0
        public void It_Should_Cast_MisMatched_Filters()
        {
            // Arrange
            var filters = new List <IFilterExpression>
            {
                new UpCaseFilter(),
                new PlusFilter(LiquidNumeric.Create(123)),
            };

            // Act
            var castedFilters = FilterChain.InterpolateCastFilters(filters).ToList();

            // Assert
            Assert.That(castedFilters.Count, Is.EqualTo(3));
            Assert.That(castedFilters[1], Is.TypeOf(typeof(CastFilter <LiquidString, LiquidNumeric>)));
        }
コード例 #29
0
        /// <summary>
        /// 过滤站点html
        /// </summary>
        /// <param name="html"></param>
        /// <param name="filter"></param>
        /// <returns></returns>
        private static string FilterHtml(string html, string filter)
        {
            if (filter == null || filter == "")
            {
                return(html);
            }

            FilterChain chain = LoadFilter(filter);

            if (chain.Count() > 0)
            {
                html = chain.DoFilter(html);
            }

            return(html);
        }
コード例 #30
0
        public void It_Should_Compose_Functions_Together()
        {
            // Arrange
            var removeFilter = new RemoveFilter(LiquidString.Create("123"));
            var upCase       = new UpCaseFilter();
            var filterList   = new List <IFilterExpression> {
                removeFilter, upCase
            };
            var compositeFilterFn = FilterChain.CreateChain(new TemplateContext(), filterList);

            // Act
            var result = compositeFilterFn(LiquidString.Create("test123")).SuccessValue <LiquidString>();

            // Assert
            Assert.That(result.Value, Is.EqualTo("TEST"));
        }
コード例 #31
0
ファイル: AmIpFilter.cs プロジェクト: orf53975/hadoop.net
        //Empty
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="Javax.Servlet.ServletException"/>
        public virtual void DoFilter(ServletRequest req, ServletResponse resp, FilterChain
                                     chain)
        {
            ProxyUtils.RejectNonHttpRequests(req);
            HttpServletRequest  httpReq  = (HttpServletRequest)req;
            HttpServletResponse httpResp = (HttpServletResponse)resp;

            if (Log.IsDebugEnabled())
            {
                Log.Debug("Remote address for request is: {}", httpReq.GetRemoteAddr());
            }
            if (!GetProxyAddresses().Contains(httpReq.GetRemoteAddr()))
            {
                string redirectUrl = FindRedirectUrl();
                string target      = redirectUrl + httpReq.GetRequestURI();
                ProxyUtils.SendRedirect(httpReq, httpResp, target);
                return;
            }
            string user = null;

            if (httpReq.GetCookies() != null)
            {
                foreach (Cookie c in httpReq.GetCookies())
                {
                    if (WebAppProxyServlet.ProxyUserCookieName.Equals(c.GetName()))
                    {
                        user = c.GetValue();
                        break;
                    }
                }
            }
            if (user == null)
            {
                if (Log.IsDebugEnabled())
                {
                    Log.Debug("Could not find " + WebAppProxyServlet.ProxyUserCookieName + " cookie, so user will not be set"
                              );
                }
                chain.DoFilter(req, resp);
            }
            else
            {
                AmIpPrincipal  principal      = new AmIpPrincipal(user);
                ServletRequest requestWrapper = new AmIpServletRequestWrapper(httpReq, principal);
                chain.DoFilter(requestWrapper, resp);
            }
        }
コード例 #32
0
        /// <summary>
        /// Starts this session.
        /// </summary>
        public void Start()
        {
            if (ReadSuspended)
            {
                return;
            }

            if (_pendingReceivedMessage != null)
            {
                if (!Object.ReferenceEquals(_pendingReceivedMessage, dummy))
                {
                    FilterChain.FireMessageReceived(_pendingReceivedMessage);
                }
                _pendingReceivedMessage = null;
                BeginReceive();
            }
        }