示例#1
0
        public void EvaluateTrue(MatchedEventMap matchEvent, EvalStateNode fromNode, bool isQuitted)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QPatternAndEvaluateTrue(EvalAndNode, matchEvent);
            }

            int?indexFrom = null;

            for (int i = 0; i < ActiveChildNodes.Length; i++)
            {
                if (ActiveChildNodes[i] == fromNode)
                {
                    indexFrom = i;
                }
            }

            // If one of the children quits, remove the child
            if (isQuitted && indexFrom != null)
            {
                ActiveChildNodes[indexFrom.Value] = null;
            }

            if (EventsPerChild == null || indexFrom == null)
            {
                if (InstrumentationHelper.ENABLED)
                {
                    InstrumentationHelper.Get().APatternAndEvaluateTrue(true);
                }
                return;
            }

            // If all nodes have events received, the AND expression turns true
            var allHaveEventsExcludingFromChild = true;

            for (int i = 0; i < EventsPerChild.Length; i++)
            {
                if (indexFrom != i && EventsPerChild[i] == null)
                {
                    allHaveEventsExcludingFromChild = false;
                    break;
                }
            }

            // if we don't have events from all child nodes, add event and done
            if (!allHaveEventsExcludingFromChild)
            {
                AddMatchEvent(EventsPerChild, indexFrom.Value, matchEvent);
                if (InstrumentationHelper.ENABLED)
                {
                    InstrumentationHelper.Get().APatternAndEvaluateTrue(false);
                }
                return;
            }

            // if all other nodes have quit other then the from-node, don't retain matching event
            var allOtherNodesQuit = true;
            var hasActive         = false;

            for (int i = 0; i < EventsPerChild.Length; i++)
            {
                if (ActiveChildNodes[i] != null)
                {
                    hasActive = true;
                    if (i != indexFrom)
                    {
                        allOtherNodesQuit = false;
                    }
                }
            }

            // if not all other nodes have quit, add event to received list
            if (!allOtherNodesQuit)
            {
                AddMatchEvent(EventsPerChild, indexFrom.Value, matchEvent);
            }

            // For each combination in eventsPerChild for all other state nodes generate an event to the parent
            List <MatchedEventMap> result = GenerateMatchEvents(matchEvent, EventsPerChild, indexFrom.Value);

            // Check if this is quitting
            bool quitted = true;

            if (hasActive)
            {
                foreach (EvalStateNode stateNode in ActiveChildNodes)
                {
                    if (stateNode != null && !(stateNode.IsNotOperator))
                    {
                        quitted = false;
                    }
                }
            }

            // So we are quitting if all non-not child nodes have quit, since the not-node wait for evaluate false
            if (quitted)
            {
                QuitInternal();
            }

            // Send results to parent
            foreach (MatchedEventMap theEvent in result)
            {
                ParentEvaluator.EvaluateTrue(theEvent, this, quitted);
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().APatternAndEvaluateTrue(EventsPerChild == null);
            }
        }
示例#2
0
        public override UniformPair <EventBean[]> ProcessJoinResult(ISet <MultiKey <EventBean> > newEvents, ISet <MultiKey <EventBean> > oldEvents, bool isSynthesize)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QResultSetProcessSimple();
            }

            EventBean[] selectOldEvents = null;
            EventBean[] selectNewEvents;

            if (Prototype.OptionalHavingExpr == null)
            {
                if (Prototype.IsSelectRStream)
                {
                    if (_orderByProcessor == null)
                    {
                        selectOldEvents = ResultSetProcessorUtil.GetSelectJoinEventsNoHaving(_selectExprProcessor, oldEvents, false, isSynthesize, ExprEvaluatorContext);
                    }
                    else
                    {
                        selectOldEvents = ResultSetProcessorUtil.GetSelectJoinEventsNoHavingWithOrderBy(_selectExprProcessor, _orderByProcessor, oldEvents, false, isSynthesize, ExprEvaluatorContext);
                    }
                }

                if (_orderByProcessor == null)
                {
                    selectNewEvents = ResultSetProcessorUtil.GetSelectJoinEventsNoHaving(_selectExprProcessor, newEvents, true, isSynthesize, ExprEvaluatorContext);
                }
                else
                {
                    selectNewEvents = ResultSetProcessorUtil.GetSelectJoinEventsNoHavingWithOrderBy(_selectExprProcessor, _orderByProcessor, newEvents, true, isSynthesize, ExprEvaluatorContext);
                }
            }
            else
            {
                if (Prototype.IsSelectRStream)
                {
                    if (_orderByProcessor == null)
                    {
                        selectOldEvents = ResultSetProcessorUtil.GetSelectJoinEventsHaving(_selectExprProcessor, oldEvents, Prototype.OptionalHavingExpr, false, isSynthesize, ExprEvaluatorContext);
                    }
                    else
                    {
                        selectOldEvents = ResultSetProcessorUtil.GetSelectJoinEventsHavingWithOrderBy(_selectExprProcessor, _orderByProcessor, oldEvents, Prototype.OptionalHavingExpr, false, isSynthesize, ExprEvaluatorContext);
                    }
                }

                if (_orderByProcessor == null)
                {
                    selectNewEvents = ResultSetProcessorUtil.GetSelectJoinEventsHaving(_selectExprProcessor, newEvents, Prototype.OptionalHavingExpr, true, isSynthesize, ExprEvaluatorContext);
                }
                else
                {
                    selectNewEvents = ResultSetProcessorUtil.GetSelectJoinEventsHavingWithOrderBy(_selectExprProcessor, _orderByProcessor, newEvents, Prototype.OptionalHavingExpr, true, isSynthesize, ExprEvaluatorContext);
                }
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AResultSetProcessSimple(selectNewEvents, selectOldEvents);
            }
            return(new UniformPair <EventBean[]>(selectNewEvents, selectOldEvents));
        }
示例#3
0
        public void TestCoreLibInstrumentation()
        {
            DirectoryInfo directory = Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), nameof(TestCoreLibInstrumentation)));

            string[] files = new[]
            {
                "System.Private.CoreLib.dll",
                "System.Private.CoreLib.pdb"
            };

            foreach (var file in files)
            {
                File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets", file), Path.Combine(directory.FullName, file), overwrite: true);
            }

            Mock <FileSystem> partialMockFileSystem = new Mock <FileSystem>();

            partialMockFileSystem.CallBase = true;
            partialMockFileSystem.Setup(fs => fs.OpenRead(It.IsAny <string>())).Returns((string path) =>
            {
                if (Path.GetFileName(path) == files[1])
                {
                    return(File.OpenRead(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets"), files[1])));
                }
                else
                {
                    return(File.OpenRead(path));
                }
            });
            partialMockFileSystem.Setup(fs => fs.Exists(It.IsAny <string>())).Returns((string path) =>
            {
                if (Path.GetFileName(path) == files[1])
                {
                    return(File.Exists(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets"), files[1])));
                }
                else
                {
                    if (path.Contains(@":\git\runtime"))
                    {
                        return(true);
                    }
                    else
                    {
                        return(File.Exists(path));
                    }
                }
            });
            var sourceRootTranslator = new SourceRootTranslator(_mockLogger.Object, new FileSystem());
            InstrumentationHelper instrumentationHelper =
                new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), partialMockFileSystem.Object, _mockLogger.Object, sourceRootTranslator);
            Instrumenter instrumenter = new Instrumenter(Path.Combine(directory.FullName, files[0]), "_coverlet_instrumented", Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(),
                                                         Array.Empty <string>(), Array.Empty <string>(), false, false, _mockLogger.Object, instrumentationHelper, partialMockFileSystem.Object, sourceRootTranslator, new CecilSymbolHelper());

            Assert.True(instrumenter.CanInstrument());
            InstrumenterResult result = instrumenter.Instrument();

            Assert.NotNull(result);
            Assert.Equal(1052, result.Documents.Count);
            foreach ((string docName, Document _) in result.Documents)
            {
                Assert.False(docName.EndsWith(@"System.Private.CoreLib\src\System\Threading\Interlocked.cs"));
            }
            directory.Delete(true);
        }
示例#4
0
        public void TestInvalid()
        {
            var configuration = SupportConfigFactory.GetConfiguration();

            configuration.AddEventType("Bean", typeof(SupportBean).FullName);
            _epService = EPServiceProviderManager.GetDefaultProvider(configuration);
            _epService.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(_epService, GetType(), GetType().FullName);
            }

            _epService.EPAdministrator.Configuration.AddImport("com.espertech.esper.regression.client");

            TryInvalid("@MyAnnotationNested(NestableSimple=@MyAnnotationNestableSimple, NestableValues=@MyAnnotationNestableValues, NestableNestable=@MyAnnotationNestableNestable) select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationNestableNestable' requires a value for attribute 'Value' [@MyAnnotationNested(NestableSimple=@MyAnnotationNestableSimple, NestableValues=@MyAnnotationNestableValues, NestableNestable=@MyAnnotationNestableNestable) select * from Bean]");

            TryInvalid("@MyAnnotationNested(NestableNestable=@MyAnnotationNestableNestable('A'), NestableSimple=1) select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationNested' requires a MyAnnotationNestableSimpleAttribute-typed value for attribute 'NestableSimple' but received a System.Int32-typed value [@MyAnnotationNested(NestableNestable=@MyAnnotationNestableNestable('A'), NestableSimple=1) select * from Bean]");

            TryInvalid("@MyAnnotationValuePair(StringVal='abc') select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationValuePair' requires a value for attribute 'BooleanVal' [@MyAnnotationValuePair(StringVal='abc') select * from Bean]");

            TryInvalid("MyAnnotationValueArray(Value=5) select * from Bean", true,
                       "Incorrect syntax near 'MyAnnotationValueArray' [MyAnnotationValueArray(Value=5) select * from Bean]");

            TryInvalid("@MyAnnotationValueArray(Value=null) select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationValueArray' requires a value for attribute 'DoubleArray' [@MyAnnotationValueArray(Value=null) select * from Bean]");

            TryInvalid("@MyAnnotationValueArray(IntArray={},DoubleArray={},StringArray={null},Value={}) select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationValueArray' requires a non-null value for array elements for attribute 'StringArray' [@MyAnnotationValueArray(IntArray={},DoubleArray={},StringArray={null},Value={}) select * from Bean]");

            TryInvalid("@MyAnnotationValueArray(IntArray={},DoubleArray={},StringArray={1},Value={}) select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationValueArray' requires a System.String-typed value for array elements for attribute 'StringArray' but received a System.Int32-typed value [@MyAnnotationValueArray(IntArray={},DoubleArray={},StringArray={1},Value={}) select * from Bean]");

            TryInvalid("@MyAnnotationValue(Value='a', Value='a') select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationValue' has duplicate attribute values for attribute 'Value' [@MyAnnotationValue(Value='a', Value='a') select * from Bean]");
            TryInvalid("@ABC select * from Bean", false,
                       "Failed to process statement annotations: Failed to resolve @-annotation class: Could not load annotation class by name 'ABCAttribute', please check imports [@ABC select * from Bean]");

            TryInvalid("@MyAnnotationSimple(5) select * from Bean", false,
                       "Failed to process statement annotations: Failed to find property Value in annotation type MyAnnotationSimple [@MyAnnotationSimple(5) select * from Bean]");
            TryInvalid("@MyAnnotationSimple(null) select * from Bean", false,
                       "Failed to process statement annotations: Failed to find property Value in annotation type MyAnnotationSimple [@MyAnnotationSimple(null) select * from Bean]");

            TryInvalid("@MyAnnotationValue select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationValue' requires a value for attribute 'Value' [@MyAnnotationValue select * from Bean]");

            TryInvalid("@MyAnnotationValue(5) select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationValue' requires a String-typed value for attribute 'Value' but received a System.Int32-typed value [@MyAnnotationValue(5) select * from Bean]");
            TryInvalid("@MyAnnotationValueArray(Value=\"ABC\", IntArray={}, DoubleArray={}, StringArray={}) select * from Bean", false,
                       "Failed to process statement annotations: Annotation 'MyAnnotationValueArray' requires a System.Int64[]-typed value for attribute 'Value' but received a System.String-typed value [@MyAnnotationValueArray(Value=\"ABC\", IntArray={}, DoubleArray={}, StringArray={}) select * from Bean]");
            TryInvalid("@MyAnnotationValueEnum(a.b.CC) select * from Bean", false,
                       "Annotation enumeration value 'a.b.CC' not recognized as an enumeration class, please check imports or type used [@MyAnnotationValueEnum(a.b.CC) select * from Bean]");

            TryInvalid("@Hint('XXX') select * from Bean", false,
                       "Failed to process statement annotations: Hint annotation value 'XXX' is not one of the known values [@Hint('XXX') select * from Bean]");
            TryInvalid("@Hint('ITERATE_ONLY,XYZ') select * from Bean", false,
                       "Failed to process statement annotations: Hint annotation value 'XYZ' is not one of the known values [@Hint('ITERATE_ONLY,XYZ') select * from Bean]");
            TryInvalid("@Hint('testit=5') select * from Bean", false,
                       "Failed to process statement annotations: Hint annotation value 'testit' is not one of the known values [@Hint('testit=5') select * from Bean]");
            TryInvalid("@Hint('RECLAIM_GROUP_AGED') select * from Bean", false,
                       "Failed to process statement annotations: Hint 'RECLAIM_GROUP_AGED' requires a parameter value [@Hint('RECLAIM_GROUP_AGED') select * from Bean]");
            TryInvalid("@Hint('ITERATE_ONLY,RECLAIM_GROUP_AGED') select * from Bean", false,
                       "Failed to process statement annotations: Hint 'RECLAIM_GROUP_AGED' requires a parameter value [@Hint('ITERATE_ONLY,RECLAIM_GROUP_AGED') select * from Bean]");
            TryInvalid("@Hint('ITERATE_ONLY=5,RECLAIM_GROUP_AGED=5') select * from Bean", false,
                       "Failed to process statement annotations: Hint 'ITERATE_ONLY' does not accept a parameter value [@Hint('ITERATE_ONLY=5,RECLAIM_GROUP_AGED=5') select * from Bean]");
            TryInvalid("@Hint('index(name)xxx') select * from Bean", false,
                       "Failed to process statement annotations: Hint 'INDEX' has additional text after parentheses [@Hint('index(name)xxx') select * from Bean]");
            TryInvalid("@Hint('index') select * from Bean", false,
                       "Failed to process statement annotations: Hint 'INDEX' requires additional parameters in parentheses [@Hint('index') select * from Bean]");

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
        /// <summary>
        /// The update method is called if the view does not participate in a join.
        /// </summary>
        /// <param name="newData">- new events</param>
        /// <param name="oldData">- old events</param>
        public override void Update(EventBean[] newData, EventBean[] oldData)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QOutputProcessWCondition(newData, oldData);
            }

            if ((ExecutionPathDebugLog.IsEnabled) && (Log.IsDebugEnabled))
            {
                Log.Debug(
                    ".update Received update, " +
                    "  newData.Length==" + ((newData == null) ? 0 : newData.Length) +
                    "  oldData.Length==" + ((oldData == null) ? 0 : oldData.Length));
            }

            // add the incoming events to the event batches
            if (_parent.HasAfter)
            {
                bool afterSatisfied = base.CheckAfterCondition(newData, _parent.StatementContext);
                if (!afterSatisfied)
                {
                    if (!_parent.IsUnaggregatedUngrouped)
                    {
                        _deltaSet.AddView(new UniformPair <EventBean[]>(newData, oldData));
                    }
                    if (InstrumentationHelper.ENABLED)
                    {
                        InstrumentationHelper.Get().AOutputProcessWCondition(false);
                    }
                    return;
                }
                else
                {
                    _deltaSet.AddView(new UniformPair <EventBean[]>(newData, oldData));
                }
            }
            else
            {
                _deltaSet.AddView(new UniformPair <EventBean[]>(newData, oldData));
            }

            int newDataLength = 0;
            int oldDataLength = 0;

            if (newData != null)
            {
                newDataLength = newData.Length;
            }
            if (oldData != null)
            {
                oldDataLength = oldData.Length;
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QOutputRateConditionUpdate(newDataLength, oldDataLength);
            }
            _outputCondition.UpdateOutputCondition(newDataLength, oldDataLength);
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AOutputRateConditionUpdate();
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AOutputProcessWCondition(true);
            }
        }
 public void TestHasPdb()
 {
     Assert.True(InstrumentationHelper.HasPdb(typeof(InstrumentationHelperTests).Assembly.Location));
 }
