示例#1
0
        public ViewableActivationResult Activate(
            AgentInstanceContext agentInstanceContext,
            bool isSubselect,
            bool isRecoveringResilient)
        {
            PatternAgentInstanceContext patternAgentInstanceContext =
                agentInstanceContext.StatementContext.PatternContextFactory.CreatePatternAgentContext(
                    _patternContext, agentInstanceContext, _hasConsumingFilter);
            EvalRootNode rootNode = EvalNodeUtil.MakeRootNodeFromFactory(_rootFactoryNode, patternAgentInstanceContext);

            EventStream sourceEventStream = _isCanIterate ?
                                            (EventStream) new ZeroDepthStreamIterable(_eventType) :
                                            (EventStream) new ZeroDepthStreamNoIterate(_eventType);
            StatementContext     statementContext = _patternContext.StatementContext;
            PatternMatchCallback callback         = matchEvent =>
            {
                EventBean compositeEvent = statementContext.EventAdapterService.AdapterForTypedMap(
                    matchEvent, _eventType);
                sourceEventStream.Insert(compositeEvent);
            };

            var rootState = (EvalRootState)rootNode.Start(callback, _patternContext, isRecoveringResilient);

            return(new ViewableActivationResult(
                       sourceEventStream, rootState, null, rootState, rootState, _suppressSameEventMatches, _discardPartialsOnMatch, null));
        }
 public override EvalNode MakeEvalNode(
     PatternAgentInstanceContext agentInstanceContext,
     EvalNode parentNode)
 {
     var child = EvalNodeUtil.MakeEvalNodeSingleChild(ChildNode, agentInstanceContext, parentNode);
     return new EvalEveryDistinctNode(this, child, agentInstanceContext);
 }
示例#3
0
 public static void WalkStreamSpecs(StatementSpecRaw spec, ExprNodeSubselectDeclaredDotVisitor visitor)
 {
     // Determine filter streams
     foreach (StreamSpecRaw rawSpec in spec.StreamSpecs)
     {
         if (rawSpec is FilterStreamSpecRaw)
         {
             FilterStreamSpecRaw raw = (FilterStreamSpecRaw)rawSpec;
             foreach (ExprNode filterExpr in raw.RawFilterSpec.FilterExpressions)
             {
                 filterExpr.Accept(visitor);
             }
         }
         if (rawSpec is PatternStreamSpecRaw)
         {
             PatternStreamSpecRaw   patternStreamSpecRaw = (PatternStreamSpecRaw)rawSpec;
             EvalNodeAnalysisResult analysisResult       = EvalNodeUtil.RecursiveAnalyzeChildNodes(patternStreamSpecRaw.EvalFactoryNode);
             foreach (EvalFactoryNode evalNode in analysisResult.ActiveNodes)
             {
                 if (evalNode is EvalFilterFactoryNode)
                 {
                     EvalFilterFactoryNode filterNode = (EvalFilterFactoryNode)evalNode;
                     foreach (ExprNode filterExpr in filterNode.RawFilterSpec.FilterExpressions)
                     {
                         filterExpr.Accept(visitor);
                     }
                 }
             }
         }
     }
 }
示例#4
0
 private static void AddFilters(StreamSpecCompiled[] streams, IList <FilterSpecCompiled> filters, IList <NamedWindowConsumerStreamSpec> namedWindows)
 {
     foreach (StreamSpecCompiled compiled in streams)
     {
         if (compiled is FilterStreamSpecCompiled)
         {
             FilterStreamSpecCompiled c = (FilterStreamSpecCompiled)compiled;
             filters.Add(c.FilterSpec);
         }
         if (compiled is PatternStreamSpecCompiled)
         {
             PatternStreamSpecCompiled     r = (PatternStreamSpecCompiled)compiled;
             EvalNodeAnalysisResult        evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes((r.EvalFactoryNode));
             IList <EvalFilterFactoryNode> filterNodes            = evalNodeAnalysisResult.FilterNodes;
             foreach (EvalFilterFactoryNode filterNode in filterNodes)
             {
                 filters.Add(filterNode.FilterSpec);
             }
         }
         if (compiled is NamedWindowConsumerStreamSpec)
         {
             namedWindows.Add((NamedWindowConsumerStreamSpec)compiled);
         }
     }
 }
示例#5
0
 public override EvalNode MakeEvalNode(
     PatternAgentInstanceContext agentInstanceContext,
     EvalNode parentNode)
 {
     EvalNode[] nodes = EvalNodeUtil.MakeEvalNodeChildren(children, agentInstanceContext, parentNode);
     return new EvalMatchUntilNode(agentInstanceContext, this, nodes[0], nodes.Length == 1 ? null : nodes[1]);
 }
        private static void AddFilters(
            StreamSpecCompiled[] streams,
            IList<FilterSpecCompiled> filters,
            IList<NamedWindowConsumerStreamSpec> namedWindows)
        {
            foreach (var compiled in streams) {
                if (compiled is FilterStreamSpecCompiled) {
                    var c = (FilterStreamSpecCompiled) compiled;
                    filters.Add(c.FilterSpecCompiled);
                }

                if (compiled is PatternStreamSpecCompiled) {
                    var r = (PatternStreamSpecCompiled) compiled;
                    var evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(r.Root);
                    var filterNodes = evalNodeAnalysisResult.FilterNodes;
                    foreach (var filterNode in filterNodes) {
                        filters.Add(filterNode.FilterSpecCompiled);
                    }
                }

                if (compiled is NamedWindowConsumerStreamSpec) {
                    namedWindows.Add((NamedWindowConsumerStreamSpec) compiled);
                }
            }
        }
