public bool EqualsTimePeriod(ExprTimePeriodEvalDeltaConst otherComputation) { if (otherComputation is ExprTimePeriodEvalDeltaConstMsec) { ExprTimePeriodEvalDeltaConstMsec other = (ExprTimePeriodEvalDeltaConstMsec)otherComputation; return(other._msec == _msec); } return(false); }
public static ExprTimePeriodEvalDeltaConst ValidateAndEvaluateTimeDelta(String viewName, StatementContext statementContext, ExprNode expression, String expectedMessage, int expressionNumber) { StreamTypeService streamTypeService = new StreamTypeServiceImpl(statementContext.EngineURI, false); ExprTimePeriodEvalDeltaConst timeDelta; if (expression is ExprTimePeriod) { ExprTimePeriod validated = (ExprTimePeriod)ViewFactorySupport.ValidateExpr(viewName, statementContext, expression, streamTypeService, expressionNumber); timeDelta = validated.ConstEvaluator(new ExprEvaluatorContextStatement(statementContext, false)); } else { var result = ViewFactorySupport.ValidateAndEvaluateExpr(viewName, statementContext, expression, streamTypeService, expressionNumber); if (!result.IsNumber()) { throw new ViewParameterException(expectedMessage); } long millisecondsBeforeExpiry; if (TypeHelper.IsFloatingPointNumber(result)) { millisecondsBeforeExpiry = (long)Math.Round(1000d * result.AsDouble()); } else { millisecondsBeforeExpiry = 1000 * result.AsLong(); } timeDelta = new ExprTimePeriodEvalDeltaConstMsec(millisecondsBeforeExpiry); } if (timeDelta.DeltaMillisecondsAdd(0) < 1) { throw new ViewParameterException(viewName + " view requires a size of at least 1 msec"); } return(timeDelta); }
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( filterNode.RawFilterSpec.OptionalPropertyEvalSpec, resolvedEventType, filterNode.EventAsName, context.EventAdapterService, context.MethodResolutionService, context.SchedulingService, context.VariableService, context.ScriptingService, context.TableService, context.EngineURI, context.StatementId, context.StatementName, context.Annotations, subexpressionIdStack, context.ConfigSnapshot, context.NamedWindowService); 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.GetTypeNameFullyQualPretty()); } 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 Count). 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); 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"); var validationContext = new ExprValidationContext( streamTypeService, context.MethodResolutionService, 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"); var validationContext = new ExprValidationContext( streamTypeService, context.MethodResolutionService, 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"); var validationContext = new ExprValidationContext( streamTypeService, context.MethodResolutionService, 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 value = expr.ExprEvaluator.Evaluate(new EvaluateParams(null, true, evaluatorContext)); if (!(value.IsNumber())) { throw new ExprValidationException( "Invalid parameter for every-distinct, expected number of seconds constant (constant not considered for distinct)"); } var secondsTemp = expr.ExprEvaluator.Evaluate(new EvaluateParams(null, true, evaluatorContext)); var secondsExpire = secondsTemp.AsBoxedDouble(); if ((secondsExpire != null) && (secondsExpire > 0)) { timeDeltaComputation = new ExprTimePeriodEvalDeltaConstMsec((long)Math.Round(1000d * secondsExpire.Value)); expiryTimeExp = expr; } } else { Log.Warn( "Every-distinct node utilizes an expression returning a constant value, please check expression '" + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(expr) + "', not adding expression to distinct-value expression list"); } } 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"); var validationContext = new ExprValidationContext( streamTypeService, context.MethodResolutionService, 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; MatchedEventConvertor 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( streamTypeService, context.MethodResolutionService, 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.Message + " 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); } }
public void TestComputeDelta() { ExprTimePeriodEvalDeltaConstMsec delta500 = new ExprTimePeriodEvalDeltaConstMsec(500); Assert.AreEqual(500, delta500.DeltaMillisecondsAdd(0)); Assert.AreEqual(500, delta500.DeltaMillisecondsSubtract(0)); ExprTimePeriodEvalDeltaConstMsec delta10k = new ExprTimePeriodEvalDeltaConstMsec(10000); Assert.AreEqual(10000, delta10k.DeltaMillisecondsAdd(0)); Assert.AreEqual(10000, delta10k.DeltaMillisecondsSubtract(0)); // With current=2300, ref=1000, and interval=500, expect 2500 as next interval and 200 as solution // the reference will stay the same since the computation is cheap without updated reference ExprTimePeriodEvalDeltaResult result = delta500.DeltaMillisecondsAddWReference(2300, 1000); Assert.AreEqual(200, result.Delta); Assert.AreEqual(1000, result.LastReference); result = delta500.DeltaMillisecondsAddWReference(2300, 4200); Assert.AreEqual(400, result.Delta); Assert.AreEqual(4200, result.LastReference); result = delta500.DeltaMillisecondsAddWReference(2200, 4200); Assert.AreEqual(500, result.Delta); Assert.AreEqual(4200, result.LastReference); result = delta500.DeltaMillisecondsAddWReference(2200, 2200); Assert.AreEqual(500, result.Delta); Assert.AreEqual(2200, result.LastReference); result = delta500.DeltaMillisecondsAddWReference(2201, 2200); Assert.AreEqual(499, result.Delta); Assert.AreEqual(2200, result.LastReference); result = delta500.DeltaMillisecondsAddWReference(2600, 2200); Assert.AreEqual(100, result.Delta); Assert.AreEqual(2200, result.LastReference); result = delta500.DeltaMillisecondsAddWReference(2699, 2200); Assert.AreEqual(1, result.Delta); Assert.AreEqual(2200, result.LastReference); result = delta500.DeltaMillisecondsAddWReference(2699, 2700); Assert.AreEqual(1, result.Delta); Assert.AreEqual(2700, result.LastReference); result = delta10k.DeltaMillisecondsAddWReference(2699, 2700); Assert.AreEqual(1, result.Delta); Assert.AreEqual(2700, result.LastReference); result = delta10k.DeltaMillisecondsAddWReference(2700, 2700); Assert.AreEqual(10000, result.Delta); Assert.AreEqual(2700, result.LastReference); result = delta10k.DeltaMillisecondsAddWReference(2700, 6800); Assert.AreEqual(4100, result.Delta); Assert.AreEqual(6800, result.LastReference); result = delta10k.DeltaMillisecondsAddWReference(23050, 16800); Assert.AreEqual(3750, result.Delta); Assert.AreEqual(16800, result.LastReference); }