示例#7
0
        public void TestClientAppAnnotationSimple()
        {
            var configuration = SupportConfigFactory.GetConfiguration();

            configuration.AddEventType("Bean", typeof(SupportBean).FullName);
            _epService = EPServiceProviderManager.GetDefaultProvider(configuration);
            _epService.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(_epService, GetType(), GetType().FullName);
            }

            _epService.EPAdministrator.Configuration.AddImport("com.espertech.esper.regression.client");
            _epService.EPAdministrator.Configuration.AddImport(typeof(SupportEnum));

            var stmtText =
                "@MyAnnotationSimple " +
                "@MyAnnotationValue('abc') " +
                "@MyAnnotationValueDefaulted " +
                "@MyAnnotationValueEnum(SupportEnum=com.espertech.esper.support.bean.SupportEnum.ENUM_VALUE_3) " +
                "@MyAnnotationValuePair(StringVal='a',IntVal=-1,LongVal=2,BooleanVal=True,CharVal='x',ByteVal=10,ShortVal=20,DoubleVal=2.5) " +
                "@Name('STMTONE') " +
                "select * from Bean";
            var stmtTextFormatted = "@MyAnnotationSimple" + NEWLINE +
                                    "@MyAnnotationValue('abc')" + NEWLINE +
                                    "@MyAnnotationValueDefaulted" + NEWLINE +
                                    "@MyAnnotationValueEnum(SupportEnum=com.espertech.esper.support.bean.SupportEnum.ENUM_VALUE_3)" + NEWLINE +
                                    "@MyAnnotationValuePair(StringVal='a',IntVal=-1,LongVal=2,BooleanVal=True,CharVal='x',ByteVal=10,ShortVal=20,DoubleVal=2.5)" + NEWLINE +
                                    "@Name('STMTONE')" + NEWLINE +
                                    "select *" + NEWLINE +
                                    "from Bean";
            var stmt = _epService.EPAdministrator.CreateEPL(stmtText);
            var spi  = (EPStatementSPI)stmt;

            Assert.AreEqual("select * from Bean", spi.ExpressionNoAnnotations);
            Assert.IsTrue(spi.IsNameProvided);

            var annotations = stmt.Annotations.ToArray();

            annotations = SortAlpha(annotations);
            Assert.AreEqual(6, annotations.Length);

            Assert.AreEqual(typeof(MyAnnotationSimpleAttribute), annotations[0].GetType());
            Assert.AreEqual("abc", ((MyAnnotationValueAttribute)annotations[1]).Value);
            Assert.AreEqual("XYZ", ((MyAnnotationValueDefaultedAttribute)annotations[2]).Value);
            Assert.AreEqual("STMTONE", ((NameAttribute)annotations[5]).Value);

            var enumval = (MyAnnotationValueEnumAttribute)annotations[3];

            Assert.AreEqual(SupportEnum.ENUM_VALUE_2, enumval.SupportEnumDef);
            Assert.AreEqual(SupportEnum.ENUM_VALUE_3, enumval.SupportEnum);

            var pair = (MyAnnotationValuePairAttribute)annotations[4];

            Assert.AreEqual("a", pair.StringVal);
            Assert.AreEqual(-1, pair.IntVal);
            Assert.AreEqual(2l, pair.LongVal);
            Assert.AreEqual(true, pair.BooleanVal);
            Assert.AreEqual('x', pair.CharVal);
            Assert.AreEqual(10, pair.ByteVal);
            Assert.AreEqual(20, pair.ShortVal);
            Assert.AreEqual(2.5, pair.DoubleVal);
            Assert.AreEqual("def", pair.StringValDef);
            Assert.AreEqual(100, pair.IntValDef);
            Assert.AreEqual(200l, pair.LongValDef);
            Assert.AreEqual(true, pair.BooleanValDef);
            Assert.AreEqual('D', pair.CharValDef);
            Assert.AreEqual(1.1, pair.DoubleValDef);

            // statement model
            var model = _epService.EPAdministrator.CompileEPL(stmtText);

            Assert.AreEqual(stmtText, model.ToEPL());
            var textFormatted = model.ToEPL(new EPStatementFormatter(true));

            Assert.AreEqual(stmtTextFormatted, textFormatted);
            var stmtTwo = _epService.EPAdministrator.Create(model);

            Assert.AreEqual(stmtTwo.Text, model.ToEPL());
            Assert.AreEqual(6, stmtTwo.Annotations.Count);

            // test array
            stmtText =
                "@MyAnnotationValueArray(Value={1, 2, 3}, IntArray={4, 5}, DoubleArray={}, \nStringArray={\"X\"})\n" +
                "/* Test */ select * \nfrom Bean";
            stmt = _epService.EPAdministrator.CreateEPL(stmtText);

            annotations = stmt.Annotations.ToArray();
            annotations = SortAlpha(annotations);
            Assert.AreEqual(1, annotations.Length);

            var array = (MyAnnotationValueArrayAttribute)annotations[0];

            Assert.IsTrue(CompatExtensions.DeepEquals(ToObjectArray(array.Value), new Object[] { 1L, 2L, 3L }));
            Assert.IsTrue(CompatExtensions.DeepEquals(ToObjectArray(array.IntArray), new Object[] { 4, 5 }));
            Assert.IsTrue(CompatExtensions.DeepEquals(ToObjectArray(array.DoubleArray), new Object[] { }));
            Assert.IsTrue(CompatExtensions.DeepEquals(ToObjectArray(array.StringArray), new Object[] { "X" }));
            Assert.IsTrue(CompatExtensions.DeepEquals(ToObjectArray(array.StringArrayDef), new Object[] { "XYZ" }));

            // statement model
            model = _epService.EPAdministrator.CompileEPL(stmtText);
            Assert.AreEqual("@MyAnnotationValueArray(Value={1,2,3},IntArray={4,5},DoubleArray={},StringArray={'X'}) select * from Bean", model.ToEPL());
            stmtTwo = _epService.EPAdministrator.Create(model);
            Assert.AreEqual(stmtTwo.Text, model.ToEPL());
            Assert.AreEqual(1, stmtTwo.Annotations.Count);

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
示例#8
0
        public override void Update(EventBean[] newData, EventBean[] oldData)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QViewProcessIRStream(this, UnivariateStatisticsViewFactory.NAME, newData, oldData);
            }

            // If we have child views, keep a reference to the old values, so we can Update them as old data event.
            EventBean oldDataMap = null;

            if (_lastNewEvent == null)
            {
                if (HasViews)
                {
                    oldDataMap = PopulateMap(_baseStatisticsBean, _agentInstanceContext.StatementContext.EventAdapterService, _viewFactory.EventType, _viewFactory.AdditionalProps, _lastValuesEventNew);
                }
            }

            var evaluateParams = new EvaluateParams(_eventsPerStream, true, _agentInstanceContext);

            // add data points to the bean
            if (newData != null)
            {
                for (int i = 0; i < newData.Length; i++)
                {
                    _eventsPerStream[0] = newData[i];
                    var pointnum = _fieldExpressionEvaluator.Evaluate(evaluateParams);
                    if (pointnum != null)
                    {
                        double point = pointnum.AsDouble();
                        _baseStatisticsBean.AddPoint(point, 0);
                    }
                }

                if ((_viewFactory.AdditionalProps != null) && (newData.Length != 0))
                {
                    if (_lastValuesEventNew == null)
                    {
                        _lastValuesEventNew = new Object[_viewFactory.AdditionalProps.AdditionalExpr.Length];
                    }
                    for (int val = 0; val < _viewFactory.AdditionalProps.AdditionalExpr.Length; val++)
                    {
                        _lastValuesEventNew[val] = _viewFactory.AdditionalProps.AdditionalExpr[val].Evaluate(evaluateParams);
                    }
                }
            }

            // remove data points from the bean
            if (oldData != null)
            {
                for (int i = 0; i < oldData.Length; i++)
                {
                    _eventsPerStream[0] = oldData[i];
                    var pointnum = _fieldExpressionEvaluator.Evaluate(evaluateParams);
                    if (pointnum != null)
                    {
                        double point = pointnum.AsDouble();
                        _baseStatisticsBean.RemovePoint(point, 0);
                    }
                }
            }

            // If there are child view, call Update method
            if (HasViews)
            {
                EventBean newDataMap = PopulateMap(_baseStatisticsBean, _agentInstanceContext.StatementContext.EventAdapterService, _viewFactory.EventType, _viewFactory.AdditionalProps, _lastValuesEventNew);

                EventBean[] oldEvents;
                EventBean[] newEvents = new EventBean[] { newDataMap };
                if (_lastNewEvent == null)
                {
                    oldEvents = new EventBean[] { oldDataMap };
                }
                else
                {
                    oldEvents = new EventBean[] { _lastNewEvent };
                }

                Instrument.With(
                    i => i.QViewIndicate(this, UnivariateStatisticsViewFactory.NAME, newEvents, oldEvents),
                    i => i.AViewIndicate(),
                    () => UpdateChildren(newEvents, oldEvents));

                _lastNewEvent = newDataMap;
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AViewProcessIRStream();
            }
        }