示例#7
0
        private static MatchEventSpec AnalyzeMatchEvent(EvalFactoryNode relativeNode)
        {
            var taggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
            var arrayEventTypes  = new LinkedHashMap <string, Pair <EventType, string> >();

            // Determine all the filter nodes used in the pattern
            var evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(relativeNode);

            // collect all filters underneath
            foreach (var filterNode in evalNodeAnalysisResult.FilterNodes)
            {
                var optionalTag = filterNode.EventAsName;
                if (optionalTag != null)
                {
                    taggedEventTypes.Put(
                        optionalTag,
                        new Pair <EventType, string>(
                            filterNode.FilterSpec.FilterForEventType, filterNode.FilterSpec.FilterForEventTypeName));
                }
            }

            // collect those filters under a repeat since they are arrays
            var arrayTags = new HashSet <string>();

            foreach (var matchUntilNode in evalNodeAnalysisResult.RepeatNodes)
            {
                var matchUntilAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(matchUntilNode.ChildNodes[0]);
                foreach (var filterNode in matchUntilAnalysisResult.FilterNodes)
                {
                    var optionalTag = filterNode.EventAsName;
                    if (optionalTag != null)
                    {
                        arrayTags.Add(optionalTag);
                    }
                }
            }

            // for each array tag change collection
            foreach (var arrayTag in arrayTags)
            {
                if (taggedEventTypes.Get(arrayTag) != null)
                {
                    arrayEventTypes.Put(arrayTag, taggedEventTypes.Get(arrayTag));
                    taggedEventTypes.Remove(arrayTag);
                }
            }

            return(new MatchEventSpec(taggedEventTypes, arrayEventTypes));
        }