示例#9
0
        protected override StatementAgentInstanceFactoryResult NewContextInternal(AgentInstanceContext agentInstanceContext, bool isRecoveringResilient)
        {
            IList <StopCallback> stopCallbacks = new List <StopCallback>(2);

            Viewable finalView;
            var      viewableActivationResult = new ViewableActivationResult[_eventStreamParentViewableActivators.Length];
            IDictionary <ExprSubselectNode, SubSelectStrategyHolder> subselectStrategies;
            AggregationService aggregationService;

            Viewable[] streamViews;
            Viewable[] eventStreamParentViewable;
            Viewable[] topViews;
            IDictionary <ExprPriorNode, ExprPriorEvalStrategy>             priorNodeStrategies;
            IDictionary <ExprPreviousNode, ExprPreviousEvalStrategy>       previousNodeStrategies;
            IDictionary <ExprTableAccessNode, ExprTableAccessEvalStrategy> tableAccessStrategies;
            RegexExprPreviousEvalStrategy         regexExprPreviousEvalStrategy = null;
            IList <StatementAgentInstancePreload> preloadList = new List <StatementAgentInstancePreload>();

            EvalRootState[] patternRoots;
            StatementAgentInstancePostLoad postLoadJoin = null;
            var suppressSameEventMatches = false;
            var discardPartialsOnMatch   = false;
            EvalRootMatchRemover evalRootMatchRemover = null;

            try {
                // create root viewables
                eventStreamParentViewable = new Viewable[_numStreams];
                patternRoots = new EvalRootState[_numStreams];

                for (var stream = 0; stream < _eventStreamParentViewableActivators.Length; stream++)
                {
                    var activationResult = _eventStreamParentViewableActivators[stream].Activate(agentInstanceContext, false, isRecoveringResilient);
                    viewableActivationResult[stream] = activationResult;
                    stopCallbacks.Add(activationResult.StopCallback);
                    suppressSameEventMatches = activationResult.IsSuppressSameEventMatches;
                    discardPartialsOnMatch   = activationResult.IsDiscardPartialsOnMatch;

                    // add stop callback for any stream-level viewable when applicable
                    if (activationResult.Viewable is StopCallback)
                    {
                        stopCallbacks.Add((StopCallback)activationResult.Viewable);
                    }

                    eventStreamParentViewable[stream] = activationResult.Viewable;
                    patternRoots[stream] = activationResult.OptionalPatternRoot;
                    if (stream == 0)
                    {
                        evalRootMatchRemover = activationResult.OptEvalRootMatchRemover;
                    }

                    if (activationResult.OptionalLock != null)
                    {
                        agentInstanceContext.EpStatementAgentInstanceHandle.StatementAgentInstanceLock = activationResult.OptionalLock;
                        _statementContext.DefaultAgentInstanceLock = activationResult.OptionalLock;
                    }
                }

                // compile view factories adding "prior" as necessary
                var viewFactoryChains = new IList <ViewFactory> [_numStreams];
                for (var i = 0; i < _numStreams; i++)
                {
                    var viewFactoryChain = _unmaterializedViewChain[i].FactoryChain;

                    // add "prior" view factory
                    var hasPrior = _viewResourceDelegate.PerStream[i].PriorRequests != null && !_viewResourceDelegate.PerStream[i].PriorRequests.IsEmpty();
                    if (hasPrior)
                    {
                        var priorEventViewFactory = EPStatementStartMethodHelperPrior.GetPriorEventViewFactory(
                            agentInstanceContext.StatementContext, i, viewFactoryChain.IsEmpty(), false, -1);
                        viewFactoryChain = new List <ViewFactory>(viewFactoryChain);
                        viewFactoryChain.Add(priorEventViewFactory);
                    }
                    viewFactoryChains[i] = viewFactoryChain;
                }

                // create view factory chain context: holds stream-specific services
                var viewFactoryChainContexts = new AgentInstanceViewFactoryChainContext[_numStreams];
                for (var i = 0; i < _numStreams; i++)
                {
                    viewFactoryChainContexts[i] = AgentInstanceViewFactoryChainContext.Create(viewFactoryChains[i], agentInstanceContext, _viewResourceDelegate.PerStream[i]);
                }

                // handle "prior" nodes and their strategies
                priorNodeStrategies = EPStatementStartMethodHelperPrior.CompilePriorNodeStrategies(_viewResourceDelegate, viewFactoryChainContexts);

                // handle "previous" nodes and their strategies
                previousNodeStrategies = EPStatementStartMethodHelperPrevious.CompilePreviousNodeStrategies(_viewResourceDelegate, viewFactoryChainContexts);

                // materialize views
                streamViews = new Viewable[_numStreams];
                topViews    = new Viewable[_numStreams];
                for (var i = 0; i < _numStreams; i++)
                {
                    var hasPreviousNode = _viewResourceDelegate.PerStream[i].PreviousRequests != null && !_viewResourceDelegate.PerStream[i].PreviousRequests.IsEmpty();

                    var createResult = _services.ViewService.CreateViews(eventStreamParentViewable[i], viewFactoryChains[i], viewFactoryChainContexts[i], hasPreviousNode);
                    topViews[i]    = createResult.TopViewable;
                    streamViews[i] = createResult.FinalViewable;

                    var isReuseableView = _eventStreamParentViewableActivators[i] is ViewableActivatorStreamReuseView;
                    if (isReuseableView)
                    {
                        var viewsCreated = createResult.NewViews;
                        var stopCallback = new ProxyStopCallback(() => {
                            ViewServiceHelper.RemoveFirstUnsharedView(viewsCreated);
                        });
                        stopCallbacks.Add(stopCallback);
                    }

                    // add views to stop callback if applicable
                    AddViewStopCallback(stopCallbacks, createResult.NewViews);
                }

                // determine match-recognize "previous"-node strategy (none if not present, or one handling and number of nodes)
                var matchRecognize = EventRowRegexHelper.RecursiveFindRegexService(topViews[0]);
                if (matchRecognize != null)
                {
                    regexExprPreviousEvalStrategy = matchRecognize.PreviousEvaluationStrategy;
                    stopCallbacks.Add(new ProxyStopCallback(matchRecognize.Stop));
                }

                // start subselects
                subselectStrategies = EPStatementStartMethodHelperSubselect.StartSubselects(_services, _subSelectStrategyCollection, agentInstanceContext, stopCallbacks, isRecoveringResilient);

                // plan table access
                tableAccessStrategies = EPStatementStartMethodHelperTableAccess.AttachTableAccess(_services, agentInstanceContext, _statementSpec.TableNodes);

                // obtain result set processor and aggregation services
                var processorPair      = EPStatementStartMethodHelperUtil.StartResultSetAndAggregation(_resultSetProcessorFactoryDesc, agentInstanceContext, false, null);
                var resultSetProcessor = processorPair.First;
                aggregationService = processorPair.Second;
                stopCallbacks.Add(aggregationService);
                stopCallbacks.Add(resultSetProcessor);

                // for just 1 event stream without joins, handle the one-table process separately.
                JoinPreloadMethod   joinPreloadMethod;
                JoinSetComposerDesc joinSetComposer = null;
                if (streamViews.Length == 1)
                {
                    finalView         = HandleSimpleSelect(streamViews[0], resultSetProcessor, agentInstanceContext, evalRootMatchRemover, suppressSameEventMatches, discardPartialsOnMatch);
                    joinPreloadMethod = null;
                }
                else
                {
                    var joinPlanResult = HandleJoin(_typeService.StreamNames, streamViews, resultSetProcessor,
                                                    agentInstanceContext, stopCallbacks, _joinAnalysisResult, isRecoveringResilient);
                    finalView         = joinPlanResult.Viewable;
                    joinPreloadMethod = joinPlanResult.PreloadMethod;
                    joinSetComposer   = joinPlanResult.JoinSetComposerDesc;
                }

                // for stoppable final views, add callback
                if (finalView is StopCallback)
                {
                    stopCallbacks.Add((StopCallback)finalView);
                }

                // Replay any named window data, for later consumers of named data windows
                if (_services.EventTableIndexService.AllowInitIndex(isRecoveringResilient))
                {
                    var hasNamedWindow             = false;
                    var namedWindowPostloadFilters = new FilterSpecCompiled[_statementSpec.StreamSpecs.Length];
                    var namedWindowTailViews       = new NamedWindowTailViewInstance[_statementSpec.StreamSpecs.Length];
                    var namedWindowFilters         = new IList <ExprNode> [_statementSpec.StreamSpecs.Length];

                    for (var i = 0; i < _statementSpec.StreamSpecs.Length; i++)
                    {
                        var streamNum  = i;
                        var streamSpec = _statementSpec.StreamSpecs[i];

                        if (streamSpec is NamedWindowConsumerStreamSpec)
                        {
                            hasNamedWindow = true;
                            var namedSpec = (NamedWindowConsumerStreamSpec)streamSpec;
                            NamedWindowProcessor processor = _services.NamedWindowMgmtService.GetProcessor(namedSpec.WindowName);
                            var processorInstance          = processor.GetProcessorInstance(agentInstanceContext);
                            if (processorInstance != null)
                            {
                                var consumerView = processorInstance.TailViewInstance;
                                namedWindowTailViews[i] = consumerView;
                                var view = (NamedWindowConsumerView)viewableActivationResult[i].Viewable;

                                // determine preload/postload filter for index access
                                if (!namedSpec.FilterExpressions.IsEmpty())
                                {
                                    namedWindowFilters[streamNum] = namedSpec.FilterExpressions;
                                    try {
                                        var streamName = streamSpec.OptionalStreamName != null ? streamSpec.OptionalStreamName : consumerView.EventType.Name;
                                        var types      = new StreamTypeServiceImpl(consumerView.EventType, streamName, false, _services.EngineURI);
                                        var tagged     = new LinkedHashMap <string, Pair <EventType, string> >();
                                        namedWindowPostloadFilters[i] = FilterSpecCompiler.MakeFilterSpec(types.EventTypes[0], types.StreamNames[0],
                                                                                                          namedSpec.FilterExpressions, null, tagged, tagged, types, null, _statementContext, Collections.SingletonSet(0));
                                    }
                                    catch (Exception ex) {
                                        Log.Warn("Unexpected exception analyzing filter paths: " + ex.Message, ex);
                                    }
                                }

                                // preload view for stream unless the expiry policy is batch window
                                var preload = !consumerView.TailView.IsParentBatchWindow && consumerView.HasFirst();
                                if (preload)
                                {
                                    if (isRecoveringResilient && _numStreams < 2)
                                    {
                                        preload = false;
                                    }
                                }
                                if (preload)
                                {
                                    var yesRecoveringResilient = isRecoveringResilient;
                                    var preloadFilterSpec      = namedWindowPostloadFilters[i];
                                    preloadList.Add(new ProxyStatementAgentInstancePreload()
                                    {
                                        ProcExecutePreload = () => {
                                            var snapshot       = consumerView.Snapshot(preloadFilterSpec, _statementContext.Annotations);
                                            var eventsInWindow = new List <EventBean>(snapshot.Count);
                                            ExprNodeUtility.ApplyFilterExpressions(snapshot, namedSpec.FilterExpressions, agentInstanceContext, eventsInWindow);
                                            EventBean[] newEvents = eventsInWindow.ToArray();
                                            view.Update(newEvents, null);
                                            if (!yesRecoveringResilient && joinPreloadMethod != null && !joinPreloadMethod.IsPreloading && agentInstanceContext.EpStatementAgentInstanceHandle.OptionalDispatchable != null)
                                            {
                                                agentInstanceContext.EpStatementAgentInstanceHandle.OptionalDispatchable.Execute();
                                            }
                                        },
                                    });
                                }
                            }
                            else
                            {
                                Log.Info("Named window access is out-of-context, the named window '" + namedSpec.WindowName + "' has been declared for a different context then the current statement, the aggregation and join state will not be initialized for statement expression [" + _statementContext.Expression + "]");
                            }

                            preloadList.Add(new ProxyStatementAgentInstancePreload()
                            {
                                ProcExecutePreload = () => {
                                    // in a join, preload indexes, if any
                                    if (joinPreloadMethod != null)
                                    {
                                        joinPreloadMethod.PreloadFromBuffer(streamNum);
                                    }
                                    else
                                    {
                                        if (agentInstanceContext.EpStatementAgentInstanceHandle.OptionalDispatchable != null)
                                        {
                                            agentInstanceContext.EpStatementAgentInstanceHandle.OptionalDispatchable.Execute();
                                        }
                                    }
                                },
                            });
                        }
                    }

                    // last, for aggregation we need to send the current join results to the result set processor
                    if ((hasNamedWindow) && (joinPreloadMethod != null) && (!isRecoveringResilient) && _resultSetProcessorFactoryDesc.ResultSetProcessorFactory.HasAggregation)
                    {
                        preloadList.Add(new ProxyStatementAgentInstancePreload()
                        {
                            ProcExecutePreload = () => {
                                joinPreloadMethod.PreloadAggregation(resultSetProcessor);
                            },
                        });
                    }

                    if (isRecoveringResilient)
                    {
                        postLoadJoin = new StatementAgentInstancePostLoadSelect(streamViews, joinSetComposer, namedWindowTailViews, namedWindowPostloadFilters, namedWindowFilters, _statementContext.Annotations, agentInstanceContext);
                    }
                    else if (joinSetComposer != null)
                    {
                        postLoadJoin = new StatementAgentInstancePostLoadIndexVisiting(joinSetComposer.JoinSetComposer);
                    }
                }
            }
            catch (Exception) {
                var stopCallback = StatementAgentInstanceUtil.GetStopCallback(stopCallbacks, agentInstanceContext);
                StatementAgentInstanceUtil.StopSafe(stopCallback, _statementContext);
                if (InstrumentationHelper.ENABLED)
                {
                    InstrumentationHelper.Get().AContextPartitionAllocate();
                }
                throw;
            }

            var selectResult = new StatementAgentInstanceFactorySelectResult(finalView, null, agentInstanceContext, aggregationService, subselectStrategies, priorNodeStrategies, previousNodeStrategies, regexExprPreviousEvalStrategy, tableAccessStrategies, preloadList, patternRoots, postLoadJoin, topViews, eventStreamParentViewable, viewableActivationResult);

            if (_statementContext.StatementExtensionServicesContext != null)
            {
                _statementContext.StatementExtensionServicesContext.ContributeStopCallback(selectResult, stopCallbacks);
            }
            var stopCallbackX = StatementAgentInstanceUtil.GetStopCallback(stopCallbacks, agentInstanceContext);

            selectResult.StopCallback = stopCallbackX;

            return(selectResult);
        }
示例#10
0
        public void TestTimeBatchWindow()
        {
            var config = SupportConfigFactory.GetConfiguration();

            config.AddEventType <SupportRecogBean>("MyEvent");
            var epService = EPServiceProviderManager.GetDefaultProvider(config);

            epService.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(epService, GetType(), GetType().FullName);
            }

            SendTimer(0, epService);
            var fields = "a_string,b_string,c_string".Split(',');
            var text   = "select * from MyEvent.win:time_batch(5 sec) " +
                         "match_recognize (" +
                         "  partition by Cat " +
                         "  measures A.TheString as a_string, B.TheString as b_string, C.TheString as c_string" +
                         "  all matches pattern ( (A | B) C ) " +
                         "  define " +
                         "    A as A.TheString like 'A%'," +
                         "    B as B.TheString like 'B%'," +
                         "    C as C.TheString like 'C%' and C.Value in (A.Value, B.Value)" +
                         ") order by a_string";

            var stmt     = epService.EPAdministrator.CreateEPL(text);
            var listener = new SupportUpdateListener();

            stmt.Events += listener.Update;

            SendTimer(50, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("A1", "001", 1));
            epService.EPRuntime.SendEvent(new SupportRecogBean("B1", "002", 1));
            epService.EPRuntime.SendEvent(new SupportRecogBean("B2", "002", 4));
            Assert.IsFalse(listener.IsInvoked);
            Assert.IsFalse(stmt.HasFirst());

            SendTimer(4000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("C1", "002", 4));
            epService.EPRuntime.SendEvent(new SupportRecogBean("C2", "002", 5));
            epService.EPRuntime.SendEvent(new SupportRecogBean("B3", "003", -1));
            Assert.IsFalse(listener.IsInvoked);
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields,
                                              new Object[][] { new Object[] { null, "B2", "C1" } });

            SendTimer(5050, epService);
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields,
                                              new Object[][] { new Object[] { null, "B2", "C1" } });
            Assert.IsFalse(stmt.HasFirst());

            SendTimer(6000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("C3", "003", -1));
            epService.EPRuntime.SendEvent(new SupportRecogBean("C4", "001", 1));
            Assert.IsFalse(listener.IsInvoked);
            Assert.IsFalse(stmt.HasFirst());

            SendTimer(10050, epService);
            Assert.IsFalse(listener.IsInvoked);
            Assert.IsFalse(stmt.HasFirst());

            SendTimer(14000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("A2", "002", 0));
            epService.EPRuntime.SendEvent(new SupportRecogBean("B4", "003", 10));
            epService.EPRuntime.SendEvent(new SupportRecogBean("C5", "002", 0));
            epService.EPRuntime.SendEvent(new SupportRecogBean("C6", "003", 10));
            Assert.IsFalse(listener.IsInvoked);
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields,
                                              new Object[][] { new Object[] { null, "B4", "C6" }, new Object[] { "A2", null, "C5" } });

            SendTimer(15050, epService);
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields,
                                              new Object[][] { new Object[] { null, "B4", "C6" }, new Object[] { "A2", null, "C5" } });
            Assert.IsFalse(stmt.HasFirst());

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
示例#11
0
        public void TestTimeWindow()
        {
            var config = SupportConfigFactory.GetConfiguration();

            config.AddEventType <SupportRecogBean>("MyEvent");
            var epService = EPServiceProviderManager.GetDefaultProvider(config);

            epService.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(epService, GetType(), GetType().FullName);
            }

            SendTimer(0, epService);
            var fields = "a_string,b_string,c_string".Split(',');
            var text   = "select * from MyEvent.win:time(5 sec) " +
                         "match_recognize (" +
                         "  measures A.TheString as a_string, B.TheString as b_string, C.TheString as c_string" +
                         "  all matches pattern ( A B C ) " +
                         "  define " +
                         "    A as (A.Value = 1)," +
                         "    B as (B.Value = 2)," +
                         "    C as (C.Value = 3)" +
                         ")";

            var stmt     = epService.EPAdministrator.CreateEPL(text);
            var listener = new SupportUpdateListener();

            stmt.Events += listener.Update;

            SendTimer(50, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("E1", 1));

            SendTimer(1000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("E2", 2));
            Assert.IsFalse(stmt.HasFirst());
            Assert.IsFalse(listener.IsInvoked);

            SendTimer(6000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("E3", 3));
            Assert.IsFalse(stmt.HasFirst());
            Assert.IsFalse(listener.IsInvoked);

            SendTimer(7000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("E4", 1));

            SendTimer(8000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("E5", 2));

            SendTimer(11500, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("E6", 3));
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields,
                                              new Object[][] { new Object[] { "E4", "E5", "E6" } });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields,
                                              new Object[][] { new Object[] { "E4", "E5", "E6" } });

            SendTimer(11999, epService);
            Assert.IsTrue(stmt.HasFirst());

            SendTimer(12000, epService);
            Assert.IsFalse(stmt.HasFirst());
            Assert.IsFalse(listener.IsInvoked);

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
示例#12
0
	    public void TearDown() {
	        if (InstrumentationHelper.ENABLED) { InstrumentationHelper.EndTest();}
	        _listener = null;
	    }