示例#8
0
 private static void AddFilters(StatementSpecRaw spec, IList<FilterSpecRaw> filters) {
     foreach (var raw in spec.StreamSpecs) {
         if (raw is FilterStreamSpecRaw) {
             var r = (FilterStreamSpecRaw) raw;
             filters.Add(r.RawFilterSpec);
         }
         if (raw is PatternStreamSpecRaw) {
             var r = (PatternStreamSpecRaw) raw;
             var evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(r.EvalFactoryNode);
             var filterNodes = evalNodeAnalysisResult.FilterNodes;
             foreach (var filterNode in filterNodes)
             {
                 filters.Add(filterNode.RawFilterSpec);
             }
         }
     }
 }
        public void TestPatternInSetOfVal()
        {
            var text = "select * from pattern [" +
                       "s=" + typeof(SupportBean).FullName + " -> " +
                       typeof(SupportBean).FullName + "(IntPrimitive in (s.IntBoxed, 0))" +
                       "]";

            var raw  = MakeSpec(text);
            var spec = Compile(raw);

            Assert.AreEqual(1, spec.TaggedEventTypes.Count);
            Assert.AreEqual(typeof(SupportBean), spec.TaggedEventTypes.Get("s").First.UnderlyingType);

            var evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(spec.EvalFactoryNode);
            var filters = evalNodeAnalysisResult.FilterNodes;

            Assert.AreEqual(2, filters.Count);

            // node 0
            var filterNode = filters[0];

            Assert.AreEqual(typeof(SupportBean), filterNode.FilterSpec.FilterForEventType.UnderlyingType);
            Assert.AreEqual(0, filterNode.FilterSpec.Parameters.Length);

            // node 1
            filterNode = filters[1];
            Assert.AreEqual(typeof(SupportBean), filterNode.FilterSpec.FilterForEventType.UnderlyingType);
            Assert.AreEqual(1, filterNode.FilterSpec.Parameters.Length);

            var inlist = (FilterSpecParamIn)filterNode.FilterSpec.Parameters[0][0];

            Assert.AreEqual(FilterOperator.IN_LIST_OF_VALUES, inlist.FilterOperator);
            Assert.AreEqual(2, inlist.ListOfValues.Count);

            // in-value 1
            var prop = (InSetOfValuesEventProp)inlist.ListOfValues[0];

            Assert.AreEqual("s", prop.ResultEventAsName);
            Assert.AreEqual("IntBoxed", prop.ResultEventProperty);

            // in-value 1
            var constant = (InSetOfValuesConstant)inlist.ListOfValues[1];

            Assert.AreEqual(0, constant.Constant);
        }
        public void TestRange()
        {
            var text = "select * from pattern [" +
                       "s=" + typeof(SupportBean).FullName + " -> " +
                       typeof(SupportBean).FullName + "(IntPrimitive between s.IntBoxed and 100)" +
                       "]";

            var raw  = MakeSpec(text);
            var spec = Compile(raw);

            Assert.AreEqual(1, spec.TaggedEventTypes.Count);
            Assert.AreEqual(typeof(SupportBean), spec.TaggedEventTypes.Get("s").First.UnderlyingType);

            var evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(spec.EvalFactoryNode);
            var filters = evalNodeAnalysisResult.FilterNodes;

            Assert.AreEqual(2, filters.Count);

            // node 0
            var filterNode = filters[0];

            Assert.AreEqual(typeof(SupportBean), filterNode.FilterSpec.FilterForEventType.UnderlyingType);
            Assert.AreEqual(0, filterNode.FilterSpec.Parameters.Length);

            // node 1
            filterNode = filters[1];
            Assert.AreEqual(typeof(SupportBean), filterNode.FilterSpec.FilterForEventType.UnderlyingType);
            Assert.AreEqual(1, filterNode.FilterSpec.Parameters.Length);

            var range = (FilterSpecParamRange)filterNode.FilterSpec.Parameters[0][0];

            Assert.AreEqual(FilterOperator.RANGE_CLOSED, range.FilterOperator);

            // min-value
            var prop = (RangeValueEventProp)range.Min;

            Assert.AreEqual("s", prop.ResultEventAsName);
            Assert.AreEqual("IntBoxed", prop.ResultEventProperty);

            // max-value
            var constant = (RangeValueDouble)range.Max;

            Assert.AreEqual(100d, constant.DoubleValue);
        }
        public static void WalkStreamSpecs(
            StatementSpecRaw spec,
            ExprNodeSubselectDeclaredDotVisitor visitor)
        {
            // determine pattern-filter subqueries
            foreach (StreamSpecRaw streamSpecRaw in spec.StreamSpecs) {
                if (streamSpecRaw is PatternStreamSpecRaw) {
                    PatternStreamSpecRaw patternStreamSpecRaw = (PatternStreamSpecRaw) streamSpecRaw;
                    EvalNodeAnalysisResult analysisResult =
                        EvalNodeUtil.RecursiveAnalyzeChildNodes(patternStreamSpecRaw.EvalForgeNode);
                    foreach (EvalForgeNode evalNode in analysisResult.ActiveNodes) {
                        if (evalNode is EvalFilterForgeNode) {
                            EvalFilterForgeNode filterNode = (EvalFilterForgeNode) evalNode;
                            foreach (ExprNode filterExpr in filterNode.RawFilterSpec.FilterExpressions) {
                                filterExpr.Accept(visitor);
                            }
                        }
                        else if (evalNode is EvalObserverForgeNode) {
                            int beforeCount = visitor.Subselects.Count;
                            EvalObserverForgeNode observerNode = (EvalObserverForgeNode) evalNode;
                            foreach (ExprNode param in observerNode.PatternObserverSpec.ObjectParameters) {
                                param.Accept(visitor);
                            }

                            if (visitor.Subselects.Count != beforeCount) {
                                throw new ExprValidationException(
                                    "Subselects are not allowed within pattern observer parameters, please consider using a variable instead");
                            }
                        }
                    }
                }
            }

            // determine filter streams
            foreach (StreamSpecRaw rawSpec in spec.StreamSpecs) {
                if (rawSpec is FilterStreamSpecRaw) {
                    FilterStreamSpecRaw raw = (FilterStreamSpecRaw) rawSpec;
                    foreach (ExprNode filterExpr in raw.RawFilterSpec.FilterExpressions) {
                        filterExpr.Accept(visitor);
                    }
                }
            }
        }
        public void Activate(EventBean optionalTriggeringEvent, MatchedEventMap priorMatches, long timeOffset, bool isRecoveringResilient)
        {
            if (PatternStopCallback != null)
            {
                PatternStopCallback.Stop();
            }

            PatternStreamSpecCompiled patternStreamSpec = _endpointPatternSpec.PatternCompiled;
            StatementContext          stmtContext       = _agentInstanceContext.StatementContext;

            EvalRootFactoryNode rootFactoryNode = _servicesContext.PatternNodeFactory.MakeRootNode(patternStreamSpec.EvalFactoryNode);
            int            streamNum            = _isStartEndpoint ? _contextStatePathKey.SubPath : -1 * _contextStatePathKey.SubPath;
            bool           allowResilient       = _contextStatePathKey.Level == 1;
            PatternContext patternContext       = stmtContext.PatternContextFactory.CreateContext(stmtContext, streamNum, rootFactoryNode, new MatchedEventMapMeta(patternStreamSpec.AllTags, !patternStreamSpec.ArrayEventTypes.IsEmpty()), allowResilient);

            PatternAgentInstanceContext patternAgentInstanceContext = stmtContext.PatternContextFactory.CreatePatternAgentContext(patternContext, _agentInstanceContext, false);
            EvalRootNode rootNode = EvalNodeUtil.MakeRootNodeFromFactory(rootFactoryNode, patternAgentInstanceContext);

            if (priorMatches == null)
            {
                priorMatches = new MatchedEventMapImpl(patternContext.MatchedEventMapMeta);
            }

            // capture any callbacks that may occur right after start
            ConditionPatternMatchCallback callback = new ConditionPatternMatchCallback(this);

            PatternStopCallback   = rootNode.Start(callback.MatchFound, patternContext, priorMatches, isRecoveringResilient);
            callback.ForwardCalls = true;

            if (_agentInstanceContext.StatementContext.StatementExtensionServicesContext != null &&
                _agentInstanceContext.StatementContext.StatementExtensionServicesContext.StmtResources != null)
            {
                _agentInstanceContext.StatementContext.StatementExtensionServicesContext.StmtResources
                .StartContextPattern(PatternStopCallback, _isStartEndpoint, _contextStatePathKey);
            }

            if (callback.IsInvoked)
            {
                MatchFound(Collections.GetEmptyMap <String, Object>());
            }
        }
        public bool Activate(
            EventBean optionalTriggeringEvent,
            ContextControllerEndConditionMatchEventProvider endConditionMatchEventProvider,
            IDictionary<string, object> optionalTriggeringPattern)
        {
            patternStopCallback?.Stop();

            var agentInstanceContext = controller.Realization.AgentInstanceContextCreate;
            Func<FilterSpecActivatable, FilterValueSetParam[][]> contextAddendumFunction = filter =>
                ContextManagerUtil.ComputeAddendumNonStmt(partitionKeys, filter, controller.Realization);
            var patternAgentInstanceContext = new PatternAgentInstanceContext(
                pattern.PatternContext,
                agentInstanceContext,
                false,
                contextAddendumFunction);
            var rootNode = EvalNodeUtil.MakeRootNodeFromFactory(pattern.Pattern, patternAgentInstanceContext);

            var matchedEventMap = new MatchedEventMapImpl(pattern.PatternContext.MatchedEventMapMeta);
            if (optionalTriggeringEvent != null) {
                endConditionMatchEventProvider?.PopulateEndConditionFromTrigger(
                    matchedEventMap,
                    optionalTriggeringEvent);
            }

            if (optionalTriggeringPattern != null) {
                endConditionMatchEventProvider?.PopulateEndConditionFromTrigger(matchedEventMap, optionalTriggeringPattern);
            }
            
            // capture any callbacks that may occur right after start
            var callback = new ConditionPatternMatchCallback(this);
            patternStopCallback = rootNode.Start(callback, pattern.PatternContext, matchedEventMap, false);
            callback.forwardCalls = true;

            if (callback.IsInvoked) {
                MatchFound(Collections.GetEmptyMap<string, object>(), optionalTriggeringEvent);
            }

            return false;
        }
        private void TryPatternEquals(String text)
        {
            var raw  = MakeSpec(text);
            var spec = Compile(raw);

            Assert.AreEqual(2, spec.TaggedEventTypes.Count);
            Assert.AreEqual(typeof(SupportBean), spec.TaggedEventTypes.Get("s").First.UnderlyingType);
            Assert.AreEqual(typeof(SupportBean), spec.TaggedEventTypes.Get("t").First.UnderlyingType);

            var evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(spec.EvalFactoryNode);
            var filters = evalNodeAnalysisResult.FilterNodes;

            Assert.AreEqual(2, filters.Count);

            // node 0
            var filterNode = filters[0];

            Assert.AreEqual(typeof(SupportBean), filterNode.FilterSpec.FilterForEventType.UnderlyingType);
            Assert.AreEqual(1, filterNode.FilterSpec.Parameters.Length);

            var constant = (FilterSpecParamConstant)filterNode.FilterSpec.Parameters[0][0];

            Assert.AreEqual(FilterOperator.EQUAL, constant.FilterOperator);
            Assert.AreEqual("IntPrimitive", constant.Lookupable.Expression);
            Assert.AreEqual(5, constant.FilterConstant);

            // node 1
            filterNode = filters[1];
            Assert.AreEqual(typeof(SupportBean), filterNode.FilterSpec.FilterForEventType.UnderlyingType);
            Assert.AreEqual(1, filterNode.FilterSpec.Parameters.Length);

            var eventprop = (FilterSpecParamEventProp)filterNode.FilterSpec.Parameters[0][0];

            Assert.AreEqual(FilterOperator.EQUAL, constant.FilterOperator);
            Assert.AreEqual("IntPrimitive", constant.Lookupable.Expression);
            Assert.AreEqual("s", eventprop.ResultEventAsName);
            Assert.AreEqual("IntBoxed", eventprop.ResultEventProperty);
        }
        public void TestPatternExpressions()
        {
            var text = "select * from pattern [" +
                       "s=" + typeof(SupportBean).FullName + "(IntPrimitive in (s.IntBoxed + 1, 0), IntBoxed+1=IntPrimitive-1)" +
                       "]";

            var raw  = MakeSpec(text);
            var spec = Compile(raw);

            Assert.AreEqual(1, spec.TaggedEventTypes.Count);
            Assert.AreEqual(typeof(SupportBean), spec.TaggedEventTypes.Get("s").First.UnderlyingType);

            var evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(spec.EvalFactoryNode);
            var filters = evalNodeAnalysisResult.FilterNodes;

            Assert.AreEqual(1, filters.Count);

            // node 0
            var filterNode = filters[0];

            Assert.AreEqual(typeof(SupportBean), filterNode.FilterSpec.FilterForEventType.UnderlyingType);
            Assert.AreEqual(1, filterNode.FilterSpec.Parameters.Length);
            var exprParam = (FilterSpecParamExprNode)filterNode.FilterSpec.Parameters[0][0];
        }