示例#13
0
	    public void TestUnboundStreamUnlimitedKey()
	    {
	        if (InstrumentationHelper.ENABLED) { InstrumentationHelper.EndTest();}

	        // ESPER-396 Unbound stream and aggregating/grouping by unlimited key (i.e. timestamp) configurable state drop
	        SendTimer(0);

	        // After the oldest group is 60 second old, reclaim group older then  30 seconds
	        _epService.EPAdministrator.Configuration.AddEventType<SupportBean>();
	        var stmtOne = _epService.EPAdministrator.CreateEPL("@Hint('reclaim_group_aged=30,reclaim_group_freq=5') select LongPrimitive, count(*) from SupportBean group by LongPrimitive");
	        stmtOne.AddListener(_listener);

	        for (var i = 0; i < 1000; i++)
	        {
	            SendTimer(1000 + i * 1000); // reduce factor if sending more events
	            var theEvent = new SupportBean();
	            theEvent.LongPrimitive = i * 1000;
	            _epService.EPRuntime.SendEvent(theEvent);
	        }

	        _listener.Reset();

	        for (var i = 0; i < 964; i++)
	        {
	            var theEvent = new SupportBean();
	            theEvent.LongPrimitive = i * 1000;
	            _epService.EPRuntime.SendEvent(theEvent);
                Assert.AreEqual(1L, _listener.AssertOneGetNewAndReset().Get("count(*)"), "Failed at " + i);
	        }

	        for (var i = 965; i < 1000; i++)
	        {
	            var theEvent = new SupportBean();
	            theEvent.LongPrimitive = i * 1000;
	            _epService.EPRuntime.SendEvent(theEvent);
                Assert.AreEqual(2L, _listener.AssertOneGetNewAndReset().Get("count(*)"), "Failed at " + i);
	        }

	        // no frequency provided
	        _epService.EPAdministrator.CreateEPL("@Hint('reclaim_group_aged=30') select LongPrimitive, count(*) from SupportBean group by LongPrimitive");
	        _epService.EPRuntime.SendEvent(new SupportBean());

	        _epService.EPAdministrator.CreateEPL("create variable int myAge = 10");
	        _epService.EPAdministrator.CreateEPL("create variable int myFreq = 10");

	        stmtOne.Dispose();
	        stmtOne = _epService.EPAdministrator.CreateEPL("@Hint('reclaim_group_aged=myAge,reclaim_group_freq=myFreq') select LongPrimitive, count(*) from SupportBean group by LongPrimitive");
	        stmtOne.AddListener(_listener);

	        for (var i = 0; i < 1000; i++)
	        {
	            SendTimer(2000000 + 1000 + i * 1000); // reduce factor if sending more events
	            var theEvent = new SupportBean();
	            theEvent.LongPrimitive = i * 1000;
	            _epService.EPRuntime.SendEvent(theEvent);

	            if (i == 500)
	            {
	                _epService.EPRuntime.SetVariableValue("myAge", 60);
	                _epService.EPRuntime.SetVariableValue("myFreq", 90);
	            }

	            /*
	            if (i % 100000 == 0)
	            {
	                System.out.println("Sending event number " + i);
	            }
	            */
	        }

	        _listener.Reset();

	        for (var i = 0; i < 900; i++)
	        {
	            var theEvent = new SupportBean();
	            theEvent.LongPrimitive = i * 1000;
	            _epService.EPRuntime.SendEvent(theEvent);
                Assert.AreEqual(1L, _listener.AssertOneGetNewAndReset().Get("count(*)"), "Failed at " + i);
	        }

	        for (var i = 900; i < 1000; i++)
	        {
	            var theEvent = new SupportBean();
	            theEvent.LongPrimitive = i * 1000;
	            _epService.EPRuntime.SendEvent(theEvent);
                Assert.AreEqual(2L, _listener.AssertOneGetNewAndReset().Get("count(*)"), "Failed at " + i);
	        }

	        stmtOne.Dispose();

	        // invalid tests
	        TryInvalid("@Hint('reclaim_group_aged=xyz') select LongPrimitive, count(*) from SupportBean group by LongPrimitive",
	                   "Error starting statement: Failed to parse hint parameter value 'xyz' as a double-typed seconds value or variable name [@Hint('reclaim_group_aged=xyz') select LongPrimitive, count(*) from SupportBean group by LongPrimitive]");
	        TryInvalid("@Hint('reclaim_group_aged=30,reclaim_group_freq=xyz') select LongPrimitive, count(*) from SupportBean group by LongPrimitive",
	                   "Error starting statement: Failed to parse hint parameter value 'xyz' as a double-typed seconds value or variable name [@Hint('reclaim_group_aged=30,reclaim_group_freq=xyz') select LongPrimitive, count(*) from SupportBean group by LongPrimitive]");
	        _epService.EPAdministrator.Configuration.AddVariable("MyVar", typeof(string), "");
	        TryInvalid("@Hint('reclaim_group_aged=MyVar') select LongPrimitive, count(*) from SupportBean group by LongPrimitive",
	                   "Error starting statement: Variable type of variable 'MyVar' is not numeric [@Hint('reclaim_group_aged=MyVar') select LongPrimitive, count(*) from SupportBean group by LongPrimitive]");
	        TryInvalid("@Hint('reclaim_group_aged=-30,reclaim_group_freq=30') select LongPrimitive, count(*) from SupportBean group by LongPrimitive",
	                   "Error starting statement: Hint parameter value '-30' is an invalid value, expecting a double-typed seconds value or variable name [@Hint('reclaim_group_aged=-30,reclaim_group_freq=30') select LongPrimitive, count(*) from SupportBean group by LongPrimitive]");
	    }
示例#14
0
        public void TestSchemaXMLTypes()
        {
            Configuration configuration = SupportConfigFactory.GetConfiguration();
            ConfigurationEventTypeXMLDOM eventTypeMeta = new ConfigurationEventTypeXMLDOM();

            eventTypeMeta.RootElementName = "typesEvent";
            String schemaUri = ResourceManager.ResolveResourceURL(CLASSLOADER_SCHEMA_URI).ToString();

            eventTypeMeta.SchemaResource = schemaUri;
            configuration.AddEventType("TestTypesEvent", eventTypeMeta);

            _epService = EPServiceProviderManager.GetDefaultProvider(configuration);
            _epService.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(_epService, GetType(), GetType().FullName);
            }

            String      stmtSelectWild = "select * from TestTypesEvent";
            EPStatement wildStmt       = _epService.EPAdministrator.CreateEPL(stmtSelectWild);
            EventType   type           = wildStmt.EventType;

            EventTypeAssertionUtil.AssertConsistency(type);

            Object[][] types = new Object[][] {
                new object[] { "attrNonPositiveInteger", typeof(int?) },
                new object[] { "attrNonNegativeInteger", typeof(int?) },
                new object[] { "attrNegativeInteger", typeof(int?) },
                new object[] { "attrPositiveInteger", typeof(int?) },
                new object[] { "attrLong", typeof(long?) },
                new object[] { "attrUnsignedLong", typeof(ulong?) },
                new object[] { "attrInt", typeof(int?) },
                new object[] { "attrUnsignedInt", typeof(uint?) },
                new object[] { "attrDecimal", typeof(double?) },
                new object[] { "attrInteger", typeof(int?) },
                new object[] { "attrFloat", typeof(float?) },
                new object[] { "attrDouble", typeof(double?) },
                new object[] { "attrString", typeof(string) },
                new object[] { "attrShort", typeof(short?) },
                new object[] { "attrUnsignedShort", typeof(ushort?) },
                new object[] { "attrByte", typeof(byte?) },
                new object[] { "attrUnsignedByte", typeof(byte?) },
                new object[] { "attrBoolean", typeof(bool?) },
                new object[] { "attrDateTime", typeof(string) },
                new object[] { "attrDate", typeof(string) },
                new object[] { "attrTime", typeof(string) }
            };

            for (int i = 0; i < types.Length; i++)
            {
                String name = types[i][0].ToString();
                EventPropertyDescriptor desc = type.GetPropertyDescriptor(name);
                Type expected = (Type)types[i][1];
                Assert.AreEqual(expected, desc.PropertyType, "Failed for " + name);
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
        public void TestPartitioned()
        {
            Configuration config = SupportConfigFactory.GetConfiguration();

            config.AddEventType <SupportRecogBean>("MyEvent");
            EPServiceProvider epService = EPServiceProviderManager.GetDefaultProvider(config);

            epService.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(epService, GetType(), GetType().FullName);
            }

            SendTimer(0, epService);
            String[] fields = "a,b0,b1,lastb".Split(',');
            String   text   = "select * from MyEvent.win:keepall() " +
                              "match_recognize (" +
                              "  partition by Cat " +
                              "  measures A.TheString as a, B[0].TheString as b0, B[1].TheString as b1, Last(B.TheString) as lastb" +
                              "  pattern (A B*) " +
                              "  INTERVAL 10 seconds " +
                              "  define " +
                              "    A as A.TheString like 'A%'," +
                              "    B as B.TheString like 'B%'" +
                              ") order by a, b0, b1, lastb";

            EPStatement stmt     = epService.EPAdministrator.CreateEPL(text);
            var         listener = new SupportUpdateListener();

            stmt.Events += listener.Update;

            SendTimer(1000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("A1", "C1", 1));

            SendTimer(1000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("A2", "C2", 2));

            SendTimer(2000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("A3", "C3", 3));

            SendTimer(3000, epService);
            epService.EPRuntime.SendEvent(new SupportRecogBean("A4", "C4", 4));

            epService.EPRuntime.SendEvent(new SupportRecogBean("B1", "C3", 5));
            epService.EPRuntime.SendEvent(new SupportRecogBean("B2", "C1", 6));
            epService.EPRuntime.SendEvent(new SupportRecogBean("B3", "C1", 7));
            epService.EPRuntime.SendEvent(new SupportRecogBean("B4", "C4", 7));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields,
                                              new Object[][]
            {
                new[] { "A1", "B2", "B3", "B3" },
                new[] { "A2", null, null, null },
                new[] { "A3", "B1", null, "B1" },
                new[] { "A4", "B4", null, "B4" }
            });

            SendTimer(10999, epService);
            Assert.IsFalse(listener.IsInvoked);

            SendTimer(11000, epService);
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields,
                                              new[]
            {
                new Object[] { "A1", "B2", "B3", "B3" },
                new[] { "A2", null, null, null }
            });

            SendTimer(11999, epService);
            Assert.IsFalse(listener.IsInvoked);

            SendTimer(12000, epService);
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields,
                                              new[] { new Object[] { "A3", "B1", null, "B1" } });

            SendTimer(13000, epService);
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields,
                                              new[] { new Object[] { "A4", "B4", null, "B4" } });

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
        public UniformPair <ISet <MultiKey <EventBean> > > Join(EventBean[][] newDataPerStream, EventBean[][] oldDataPerStream, ExprEvaluatorContext exprEvaluatorContext)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QJoinCompositionHistorical();
            }

            _oldResults.Clear();
            _newResults.Clear();

            // join old data
            for (var i = 0; i < oldDataPerStream.Length; i++)
            {
                if (oldDataPerStream[i] != null)
                {
                    if (InstrumentationHelper.ENABLED)
                    {
                        InstrumentationHelper.Get().QJoinCompositionQueryStrategy(false, i, oldDataPerStream[i]);
                    }
                    _queryStrategies[i].Lookup(oldDataPerStream[i], _oldResults, exprEvaluatorContext);
                    if (InstrumentationHelper.ENABLED)
                    {
                        InstrumentationHelper.Get().AJoinCompositionQueryStrategy();
                    }
                }
            }

            if (_repositories != null)
            {
                // We add and remove data in one call to each index.
                // Most indexes will add first then remove as newdata and olddata may contain the same event.
                // Unique indexes may remove then add.
                for (var stream = 0; stream < newDataPerStream.Length; stream++)
                {
                    for (var j = 0; j < _repositories[stream].Length; j++)
                    {
                        if (InstrumentationHelper.ENABLED)
                        {
                            InstrumentationHelper.Get().QJoinCompositionStepUpdIndex(stream, newDataPerStream[stream], oldDataPerStream[stream]);
                        }
                        _repositories[stream][j].AddRemove(newDataPerStream[stream], oldDataPerStream[stream]);
                        if (InstrumentationHelper.ENABLED)
                        {
                            InstrumentationHelper.Get().AJoinCompositionStepUpdIndex();
                        }
                    }
                }
            }

            // join new data
            for (var i = 0; i < newDataPerStream.Length; i++)
            {
                if (newDataPerStream[i] != null)
                {
                    if (InstrumentationHelper.ENABLED)
                    {
                        InstrumentationHelper.Get().QJoinCompositionQueryStrategy(true, i, newDataPerStream[i]);
                    }
                    _queryStrategies[i].Lookup(newDataPerStream[i], _newResults, exprEvaluatorContext);
                    if (InstrumentationHelper.ENABLED)
                    {
                        InstrumentationHelper.Get().AJoinCompositionQueryStrategy();
                    }
                }
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AJoinCompositionHistorical(_newResults, _oldResults);
            }
            return(new UniformPair <ISet <MultiKey <EventBean> > >(_newResults, _oldResults));
        }