示例#16
0
        private static void RecursiveCompile(
            EvalFactoryNode evalNode,
            StatementContext context,
            ExprEvaluatorContext evaluatorContext,
            ICollection <string> eventTypeReferences,
            bool isInsertInto,
            MatchEventSpec tags,
            Deque <int> subexpressionIdStack,
            Stack <EvalFactoryNode> parentNodeStack,
            ICollection <string> allTagNamesOrdered)
        {
            var counter = 0;

            parentNodeStack.Push(evalNode);
            foreach (var child in evalNode.ChildNodes)
            {
                subexpressionIdStack.AddLast(counter++);
                RecursiveCompile(
                    child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags, subexpressionIdStack,
                    parentNodeStack, allTagNamesOrdered);
                subexpressionIdStack.RemoveLast();
            }
            parentNodeStack.Pop();

            LinkedHashMap <string, Pair <EventType, string> > newTaggedEventTypes = null;
            LinkedHashMap <string, Pair <EventType, string> > newArrayEventTypes  = null;

            if (evalNode is EvalFilterFactoryNode)
            {
                var filterNode = (EvalFilterFactoryNode)evalNode;
                var eventName  = filterNode.RawFilterSpec.EventTypeName;
                if (context.TableService.GetTableMetadata(eventName) != null)
                {
                    throw new ExprValidationException("Tables cannot be used in pattern filter atoms");
                }

                var resolvedEventType = FilterStreamSpecRaw.ResolveType(
                    context.EngineURI, eventName, context.EventAdapterService, context.PlugInTypeResolutionURIs);
                var finalEventType       = resolvedEventType;
                var optionalTag          = filterNode.EventAsName;
                var isPropertyEvaluation = false;
                var isParentMatchUntil   = IsParentMatchUntil(evalNode, parentNodeStack);

                // obtain property event type, if final event type is properties
                if (filterNode.RawFilterSpec.OptionalPropertyEvalSpec != null)
                {
                    var optionalPropertyEvaluator =
                        PropertyEvaluatorFactory.MakeEvaluator(
                            context.Container,
                            filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                            resolvedEventType,
                            filterNode.EventAsName,
                            context.EventAdapterService,
                            context.EngineImportService,
                            context.SchedulingService,
                            context.VariableService,
                            context.ScriptingService,
                            context.TableService,
                            context.EngineURI,
                            context.StatementId,
                            context.StatementName,
                            context.Annotations,
                            subexpressionIdStack,
                            context.ConfigSnapshot,
                            context.NamedWindowMgmtService,
                            context.StatementExtensionServicesContext);
                    finalEventType       = optionalPropertyEvaluator.FragmentEventType;
                    isPropertyEvaluation = true;
                }

                if (finalEventType is EventTypeSPI)
                {
                    eventTypeReferences.Add(((EventTypeSPI)finalEventType).Metadata.PrimaryName);
                }

                // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no
                if (optionalTag != null)
                {
                    var       pair         = tags.TaggedEventTypes.Get(optionalTag);
                    EventType existingType = null;
                    if (pair != null)
                    {
                        existingType = pair.First;
                    }
                    if (existingType == null)
                    {
                        pair = tags.ArrayEventTypes.Get(optionalTag);
                        if (pair != null)
                        {
                            throw new ExprValidationException(
                                      "Tag '" + optionalTag + "' for event '" + eventName +
                                      "' used in the repeat-until operator cannot also appear in other filter expressions");
                        }
                    }
                    if ((existingType != null) && (existingType != finalEventType))
                    {
                        throw new ExprValidationException(
                                  "Tag '" + optionalTag + "' for event '" + eventName +
                                  "' has already been declared for events of type " + existingType.UnderlyingType.FullName);
                    }
                    pair = new Pair <EventType, string>(finalEventType, eventName);

                    // add tagged type
                    if (isPropertyEvaluation || isParentMatchUntil)
                    {
                        newArrayEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newArrayEventTypes.Put(optionalTag, pair);
                    }
                    else
                    {
                        newTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newTaggedEventTypes.Put(optionalTag, pair);
                    }
                }

                // For this filter, filter types are all known tags at this time,
                // and additionally stream 0 (self) is our event type.
                // Stream type service allows resolution by property name event if that name appears in other tags.
                // by defaulting to stream zero.
                // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N).
                var selfStreamName = optionalTag;
                if (selfStreamName == null)
                {
                    selfStreamName = "s_" + UuidGenerator.Generate();
                }
                var filterTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                var typePair    = new Pair <EventType, string>(finalEventType, eventName);
                filterTypes.Put(selfStreamName, typePair);
                filterTypes.PutAll(tags.TaggedEventTypes);

                // for the filter, specify all tags used
                var filterTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(tags.TaggedEventTypes);
                filterTaggedEventTypes.Remove(optionalTag);

                // handle array tags (match-until clause)
                LinkedHashMap <string, Pair <EventType, string> > arrayCompositeEventTypes = null;
                if (tags.ArrayEventTypes != null && !tags.ArrayEventTypes.IsEmpty())
                {
                    arrayCompositeEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                    var patternSubexEventType = GetPatternSubexEventType(
                        context.StatementId, "pattern", subexpressionIdStack);

                    foreach (var entry in tags.ArrayEventTypes)
                    {
                        var specificArrayType = new LinkedHashMap <string, Pair <EventType, string> >();
                        specificArrayType.Put(entry.Key, entry.Value);
                        var arrayTagCompositeEventType =
                            context.EventAdapterService.CreateSemiAnonymousMapType(
                                patternSubexEventType, Collections.GetEmptyMap <string, Pair <EventType, string> >(),
                                specificArrayType, isInsertInto);
                        context.StatementSemiAnonymousTypeRegistry.Register(arrayTagCompositeEventType);

                        var tag = entry.Key;
                        if (!filterTypes.ContainsKey(tag))
                        {
                            var pair = new Pair <EventType, string>(arrayTagCompositeEventType, tag);
                            filterTypes.Put(tag, pair);
                            arrayCompositeEventTypes.Put(tag, pair);
                        }
                    }
                }

                StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                    filterTypes, context.EngineURI, true, false);
                var exprNodes = filterNode.RawFilterSpec.FilterExpressions;

                var spec = FilterSpecCompiler.MakeFilterSpec(
                    resolvedEventType, eventName, exprNodes,
                    filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                    filterTaggedEventTypes,
                    arrayCompositeEventTypes,
                    streamTypeService,
                    null, context, subexpressionIdStack);
                filterNode.FilterSpec = spec;
            }
            else if (evalNode is EvalObserverFactoryNode)
            {
                var observerNode = (EvalObserverFactoryNode)evalNode;
                try
                {
                    var observerFactory = context.PatternResolutionService.Create(observerNode.PatternObserverSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "observer", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNOBSERVER, observerNode.PatternObserverSpec.ObjectParameters,
                        validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    observerNode.ObserverFactory = observerFactory;
                    observerFactory.SetObserverParameters(validated, convertor, validationContext);
                }
                catch (ObserverParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " +
                              e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " + e.Message,
                              e);
                }
            }
            else if (evalNode is EvalGuardFactoryNode)
            {
                var guardNode = (EvalGuardFactoryNode)evalNode;
                try
                {
                    var guardFactory = context.PatternResolutionService.Create(guardNode.PatternGuardSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "guard", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNGUARD, guardNode.PatternGuardSpec.ObjectParameters, validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    guardNode.GuardFactory = guardFactory;
                    guardFactory.SetGuardParameters(validated, convertor);
                }
                catch (GuardParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
            }
            else if (evalNode is EvalEveryDistinctFactoryNode)
            {
                var distinctNode             = (EvalEveryDistinctFactoryNode)evalNode;
                var matchEventFromChildNodes = AnalyzeMatchEvent(distinctNode);
                var streamTypeService        = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                    subexpressionIdStack, "every-distinct", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);
                IList <ExprNode> validated;
                try
                {
                    validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNEVERYDISTINCT, distinctNode.Expressions, validationContext);
                }
                catch (ExprValidationPropertyException ex)
                {
                    throw new ExprValidationPropertyException(
                              ex.Message +
                              ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct",
                              ex.InnerException);
                }

                MatchedEventConvertor convertor =
                    new MatchedEventConvertorImpl(
                        matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                        allTagNamesOrdered, context.EventAdapterService);

                distinctNode.Convertor = convertor;

                // Determine whether some expressions are constants or time period
                IList <ExprNode>             distinctExpressions  = new List <ExprNode>();
                ExprTimePeriodEvalDeltaConst timeDeltaComputation = null;
                ExprNode expiryTimeExp = null;
                var      count         = -1;
                var      last          = validated.Count - 1;
                foreach (var expr in validated)
                {
                    count++;
                    if (count == last && expr is ExprTimePeriod)
                    {
                        expiryTimeExp = expr;
                        var timePeriodExpr = (ExprTimePeriod)expiryTimeExp;
                        timeDeltaComputation =
                            timePeriodExpr.ConstEvaluator(new ExprEvaluatorContextStatement(context, false));
                    }
                    else if (expr.IsConstantResult)
                    {
                        if (count == last)
                        {
                            var evaluateParams = new EvaluateParams(null, true, evaluatorContext);
                            var value          = expr.ExprEvaluator.Evaluate(evaluateParams);
                            if (!(value.IsNumber()))
                            {
                                throw new ExprValidationException(
                                          "Invalid parameter for every-distinct, expected number of seconds constant (constant not considered for distinct)");
                            }

                            var secondsExpire = expr.ExprEvaluator.Evaluate(evaluateParams);

                            long?timeExpire;
                            if (secondsExpire == null)
                            {
                                timeExpire = null;
                            }
                            else
                            {
                                timeExpire = context.TimeAbacus.DeltaForSecondsNumber(secondsExpire);
                            }

                            if (timeExpire != null && timeExpire > 0)
                            {
                                timeDeltaComputation = new ExprTimePeriodEvalDeltaConstGivenDelta(timeExpire.Value);
                                expiryTimeExp        = expr;
                            }
                            else
                            {
                                Log.Warn("Invalid seconds-expire " + timeExpire + " for " + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(expr));
                            }
                        }
                        else
                        {
                            Log.Warn(
                                "Every-distinct node utilizes an expression returning a constant value, please check expression '{0}', not adding expression to distinct-value expression list",
                                expr.ToExpressionStringMinPrecedenceSafe());
                        }
                    }
                    else
                    {
                        distinctExpressions.Add(expr);
                    }
                }
                if (distinctExpressions.IsEmpty())
                {
                    throw new ExprValidationException(
                              "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values");
                }
                distinctNode.SetDistinctExpressions(distinctExpressions, timeDeltaComputation, expiryTimeExp);
            }
            else if (evalNode is EvalMatchUntilFactoryNode)
            {
                var matchUntilNode = (EvalMatchUntilFactoryNode)evalNode;

                // compile bounds expressions, if any
                var untilMatchEventSpec = new MatchEventSpec(tags.TaggedEventTypes, tags.ArrayEventTypes);
                var streamTypeService   = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, subexpressionIdStack,
                    "until", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                var lower = ValidateBounds(matchUntilNode.LowerBounds, validationContext);
                matchUntilNode.LowerBounds = lower;

                var upper = ValidateBounds(matchUntilNode.UpperBounds, validationContext);
                matchUntilNode.UpperBounds = upper;

                var single = ValidateBounds(matchUntilNode.SingleBound, validationContext);
                matchUntilNode.SingleBound = single;

                var convertor = new MatchedEventConvertorImpl(
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, allTagNamesOrdered,
                    context.EventAdapterService);
                matchUntilNode.Convertor = convertor;

                // compile new tag lists
                ISet <string> arrayTags = null;
                var           matchUntilAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(matchUntilNode.ChildNodes[0]);
                foreach (var filterNode in matchUntilAnalysisResult.FilterNodes)
                {
                    var optionalTag = filterNode.EventAsName;
                    if (optionalTag != null)
                    {
                        if (arrayTags == null)
                        {
                            arrayTags = new HashSet <string>();
                        }
                        arrayTags.Add(optionalTag);
                    }
                }

                if (arrayTags != null)
                {
                    foreach (var arrayTag in arrayTags)
                    {
                        if (!tags.ArrayEventTypes.ContainsKey(arrayTag))
                        {
                            tags.ArrayEventTypes.Put(arrayTag, tags.TaggedEventTypes.Get(arrayTag));
                            tags.TaggedEventTypes.Remove(arrayTag);
                        }
                    }
                }
                matchUntilNode.TagsArrayed = GetIndexesForTags(allTagNamesOrdered, arrayTags);
            }
            else if (evalNode is EvalFollowedByFactoryNode)
            {
                var followedByNode = (EvalFollowedByFactoryNode)evalNode;
                StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.EngineURI, false);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService,
                    evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                if (followedByNode.OptionalMaxExpressions != null)
                {
                    IList <ExprNode> validated = new List <ExprNode>();
                    foreach (var maxExpr in followedByNode.OptionalMaxExpressions)
                    {
                        if (maxExpr == null)
                        {
                            validated.Add(null);
                        }
                        else
                        {
                            var visitor = new ExprNodeSummaryVisitor();
                            maxExpr.Accept(visitor);
                            if (!visitor.IsPlain)
                            {
                                var errorMessage = "Invalid maximum expression in followed-by, " + visitor.GetMessage() +
                                                   " are not allowed within the expression";
                                Log.Error(errorMessage);
                                throw new ExprValidationException(errorMessage);
                            }

                            var validatedExpr = ExprNodeUtility.GetValidatedSubtree(
                                ExprNodeOrigin.FOLLOWEDBYMAX, maxExpr, validationContext);
                            validated.Add(validatedExpr);
                            if ((validatedExpr.ExprEvaluator.ReturnType == null) ||
                                (!validatedExpr.ExprEvaluator.ReturnType.IsNumeric()))
                            {
                                var message = "Invalid maximum expression in followed-by, the expression must return an integer value";
                                throw new ExprValidationException(message);
                            }
                        }
                    }
                    followedByNode.OptionalMaxExpressions = validated;
                }
            }

            if (newTaggedEventTypes != null)
            {
                tags.TaggedEventTypes.PutAll(newTaggedEventTypes);
            }
            if (newArrayEventTypes != null)
            {
                tags.ArrayEventTypes.PutAll(newArrayEventTypes);
            }
        }