示例#17
0
        private void RunTest(PatternTestStyle testStyle)
        {
            Configuration config = SupportConfigFactory.GetConfiguration();

            config.AddEventType("A", typeof(SupportBean_A));
            config.AddEventType("B", typeof(SupportBean_B));
            config.AddEventType("C", typeof(SupportBean_C));
            config.AddEventType("D", typeof(SupportBean_D));
            config.AddEventType("E", typeof(SupportBean_E));
            config.AddEventType("F", typeof(SupportBean_F));
            config.AddEventType("G", typeof(SupportBean_G));
            EPServiceProvider serviceProvider = EPServiceProviderManager.GetDefaultProvider(config);

            serviceProvider.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(serviceProvider, _testClass, _testMethodName);
            }

            EPRuntime runtime = serviceProvider.EPRuntime;

            // Send the start time to the runtime
            if (_sendEventCollection.GetTime(EventCollection.ON_START_EVENT_ID) != null)
            {
                TimerEvent startTime = new CurrentTimeEvent(_sendEventCollection.GetTime(EventCollection.ON_START_EVENT_ID).Value);
                runtime.SendEvent(startTime);
                Log.Debug(".runTest Start time is " + startTime);
            }

            // Set up expression filters and match listeners

            int index = 0;

            foreach (EventExpressionCase descriptor in _caseList.Results)
            {
                String expressionText        = descriptor.ExpressionText;
                EPStatementObjectModel model = descriptor.ObjectModel;

                EPStatement statement = null;

                try
                {
                    if (model != null)
                    {
                        statement = serviceProvider.EPAdministrator.Create(model, "name--" + expressionText);
                    }
                    else
                    {
                        if (testStyle == PatternTestStyle.USE_PATTERN_LANGUAGE)
                        {
                            statement = serviceProvider.EPAdministrator.CreatePattern(expressionText, "name--" + expressionText);
                        }
                        else if (testStyle == PatternTestStyle.USE_EPL)
                        {
                            String text = "@Audit('pattern') @Audit('pattern-instances') select * from pattern [" + expressionText + "]";
                            statement      = serviceProvider.EPAdministrator.CreateEPL(text);
                            expressionText = text;
                        }
                        else if (testStyle == PatternTestStyle.USE_EPL_AND_CONSUME_NOCHECK)
                        {
                            String text = "select * from pattern @DiscardPartialsOnMatch @SuppressOverlappingMatches [" + expressionText + "]";
                            statement      = serviceProvider.EPAdministrator.CreateEPL(text);
                            expressionText = text;
                        }
                        else if (testStyle == PatternTestStyle.COMPILE_TO_MODEL)
                        {
                            String text = "select * from pattern [" + expressionText + "]";
                            EPStatementObjectModel mymodel = serviceProvider.EPAdministrator.CompileEPL(text);
                            statement      = serviceProvider.EPAdministrator.Create(mymodel);
                            expressionText = text;
                        }
                        else if (testStyle == PatternTestStyle.COMPILE_TO_EPL)
                        {
                            String text = "select * from pattern [" + expressionText + "]";
                            EPStatementObjectModel mymodel = serviceProvider.EPAdministrator.CompileEPL(text);
                            String reverse = mymodel.ToEPL();
                            statement      = serviceProvider.EPAdministrator.CreateEPL(reverse);
                            expressionText = reverse;
                        }
                        else
                        {
                            throw new ArgumentException("Unknown test style");
                        }
                    }
                }
                catch (Exception ex)
                {
                    String text = expressionText;
                    if (model != null)
                    {
                        text = "Model: " + model.ToEPL();
                    }
                    Log.Fatal(".runTest Failed to create statement for style " + testStyle + " pattern expression=" + text, ex);
                    Assert.Fail(".runTest Failed to create statement for style " + testStyle + " pattern expression=" + text);
                }

                // We stop the statement again and start after the first listener was added.
                // Thus we can handle patterns that fireStatementStopped on startup.
                statement.Stop();

                _expressions[index]         = statement;
                _expressions[index].Events += _listeners[index].Update;

                // Start the statement again: listeners now got called for on-start events such as for a "not"
                statement.Start();

                index++;
            }

            // Some expressions may fireStatementStopped as soon as they are started, such as a "not b()" expression, for example.
            // Check results for any such listeners/expressions.
            // NOTE: For EPL statements we do not support calling listeners when a pattern that fires upon start.
            // Reason is that this should not be a relevant functionality of a pattern, the start pattern
            // event itself cannot carry any information and is thus ignore. Note subsequent events
            // generated by the same pattern are fine.
            int totalEventsReceived = 0;

            if (testStyle != PatternTestStyle.USE_PATTERN_LANGUAGE)
            {
                ClearListenerEvents();
                totalEventsReceived += CountExpectedEvents(EventCollection.ON_START_EVENT_ID);
            }
            else    // Patterns do need to handle event publishing upon pattern expression start (patterns that turn true right away)
            {
                CheckResults(testStyle, EventCollection.ON_START_EVENT_ID);
                totalEventsReceived += CountListenerEvents();
                ClearListenerEvents();
            }

            // Send actual test events
            foreach (var entry in _sendEventCollection)
            {
                String eventId = entry.Key;

                // Manipulate the time when this event was send
                if (_sendEventCollection.GetTime(eventId) != null)
                {
                    TimerEvent currentTimeEvent = new CurrentTimeEvent(_sendEventCollection.GetTime(eventId).Value);
                    runtime.SendEvent(currentTimeEvent);
                    Log.Debug(".runTest Sending event " + entry.Key
                              + " = " + entry.Value +
                              "  timed " + currentTimeEvent);
                }

                // Send event itself
                runtime.SendEvent(entry.Value);

                // Check expected results for this event
                if (testStyle != PatternTestStyle.USE_EPL_AND_CONSUME_NOCHECK)
                {
                    CheckResults(testStyle, eventId);

                    // Count and clear the list of events that each listener has received
                    totalEventsReceived += CountListenerEvents();
                }

                ClearListenerEvents();
            }

            // Count number of expected matches
            int totalExpected = 0;

            foreach (EventExpressionCase descriptor in _caseList.Results)
            {
                totalExpected += descriptor.ExpectedResults.Values.Sum(events => events.Count);
            }

            if (totalExpected != totalEventsReceived && testStyle != PatternTestStyle.USE_EPL_AND_CONSUME_NOCHECK)
            {
                Log.Debug(".test Count expected does not match count received, expected=" + totalExpected +
                          " received=" + totalEventsReceived);
                Assert.Fail();
            }

            // Kill all expressions
            foreach (EPStatement expression in _expressions)
            {
                expression.RemoveAllEventHandlers();
            }

            // Send test events again to also test that all were indeed killed
            foreach (var entry in _sendEventCollection)
            {
                runtime.SendEvent(entry.Value);
            }

            // Make sure all listeners are still at zero
            foreach (SupportUpdateListener listener in _listeners)
            {
                if (listener.NewDataList.Count > 0)
                {
                    Log.Debug(".test A match was received after stopping all expressions");
                    Assert.Fail();
                }
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
示例#18
0
 public void TestGetExcludedFilesReturnsEmpty(string[] excludedFiles)
 {
     Assert.False(InstrumentationHelper.GetExcludedFiles(excludedFiles)?.Any());
 }
示例#19
0
        public void TestBuiltin()
        {
            var configuration = SupportConfigFactory.GetConfiguration();

            configuration.AddEventType("Bean", typeof(SupportBean).FullName);
            configuration.AddImport(typeof(MyAnnotationNestableValuesAttribute).Namespace);
            _epService = EPServiceProviderManager.GetDefaultProvider(configuration);
            _epService.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(_epService, GetType(), GetType().FullName);
            }

            var stmtText = "@Name('MyTestStmt') @Description('MyTestStmt description') @Tag(Name=\"UserId\", Value=\"Value\") select * from Bean";
            var stmt     = _epService.EPAdministrator.CreateEPL(stmtText);

            Assert.IsTrue((((EPStatementSPI)stmt).IsNameProvided));
            RunAssertion(stmt);
            stmt.Dispose();
            var name = (NameAttribute)AnnotationUtil.FindAttribute(stmt.Annotations, typeof(NameAttribute));

            Assert.AreEqual("MyTestStmt", name.Value);

            // try lowercase
            var stmtTextLower = "@Name('MyTestStmt') @Description('MyTestStmt description') @Tag(Name=\"UserId\", Value=\"Value\") select * from Bean";

            stmt = _epService.EPAdministrator.CreateEPL(stmtTextLower);
            RunAssertion(stmt);
            stmt.Dispose();

            // try pattern
            stmtText = "@Name('MyTestStmt') @Description('MyTestStmt description') @Tag(Name='UserId', Value='Value') every Bean";
            stmt     = _epService.EPAdministrator.CreatePattern(stmtText);
            RunAssertion(stmt);
            stmt.Dispose();

            stmtText = "@Name('MyTestStmt') @Description('MyTestStmt description') @Tag(Name=\"UserId\", Value=\"Value\") every Bean";
            stmt     = _epService.EPAdministrator.CreatePattern(stmtText);
            RunAssertion(stmt);

            _epService.EPAdministrator.CreateEPL("@Hint('ITERATE_ONLY') select * from Bean");
            _epService.EPAdministrator.CreateEPL("@Hint('ITERATE_ONLY,DISABLE_RECLAIM_GROUP') select * from Bean");
            _epService.EPAdministrator.CreateEPL("@Hint('ITERATE_ONLY,DISABLE_RECLAIM_GROUP,ITERATE_ONLY') select * from Bean");
            _epService.EPAdministrator.CreateEPL("@Hint('  iterate_only ') select * from Bean");

            // test statement name override
            stmtText = "@Name('MyAnnotatedName') select * from Bean";
            stmt     = _epService.EPAdministrator.CreateEPL(stmtText, "MyABCStmt");
            Assert.AreEqual("MyABCStmt", stmt.Name);

            // hint tests
            Assert.IsNull(HintEnum.DISABLE_RECLAIM_GROUP.GetHint(null));
            Assert.IsNull(HintEnum.DISABLE_RECLAIM_GROUP.GetHint(new Attribute[0]));

            var annos =
                _epService.EPAdministrator.CreateEPL("@Hint('DISABLE_RECLAIM_GROUP') select * from Bean").Annotations.ToArray();

            Assert.AreEqual("DISABLE_RECLAIM_GROUP", HintEnum.DISABLE_RECLAIM_GROUP.GetHint(annos).Value);

            annos = _epService.EPAdministrator.CreateEPL("@Hint('ITERATE_ONLY,ITERATE_ONLY,DISABLE_RECLAIM_GROUP,ITERATE_ONLY') select * from Bean").Annotations.ToArray();
            Assert.AreEqual("ITERATE_ONLY,ITERATE_ONLY,DISABLE_RECLAIM_GROUP,ITERATE_ONLY", HintEnum.DISABLE_RECLAIM_GROUP.GetHint(annos).Value);

            annos = _epService.EPAdministrator.CreateEPL("@Hint('ITERATE_ONLY,reclaim_group_aged=10') select * from Bean").Annotations.ToArray();
            var hint = HintEnum.RECLAIM_GROUP_AGED.GetHint(annos);

            Assert.AreEqual("10", HintEnum.RECLAIM_GROUP_AGED.GetHintAssignedValue(hint));

            annos = _epService.EPAdministrator.CreateEPL("@Hint('reclaim_group_aged=11') select * from Bean").Annotations.ToArray();
            hint  = HintEnum.RECLAIM_GROUP_AGED.GetHint(annos);
            Assert.AreEqual("11", HintEnum.RECLAIM_GROUP_AGED.GetHintAssignedValue(hint));

            annos = _epService.EPAdministrator.CreateEPL("@Hint('index(one, two)') select * from Bean").Annotations.ToArray();
            Assert.AreEqual("one, two", HintEnum.INDEX.GetHintAssignedValues(annos)[0]);

            // NoLock
            stmt = _epService.EPAdministrator.CreateEPL("@NoLock select * from Bean");
            Assert.NotNull(AnnotationUtil.FindAttribute(stmt.Annotations.ToArray(), typeof(NoLockAttribute)));
            Assert.AreEqual(1, AnnotationUtil.FindAttributes(stmt.Annotations.ToArray(), typeof(NoLockAttribute)).Count);

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
示例#20
0
        public void TestIsModuleExcludedWithSingleMismatchFilter(string filter)
        {
            var result = InstrumentationHelper.IsModuleExcluded("Module.dll", new[] { filter });

            Assert.False(result);
        }
示例#21
0
        public void TestSPI()
        {
            var configuration = SupportConfigFactory.GetConfiguration();

            configuration.AddEventType("Bean", typeof(SupportBean).FullName);
            _epService = EPServiceProviderManager.GetDefaultProvider(configuration);
            _epService.Initialize();
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.StartTest(_epService, GetType(), GetType().FullName);
            }

            _epService.EPAdministrator.Configuration.AddImport("com.espertech.esper.regression.client");

            var testdata = new String[][] {
                new String[]
                {
                    "@MyAnnotationSimple /* test */ select * from Bean",
                    "/* test */ select * from Bean"
                },
                new String[]
                {
                    "/* test */ select * from Bean",
                    "/* test */ select * from Bean"
                },
                new String[]
                {
                    "@MyAnnotationValueArray(Value={1, 2, 3}, IntArray={4, 5}, DoubleArray={}, StringArray={\"X\"})    select * from Bean",
                    "select * from Bean"
                },
                new String[]
                {
                    "@MyAnnotationSimple\nselect * from Bean",
                    "select * from Bean"
                },
                new String[]
                {
                    "@MyAnnotationSimple\n@MyAnnotationSimple\nselect * from Bean",
                    "select * from Bean"
                },
                new String[]
                {
                    "@MyAnnotationValueArray(Value={1, 2, 3}, IntArray={4, 5}, DoubleArray={}, \nStringArray={\"X\"})\n" +
                    "/* Test */ select * \nfrom Bean",
                    "/* Test */ select * \r\nfrom Bean"
                },
            };

            for (var i = 0; i < testdata.Length; i++)
            {
                var innerStmt = _epService.EPAdministrator.CreateEPL(testdata[i][0]) as EPStatementSPI;
                Assert.That(innerStmt, Is.Not.Null);
                Assert.AreEqual(RemoveNewlines(testdata[i][1]), RemoveNewlines(innerStmt.ExpressionNoAnnotations), "Error on " + testdata[i][0]);
                Assert.IsFalse(innerStmt.IsNameProvided);
            }

            var stmt = _epService.EPAdministrator.CreateEPL(testdata[0][0], "nameProvided");

            Assert.IsTrue(((EPStatementSPI)stmt).IsNameProvided);

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
        }