示例#17
0
        private PatternStreamSpecCompiled CompileInternal(
            StatementContext context,
            ICollection <string> eventTypeReferences,
            bool isInsertInto,
            ICollection <int> assignedTypeNumberStack,
            MatchEventSpec tags,
            IEnumerable <string> priorAllTags,
            bool isJoin,
            bool isContextDeclaration,
            bool isOnTrigger)
        {
            // validate
            if ((_suppressSameEventMatches || _discardPartialsOnMatch) &&
                (isJoin || isContextDeclaration || isOnTrigger))
            {
                throw new ExprValidationException(
                          "Discard-partials and suppress-matches is not supported in a joins, context declaration and on-action");
            }

            if (tags == null)
            {
                tags = new MatchEventSpec();
            }
            var subexpressionIdStack = new ArrayDeque <int>(assignedTypeNumberStack);
            var evaluatorContextStmt = new ExprEvaluatorContextStatement(context, false);
            var nodeStack            = new Stack <EvalFactoryNode>();

            // detemine ordered tags
            var filterFactoryNodes = EvalNodeUtil.RecursiveGetChildNodes(
                _evalFactoryNode, FilterForFilterFactoryNodes.INSTANCE);
            var allTagNamesOrdered = new LinkedHashSet <string>();

            if (priorAllTags != null)
            {
                allTagNamesOrdered.AddAll(priorAllTags);
            }
            foreach (var filterNode in filterFactoryNodes)
            {
                var factory = (EvalFilterFactoryNode)filterNode;
                int tagNumber;
                if (factory.EventAsName != null)
                {
                    if (!allTagNamesOrdered.Contains(factory.EventAsName))
                    {
                        allTagNamesOrdered.Add(factory.EventAsName);
                        tagNumber = allTagNamesOrdered.Count - 1;
                    }
                    else
                    {
                        tagNumber = FindTagNumber(factory.EventAsName, allTagNamesOrdered);
                    }
                    factory.EventAsTagNumber = tagNumber;
                }
            }

            RecursiveCompile(
                _evalFactoryNode, context, evaluatorContextStmt, eventTypeReferences, isInsertInto, tags,
                subexpressionIdStack, nodeStack, allTagNamesOrdered);

            var auditPattern            = AuditEnum.PATTERN.GetAudit(context.Annotations);
            var auditPatternInstance    = AuditEnum.PATTERNINSTANCES.GetAudit(context.Annotations);
            var compiledEvalFactoryNode = _evalFactoryNode;

            if (context.PatternNodeFactory.IsAuditSupported && (auditPattern != null || auditPatternInstance != null))
            {
                var instanceCount = new EvalAuditInstanceCount();
                compiledEvalFactoryNode = RecursiveAddAuditNode(
                    context.PatternNodeFactory, null, auditPattern != null, auditPatternInstance != null,
                    _evalFactoryNode, instanceCount);
            }

            return(new PatternStreamSpecCompiled(
                       compiledEvalFactoryNode, tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, ViewSpecs,
                       OptionalStreamName, Options, _suppressSameEventMatches, _discardPartialsOnMatch));
        }