示例#22
0
        public void TestIsTypeExcludedWithoutFilter()
        {
            var result = InstrumentationHelper.IsTypeExcluded("Module.dll", "a.b.Dto", new string[0]);

            Assert.False(result);
        }
示例#23
0
        public void TestAllAggFunctions()
        {
            var fields = "cavedev,cavg,cmax,cmedian,cmin,cstddev,csum,cfmaxever,cfminever".Split(',');
            var stmt   = (EPStatementSPI)_epService.EPAdministrator.CreateEPL("select " +
                                                                              "avedev(IntBoxed, BoolPrimitive) as cavedev," +
                                                                              "avg(IntBoxed, BoolPrimitive) as cavg, " +
                                                                              "fmax(IntBoxed, BoolPrimitive) as cmax, " +
                                                                              "median(IntBoxed, BoolPrimitive) as cmedian, " +
                                                                              "fmin(IntBoxed, BoolPrimitive) as cmin, " +
                                                                              "stddev(IntBoxed, BoolPrimitive) as cstddev, " +
                                                                              "sum(IntBoxed, BoolPrimitive) as csum," +
                                                                              "fmaxever(IntBoxed, BoolPrimitive) as cfmaxever, " +
                                                                              "fminever(IntBoxed, BoolPrimitive) as cfminever " +
                                                                              "from SupportBean.win:length(3)");

            stmt.AddListener(_listener);

            _epService.EPRuntime.SendEvent(MakeBean(100, false));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { null, null, null, null, null, null, null, null, null });

            _epService.EPRuntime.SendEvent(MakeBean(10, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 0.0d, 10.0, 10, 10.0, 10, null, 10, 10, 10 });

            _epService.EPRuntime.SendEvent(MakeBean(11, false));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 0.0d, 10.0, 10, 10.0, 10, null, 10, 10, 10 });

            _epService.EPRuntime.SendEvent(MakeBean(20, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 5.0d, 15.0, 20, 15.0, 10, 7.0710678118654755, 30, 20, 10 });

            _epService.EPRuntime.SendEvent(MakeBean(30, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 5.0d, 25.0, 30, 25.0, 20, 7.0710678118654755, 50, 30, 10 });

            // Test all remaining types of "sum"
            stmt.Dispose();
            fields = "c1,c2,c3,c4".Split(',');
            stmt   = (EPStatementSPI)_epService.EPAdministrator.CreateEPL("select " +
                                                                          "sum(FloatPrimitive, BoolPrimitive) as c1," +
                                                                          "sum(DoublePrimitive, BoolPrimitive) as c2, " +
                                                                          "sum(LongPrimitive, BoolPrimitive) as c3, " +
                                                                          "sum(shortPrimitive, BoolPrimitive) as c4 " +
                                                                          "from SupportBean.win:length(2)");
            stmt.AddListener(_listener);

            _epService.EPRuntime.SendEvent(MakeBean(2f, 3d, 4L, (short)5, false));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { null, null, null, null });

            _epService.EPRuntime.SendEvent(MakeBean(3f, 4d, 5L, (short)6, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 3f, 4d, 5L, 6 });

            _epService.EPRuntime.SendEvent(MakeBean(4f, 5d, 6L, (short)7, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 7f, 9d, 11L, 13 });

            _epService.EPRuntime.SendEvent(MakeBean(1f, 1d, 1L, (short)1, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 5f, 6d, 7L, 8 });

            // Test min/max-ever
            stmt.Dispose();
            fields = "c1,c2".Split(',');
            stmt   = (EPStatementSPI)_epService.EPAdministrator.CreateEPL("select " +
                                                                          "fmax(IntBoxed, BoolPrimitive) as c1," +
                                                                          "fmin(IntBoxed, BoolPrimitive) as c2 " +
                                                                          "from SupportBean");
            stmt.AddListener(_listener);
            Assert.IsFalse(stmt.StatementContext.IsStatelessSelect);

            _epService.EPRuntime.SendEvent(MakeBean(10, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 10, 10 });

            _epService.EPRuntime.SendEvent(MakeBean(20, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 20, 10 });

            _epService.EPRuntime.SendEvent(MakeBean(8, false));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 20, 10 });

            _epService.EPRuntime.SendEvent(MakeBean(7, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 20, 7 });

            _epService.EPRuntime.SendEvent(MakeBean(30, false));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 20, 7 });

            _epService.EPRuntime.SendEvent(MakeBean(40, true));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { 40, 7 });

            // test big decimal big integer
            stmt.Dispose();
            fields = "c1,c2,c3".Split(',');
            stmt   = (EPStatementSPI)_epService.EPAdministrator.CreateEPL("select " +
                                                                          "avg(DecimalOne, BigInt < 100) as c1," +
                                                                          "sum(DecimalOne, BigInt < 100) as c2, " +
                                                                          "sum(BigInt, BigInt < 100) as c3 " +
                                                                          "from SupportBeanNumeric.win:length(2)");
            stmt.AddListener(_listener);

            _epService.EPRuntime.SendEvent(new SupportBeanNumeric(new BigInteger(10), 20m));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { (decimal)20, (decimal)20, new BigInteger(10) });

            _epService.EPRuntime.SendEvent(new SupportBeanNumeric(new BigInteger(101), 101m));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { (decimal)20, (decimal)20, new BigInteger(10) });

            _epService.EPRuntime.SendEvent(new SupportBeanNumeric(new BigInteger(20), 40m));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { (decimal)40, (decimal)40, new BigInteger(20) });

            _epService.EPRuntime.SendEvent(new SupportBeanNumeric(new BigInteger(30), 50m));
            EPAssertionUtil.AssertProps(_listener.AssertOneGetNewAndReset(), fields, new object[] { (decimal)45, (decimal)90, new BigInteger(50) });

            stmt.Dispose();
            var epl = "select " +
                      "avedev(distinct IntBoxed,BoolPrimitive) as cavedev, " +
                      "avg(distinct IntBoxed,BoolPrimitive) as cavg, " +
                      "fmax(distinct IntBoxed,BoolPrimitive) as cmax, " +
                      "median(distinct IntBoxed,BoolPrimitive) as cmedian, " +
                      "fmin(distinct IntBoxed,BoolPrimitive) as cmin, " +
                      "stddev(distinct IntBoxed,BoolPrimitive) as cstddev, " +
                      "sum(distinct IntBoxed,BoolPrimitive) as csum " +
                      "from SupportBean.win:length(3)";

            stmt = (EPStatementSPI)_epService.EPAdministrator.CreateEPL(epl);
            stmt.AddListener(_listener);

            RunAssertionDistinct();

            // test SODA
            stmt.Dispose();
            var model = _epService.EPAdministrator.CompileEPL(epl);

            Assert.AreEqual(epl, model.ToEPL());
            stmt = (EPStatementSPI)_epService.EPAdministrator.Create(model);
            stmt.AddListener(_listener);
            Assert.AreEqual(epl, stmt.Text);

            RunAssertionDistinct();

            // test math context for big decimal and average divide
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }
            var config = SupportConfigFactory.GetConfiguration();

            config.EngineDefaults.ExpressionConfig.MathContext = new MathContext(MidpointRounding.AwayFromZero, 2);
            config.AddEventType(typeof(SupportBeanNumeric));
            var engineMathCtx = EPServiceProviderManager.GetDefaultProvider(config);

            engineMathCtx.Initialize();

            engineMathCtx.EPAdministrator.CreateEPL("select avg(DecimalOne) as c0 from SupportBeanNumeric").AddListener(_listener);
            engineMathCtx.EPRuntime.SendEvent(new SupportBeanNumeric(null, MakeDecimal(0, 2, MidpointRounding.AwayFromZero)));
            engineMathCtx.EPRuntime.SendEvent(new SupportBeanNumeric(null, MakeDecimal(0, 2, MidpointRounding.AwayFromZero)));
            engineMathCtx.EPRuntime.SendEvent(new SupportBeanNumeric(null, MakeDecimal(1, 2, MidpointRounding.AwayFromZero)));
            Assert.AreEqual(0.33, _listener.GetAndResetLastNewData()[0].Get("c0").AsDouble());

            engineMathCtx.Dispose();
        }
示例#24
0
        public void TestIsTypeExcludedWithFilter(string filter)
        {
            var result = InstrumentationHelper.IsTypeExcluded("Module.dll", "a.b.Dto", new[] { filter });

            Assert.True(result);
        }
        /// <summary>
        /// This process (update) method is for participation in a join.
        /// </summary>
        /// <param name="newEvents">- new events</param>
        /// <param name="oldEvents">- old events</param>
        public override void Process(
            ISet <MultiKey <EventBean> > newEvents,
            ISet <MultiKey <EventBean> > oldEvents,
            ExprEvaluatorContext exprEvaluatorContext)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QOutputProcessWConditionJoin(newEvents, oldEvents);
            }

            if ((ExecutionPathDebugLog.IsEnabled) && (Log.IsDebugEnabled))
            {
                Log.Debug(
                    ".process Received update, " +
                    "  newData.Length==" + ((newEvents == null) ? 0 : newEvents.Count) +
                    "  oldData.Length==" + ((oldEvents == null) ? 0 : oldEvents.Count));
            }

            // add the incoming events to the event batches
            if (_parent.HasAfter)
            {
                bool afterSatisfied = base.CheckAfterCondition(newEvents, _parent.StatementContext);
                if (!afterSatisfied)
                {
                    if (!_parent.IsUnaggregatedUngrouped)
                    {
                        AddToChangeset(newEvents, oldEvents, _deltaSet);
                    }
                    if (InstrumentationHelper.ENABLED)
                    {
                        InstrumentationHelper.Get().AOutputProcessWConditionJoin(false);
                    }
                    return;
                }
                else
                {
                    AddToChangeset(newEvents, oldEvents, _deltaSet);
                }
            }
            else
            {
                AddToChangeset(newEvents, oldEvents, _deltaSet);
            }

            int newEventsSize = 0;

            if (newEvents != null)
            {
                newEventsSize = newEvents.Count;
            }

            int oldEventsSize = 0;

            if (oldEvents != null)
            {
                oldEventsSize = oldEvents.Count;
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QOutputRateConditionUpdate(newEventsSize, oldEventsSize);
            }
            _outputCondition.UpdateOutputCondition(newEventsSize, oldEventsSize);
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AOutputRateConditionUpdate();
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AOutputProcessWConditionJoin(true);
            }
        }
示例#26
0
        public override void Update(EventBean[] newData, EventBean[] oldData)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QViewProcessIRStream(this, _dataWindowViewFactory.ViewName, newData, oldData);
            }

            bool fireBatch = false;

            // remove points from data window
            if (oldData != null)
            {
                foreach (EventBean anOldData in oldData)
                {
                    Window.Remove(anOldData);
                }
                if (AggregationService != null)
                {
                    AggregationService.ApplyLeave(oldData, null, AgentInstanceContext);
                }

                if (Window.IsNotEmpty())
                {
                    OldestEvent = Window.First();
                }
                else
                {
                    OldestEvent = null;
                }

                fireBatch = EvaluateExpression(null, Window.Count);
            }

            // add data points to the window
            int numEventsInBatch = -1;

            if (newData != null && newData.Length > 0)
            {
                if (Window.IsEmpty())
                {
                    OldestEventTimestamp = AgentInstanceContext.StatementContext.SchedulingService.Time;
                }
                NewestEventTimestamp = AgentInstanceContext.StatementContext.SchedulingService.Time;
                if (OldestEvent == null)
                {
                    OldestEvent = newData[0];
                }

                foreach (EventBean newEvent in newData)
                {
                    Window.Add(newEvent);
                    if (AggregationService != null)
                    {
                        AggregationService.ApplyEnter(new EventBean[] { newEvent }, null, AgentInstanceContext);
                    }
                    NewestEvent = newEvent;
                    if (!fireBatch)
                    {
                        fireBatch = EvaluateExpression(newEvent, Window.Count);
                        if (fireBatch && !_dataWindowViewFactory.IsIncludeTriggeringEvent)
                        {
                            numEventsInBatch = Window.Count - 1;
                        }
                    }
                }
            }

            // may fire the batch
            if (fireBatch)
            {
                Expire(numEventsInBatch);
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AViewProcessIRStream();
            }
        }
示例#27
0
 public bool CanInstrument() => InstrumentationHelper.HasPdb(_module);
示例#28
0
        public override void HandleMatching(EventBean[] triggerEvents, EventBean[] matchingEvents)
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().QInfraOnAction(OnTriggerType.ON_SELECT, triggerEvents, matchingEvents);
            }

            EventBean[] newData;

            // clear state from prior results
            _resultSetProcessor.Clear();

            // build join result
            // use linked hash set to retain order of join results for last/first/window to work most intuitively
            ISet <MultiKey <EventBean> > newEvents = NamedWindowOnSelectView.BuildJoinResult(triggerEvents, matchingEvents);

            // process matches
            UniformPair <EventBean[]> pair = _resultSetProcessor.ProcessJoinResult(newEvents, Collections.GetEmptySet <MultiKey <EventBean> >(), false);

            newData = (pair != null ? pair.First : null);

            if (_parent.IsDistinct)
            {
                newData = EventBeanUtility.GetDistinctByProp(newData, _parent.EventBeanReader);
            }

            if (_parent.InternalEventRouter != null)
            {
                if (newData != null)
                {
                    for (int i = 0; i < newData.Length; i++)
                    {
                        if (_audit)
                        {
                            AuditPath.AuditInsertInto(ExprEvaluatorContext.EngineURI, ExprEvaluatorContext.StatementName, newData[i]);
                        }
                        _parent.InternalEventRouter.Route(newData[i], _parent.StatementHandle, _parent.InternalEventRouteDest, ExprEvaluatorContext, false);
                    }
                }
            }

            // The on-select listeners receive the events selected
            if ((newData != null) && (newData.Length > 0))
            {
                // And post only if we have listeners/subscribers that need the data
                if (_parent.StatementResultService.IsMakeNatural || _parent.StatementResultService.IsMakeSynthetic)
                {
                    UpdateChildren(newData, null);
                }
            }

            // clear state from prior results
            _resultSetProcessor.Clear();

            // Events to delete are indicated via old data
            if (_deleteAndSelect)
            {
                foreach (EventBean @event in matchingEvents)
                {
                    TableStateInstance.DeleteEvent(@event);
                }
            }

            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.Get().AInfraOnAction();
            }
        }
示例#29
0
        public CoverageResult GetCoverageResult()
        {
            CalculateCoverage();

            Modules modules = new Modules();

            foreach (var result in _results)
            {
                Documents documents = new Documents();
                foreach (var doc in result.Documents.Values)
                {
                    // Construct Line Results
                    foreach (var line in doc.Lines.Values)
                    {
                        if (documents.TryGetValue(doc.Path, out Classes classes))
                        {
                            if (classes.TryGetValue(line.Class, out Methods methods))
                            {
                                if (methods.TryGetValue(line.Method, out Method method))
                                {
                                    documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                                }
                                else
                                {
                                    documents[doc.Path][line.Class].Add(line.Method, new Method());
                                    documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                                }
                            }
                            else
                            {
                                documents[doc.Path].Add(line.Class, new Methods());
                                documents[doc.Path][line.Class].Add(line.Method, new Method());
                                documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                            }
                        }
                        else
                        {
                            documents.Add(doc.Path, new Classes());
                            documents[doc.Path].Add(line.Class, new Methods());
                            documents[doc.Path][line.Class].Add(line.Method, new Method());
                            documents[doc.Path][line.Class][line.Method].Lines.Add(line.Number, line.Hits);
                        }
                    }

                    // Construct Branch Results
                    foreach (var branch in doc.Branches.Values)
                    {
                        if (documents.TryGetValue(doc.Path, out Classes classes))
                        {
                            if (classes.TryGetValue(branch.Class, out Methods methods))
                            {
                                if (methods.TryGetValue(branch.Method, out Method method))
                                {
                                    method.Branches.Add(new BranchInfo
                                    {
                                        Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                    }
                                                        );
                                }
                                else
                                {
                                    documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                                    documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                                    {
                                        Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                    }
                                                                                                  );
                                }
                            }
                            else
                            {
                                documents[doc.Path].Add(branch.Class, new Methods());
                                documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                                documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                                {
                                    Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                                }
                                                                                              );
                            }
                        }
                        else
                        {
                            documents.Add(doc.Path, new Classes());
                            documents[doc.Path].Add(branch.Class, new Methods());
                            documents[doc.Path][branch.Class].Add(branch.Method, new Method());
                            documents[doc.Path][branch.Class][branch.Method].Branches.Add(new BranchInfo
                            {
                                Line = branch.Number, Hits = branch.Hits, Offset = branch.Offset, EndOffset = branch.EndOffset, Path = branch.Path, Ordinal = branch.Ordinal
                            }
                                                                                          );
                        }
                    }
                }

                modules.Add(Path.GetFileName(result.ModulePath), documents);
                InstrumentationHelper.RestoreOriginalModule(result.ModulePath, _identifier);
            }

            var coverageResult = new CoverageResult {
                Identifier = _identifier, Modules = modules, InstrumentedResults = _results
            };

            if (!string.IsNullOrEmpty(_mergeWith) && !string.IsNullOrWhiteSpace(_mergeWith) && File.Exists(_mergeWith))
            {
                string json = File.ReadAllText(_mergeWith);
                coverageResult.Merge(JsonConvert.DeserializeObject <Modules>(json));
            }

            return(coverageResult);
        }
示例#30
0
        public CoverageResult GetCoverageResult()
        {
            CalculateCoverage();

            Modules modules = new Modules();

            foreach (var result in _results)
            {
                Documents documents = new Documents();
                foreach (var doc in result.Documents)
                {
                    foreach (var line in doc.Lines)
                    {
                        if (documents.TryGetValue(doc.Path, out Classes classes))
                        {
                            if (classes.TryGetValue(line.Class, out Methods methods))
                            {
                                if (methods.TryGetValue(line.Method, out Lines lines))
                                {
                                    documents[doc.Path][line.Class][line.Method].Add(line.Number, new LineInfo {
                                        Hits = line.Hits, IsBranchPoint = line.IsBranchTarget
                                    });
                                }
                                else
                                {
                                    documents[doc.Path][line.Class].Add(line.Method, new Lines());
                                    documents[doc.Path][line.Class][line.Method].Add(line.Number, new LineInfo {
                                        Hits = line.Hits, IsBranchPoint = line.IsBranchTarget
                                    });
                                }
                            }
                            else
                            {
                                documents[doc.Path].Add(line.Class, new Methods());
                                documents[doc.Path][line.Class].Add(line.Method, new Lines());
                                documents[doc.Path][line.Class][line.Method].Add(line.Number, new LineInfo {
                                    Hits = line.Hits, IsBranchPoint = line.IsBranchTarget
                                });
                            }
                        }
                        else
                        {
                            documents.Add(doc.Path, new Classes());
                            documents[doc.Path].Add(line.Class, new Methods());
                            documents[doc.Path][line.Class].Add(line.Method, new Lines());
                            documents[doc.Path][line.Class][line.Method].Add(line.Number, new LineInfo {
                                Hits = line.Hits, IsBranchPoint = line.IsBranchTarget
                            });
                        }
                    }
                }

                modules.Add(result.ModulePath, documents);
                InstrumentationHelper.RestoreOriginalModule(result.ModulePath, _identifier);
            }

            return(new CoverageResult
            {
                Identifier = _identifier,
                Modules = modules
            });
        }