示例#18
0
        public static ExprNodeSubselectDeclaredDotVisitor WalkSubselectAndDeclaredDotExpr(StatementSpecRaw spec)
        {
            // Look for expressions with sub-selects in select expression list and filter expression
            // Recursively compile the statement within the statement.
            var visitor = new ExprNodeSubselectDeclaredDotVisitor();

            foreach (var raw in spec.SelectClauseSpec.SelectExprList)
            {
                if (raw is SelectClauseExprRawSpec)
                {
                    var rawExpr = (SelectClauseExprRawSpec)raw;
                    rawExpr.SelectExpression.Accept(visitor);
                }
            }
            if (spec.FilterRootNode != null)
            {
                spec.FilterRootNode.Accept(visitor);
            }
            if (spec.HavingExprRootNode != null)
            {
                spec.HavingExprRootNode.Accept(visitor);
            }
            if (spec.UpdateDesc != null)
            {
                if (spec.UpdateDesc.OptionalWhereClause != null)
                {
                    spec.UpdateDesc.OptionalWhereClause.Accept(visitor);
                }
                foreach (var assignment in spec.UpdateDesc.Assignments)
                {
                    assignment.Expression.Accept(visitor);
                }
            }
            if (spec.OnTriggerDesc != null)
            {
                VisitSubselectOnTrigger(spec.OnTriggerDesc, visitor);
            }
            // Determine pattern-filter subqueries
            foreach (var streamSpecRaw in spec.StreamSpecs)
            {
                if (streamSpecRaw is PatternStreamSpecRaw)
                {
                    var patternStreamSpecRaw = (PatternStreamSpecRaw)streamSpecRaw;
                    var analysisResult       = EvalNodeUtil.RecursiveAnalyzeChildNodes(patternStreamSpecRaw.EvalFactoryNode);
                    foreach (var evalNode in analysisResult.ActiveNodes)
                    {
                        if (evalNode is EvalFilterFactoryNode)
                        {
                            var filterNode = (EvalFilterFactoryNode)evalNode;
                            foreach (var filterExpr in filterNode.RawFilterSpec.FilterExpressions)
                            {
                                filterExpr.Accept(visitor);
                            }
                        }
                        else if (evalNode is EvalObserverFactoryNode)
                        {
                            var beforeCount  = visitor.Subselects.Count;
                            var observerNode = (EvalObserverFactoryNode)evalNode;
                            foreach (var param in observerNode.PatternObserverSpec.ObjectParameters)
                            {
                                param.Accept(visitor);
                            }
                            if (visitor.Subselects.Count != beforeCount)
                            {
                                throw new ExprValidationException("Subselects are not allowed within pattern observer parameters, please consider using a variable instead");
                            }
                        }
                    }
                }
            }
            // Determine filter streams
            foreach (var rawSpec in spec.StreamSpecs)
            {
                if (rawSpec is FilterStreamSpecRaw)
                {
                    var raw = (FilterStreamSpecRaw)rawSpec;
                    foreach (var filterExpr in raw.RawFilterSpec.FilterExpressions)
                    {
                        filterExpr.Accept(visitor);
                    }
                }
            }

            return(visitor);
        }