コード例 #1
0
        private OnTriggerActivatorDesc ActivatorNamedWindow(
            NamedWindowConsumerStreamSpec namedSpec,
            StatementCompileTimeServices services)
        {
            var namedWindow = namedSpec.NamedWindow;
            var triggerEventTypeName = namedSpec.NamedWindow.EventType.Name;

            var typesFilterValidation = new StreamTypeServiceImpl(
                namedWindow.EventType,
                namedSpec.OptionalStreamName,
                false);
            var filterSingle =
                ExprNodeUtilityMake.ConnectExpressionsByLogicalAndWhenNeeded(namedSpec.FilterExpressions);
            var filterQueryGraph = EPLValidationUtil.ValidateFilterGetQueryGraphSafe(
                filterSingle,
                typesFilterValidation,
                @base.StatementRawInfo,
                services);
            var activator = new ViewableActivatorNamedWindowForge(
                namedSpec,
                namedWindow,
                filterSingle,
                filterQueryGraph,
                false,
                namedSpec.OptPropertyEvaluator);

            var activatorResultEventType = namedWindow.EventType;
            if (namedSpec.OptPropertyEvaluator != null) {
                activatorResultEventType = namedSpec.OptPropertyEvaluator.FragmentEventType;
            }

            return new OnTriggerActivatorDesc(activator, triggerEventTypeName, activatorResultEventType);
        }
コード例 #2
0
        /// <summary>
        /// Validate the view parameter expressions and return the validated expression for later execution.
        /// <para>
        /// Does not evaluate the expression.
        /// </para>
        /// </summary>
        /// <param name="viewName">textual name of view</param>
        /// <param name="eventType">is the event type of the parent view or stream attached.</param>
        /// <param name="statementContext">context with statement services</param>
        /// <param name="expressions">view expression parameter to validate</param>
        /// <param name="allowConstantResult">
        /// true to indicate whether expressions that return a constant
        /// result should be allowed; false to indicate that if an expression is known to return a constant result
        /// the expression is considered invalid
        /// </param>
        /// <exception cref="ViewParameterException">if the expressions fail to validate</exception>
        /// <returns>object result value of parameter expressions</returns>
        public static ExprNode[] Validate(
            string viewName,
            EventType eventType,
            StatementContext statementContext,
            IList <ExprNode> expressions,
            bool allowConstantResult)
        {
            var results           = new List <ExprNode>();
            int expressionNumber  = 0;
            var streamTypeService = new StreamTypeServiceImpl(eventType, null, false, statementContext.EngineURI);

            foreach (ExprNode expr in expressions)
            {
                ExprNode validated = ValidateExpr(viewName, statementContext, expr, streamTypeService, expressionNumber);
                results.Add(validated);

                if ((!allowConstantResult) && (validated.IsConstantResult))
                {
                    string message = "Invalid view parameter expression " + expressionNumber + GetViewDesc(viewName) +
                                     ", the expression returns a constant result value, are you sure?";
                    Log.Error(message);
                    throw new ViewParameterException(message);
                }

                expressionNumber++;
            }
            return(results.ToArray());
        }
コード例 #3
0
        public static Pair <ExprNode, string> CompileValidateStatementFilterExpr(
            EPServiceProviderSPI engine,
            string filterExpression)
        {
            ExprNode exprNode;

            try
            {
                var spi = (EPAdministratorSPI)engine.EPAdministrator;
                exprNode = spi.CompileExpression(filterExpression);
            }
            catch (Exception ex)
            {
                return(new Pair <ExprNode, string>(null, "Error compiling expression: " + ex.Message));
            }

            try
            {
                var streamTypeService = new StreamTypeServiceImpl(STATEMENT_META_EVENT_TYPE, null, true, engine.URI);
                exprNode = ExprNodeUtility.GetValidatedSubtree(
                    ExprNodeOrigin.SCRIPTPARAMS, exprNode,
                    new ExprValidationContext(
                        streamTypeService,
                        engine.EngineImportService,
                        null, null,
                        engine.TimeProvider, null, null, null,
                        engine.EventAdapterService, "no-name-assigned", -1,
                        null, null, null, true, false, false, false, null, true));
            }
            catch (Exception ex)
            {
                return(new Pair <ExprNode, string>(null, "Error validating expression: " + ex.Message));
            }
            return(new Pair <ExprNode, string>(exprNode, null));
        }
コード例 #4
0
ファイル: ViewForgeSupport.cs プロジェクト: lanicon/nesper
        /// <summary>
        ///     Validate the view parameter expressions and return the validated expression for later execution.
        ///     <para />
        ///     Does not evaluate the expression.
        /// </summary>
        /// <param name="viewName">textual name of view</param>
        /// <param name="eventType">is the event type of the parent view or stream attached.</param>
        /// <param name="expressions">view expression parameter to validate</param>
        /// <param name="allowConstantResult">
        ///     true to indicate whether expressions that return a constantresult should be allowed; false to indicate that if an
        ///     expression is known to return a constant result
        ///     the expression is considered invalid
        /// </param>
        /// <param name="streamNumber">stream number</param>
        /// <param name="viewForgeEnv">view forge env</param>
        /// <returns>object result value of parameter expressions</returns>
        /// <throws>ViewParameterException if the expressions fail to validate</throws>
        public static ExprNode[] Validate(
            string viewName,
            EventType eventType,
            IList<ExprNode> expressions,
            bool allowConstantResult,
            ViewForgeEnv viewForgeEnv,
            int streamNumber)
        {
            IList<ExprNode> results = new List<ExprNode>();
            var expressionNumber = 0;
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(eventType, null, false);
            foreach (var expr in expressions) {
                var validated = ValidateExpr(
                    viewName,
                    expr,
                    streamTypeService,
                    viewForgeEnv,
                    expressionNumber,
                    streamNumber);
                results.Add(validated);

                if (!allowConstantResult && validated.Forge.ForgeConstantType.IsCompileTimeConstant) {
                    var message = "Invalid view parameter expression " +
                                  expressionNumber +
                                  GetViewDesc(viewName) +
                                  ", the expression returns a constant result value, are you sure?";
                    throw new ViewParameterException(message);
                }

                expressionNumber++;
            }

            return results.ToArray();
        }
コード例 #5
0
        public static void Validate1StreamMD(ExprNode topNode)
        {
            var eventType = SupportEventTypeFactory.CreateBeanType(typeof(SupportMarketDataBean));
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(eventType, "s0", false, "uri");

            ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.SELECT, topNode, ExprValidationContextFactory.Make(streamTypeService));
        }
コード例 #6
0
ファイル: EPLValidationUtil.cs プロジェクト: lanicon/nesper
 public static void ValidateFilterWQueryGraphSafe(
     QueryGraphForge queryGraph,
     ExprNode filterExpression,
     StreamTypeServiceImpl typeService,
     StatementRawInfo statementRawInfo,
     StatementCompileTimeServices services)
 {
     try {
         var validationContext = new ExprValidationContextBuilder(typeService, statementRawInfo, services)
             .WithAllowBindingConsumption(true)
             .WithIsFilterExpression(true)
             .Build();
         var validated = ExprNodeUtilityValidate.GetValidatedSubtree(
             ExprNodeOrigin.FILTER,
             filterExpression,
             validationContext);
         FilterExprAnalyzer.Analyze(validated, queryGraph, false);
     }
     catch (Exception ex) {
         Log.Warn(
             "Unexpected exception analyzing filterable expression '" +
             ExprNodeUtilityPrint.ToExpressionStringMinPrecedenceSafe(filterExpression) +
             "': " +
             ex.Message,
             ex);
     }
 }
コード例 #7
0
        protected internal static ExprNode ValidateJoinNamedWindow(
            ExprNodeOrigin exprNodeOrigin,
            ExprNode deleteJoinExpr,
            EventType namedWindowType,
            string namedWindowStreamName,
            string namedWindowName,
            EventType filteredType,
            string filterStreamName,
            string filteredTypeName,
            string optionalTableName,
            StatementRawInfo statementRawInfo,
            StatementCompileTimeServices compileTimeServices
        )
        {
            if (deleteJoinExpr == null) {
                return null;
            }

            var namesAndTypes = new LinkedHashMap<string, Pair<EventType, string>>();
            namesAndTypes.Put(namedWindowStreamName, new Pair<EventType, string>(namedWindowType, namedWindowName));
            namesAndTypes.Put(filterStreamName, new Pair<EventType, string>(filteredType, filteredTypeName));
            StreamTypeService typeService = new StreamTypeServiceImpl(namesAndTypes, false, false);

            var validationContext = new ExprValidationContextBuilder(typeService, statementRawInfo, compileTimeServices)
                .WithAllowBindingConsumption(true)
                .Build();
            return ExprNodeUtilityValidate.GetValidatedSubtree(exprNodeOrigin, deleteJoinExpr, validationContext);
        }
コード例 #8
0
        private NamedWindowOnMergeActionIns SetupInsert(string namedWindowName, InternalEventRouter internalEventRouter, EventTypeSPI eventTypeNamedWindow, int selectClauseNumber, OnTriggerMergeActionInsert desc, EventType triggeringEventType, string triggeringStreamName, StatementContext statementContext)
        {
            // Compile insert-into INFO
            string streamName     = desc.OptionalStreamName ?? eventTypeNamedWindow.Name;
            var    insertIntoDesc = InsertIntoDesc.FromColumns(streamName, desc.Columns);

            // rewrite any wildcards to use "stream.wildcard"
            if (triggeringStreamName == null)
            {
                triggeringStreamName = UuidGenerator.Generate();
            }
            var selectNoWildcard = CompileSelectNoWildcard(triggeringStreamName, desc.SelectClauseCompiled);

            // Set up event types for select-clause evaluation: The first type does not contain anything as its the named window row which is not present for insert
            var dummyTypeNoProperties = new MapEventType(EventTypeMetadata.CreateAnonymous("merge_named_window_insert", ApplicationType.MAP), "merge_named_window_insert", 0, null, Collections.EmptyDataMap, null, null, null);
            var eventTypes            = new EventType[] { dummyTypeNoProperties, triggeringEventType };
            var streamNames           = new string[] { UuidGenerator.Generate(), triggeringStreamName };
            var streamTypeService     = new StreamTypeServiceImpl(eventTypes, streamNames, new bool[1], statementContext.EngineURI, false);

            // Get select expr processor
            var selectExprEventTypeRegistry = new SelectExprEventTypeRegistry(statementContext.StatementName, statementContext.StatementEventTypeRef);
            var exprEvaluatorContext        = new ExprEvaluatorContextStatement(statementContext, false);
            var insertHelper = SelectExprProcessorFactory.GetProcessor(
                statementContext.Container,
                Collections.SingletonList(selectClauseNumber),
                selectNoWildcard.ToArray(), false,
                insertIntoDesc, null, null, streamTypeService,
                statementContext.EventAdapterService,
                statementContext.StatementResultService,
                statementContext.ValueAddEventService,
                selectExprEventTypeRegistry,
                statementContext.EngineImportService,
                exprEvaluatorContext,
                statementContext.VariableService,
                statementContext.ScriptingService,
                statementContext.TableService,
                statementContext.TimeProvider,
                statementContext.EngineURI,
                statementContext.StatementId,
                statementContext.StatementName,
                statementContext.Annotations,
                statementContext.ContextDescriptor,
                statementContext.ConfigSnapshot, null,
                statementContext.NamedWindowMgmtService, null, null,
                statementContext.StatementExtensionServicesContext);
            var filterEval = desc.OptionalWhereClause == null ? null : desc.OptionalWhereClause.ExprEvaluator;

            var routerToUser = streamName.Equals(namedWindowName) ? null : internalEventRouter;
            var audit        = AuditEnum.INSERT.GetAudit(statementContext.Annotations) != null;

            string insertIntoTableName = null;

            if (statementContext.TableService.GetTableMetadata(insertIntoDesc.EventTypeName) != null)
            {
                insertIntoTableName = insertIntoDesc.EventTypeName;
            }

            return(new NamedWindowOnMergeActionIns(filterEval, insertHelper, routerToUser, insertIntoTableName, statementContext.TableService, statementContext.EpStatementHandle, statementContext.InternalEventEngineRouteDest, audit));
        }
コード例 #9
0
        public static void Validate1StreamBean(ExprNode topNode)
        {
            var supportContainer = SupportContainer.Instance;
            var eventType        = SupportEventTypeFactory.CreateBeanType(typeof(SupportBean));
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(eventType, "s0", false, "uri");

            ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.SELECT, topNode, SupportExprValidationContextFactory.Make(supportContainer, streamTypeService));
        }
コード例 #10
0
        public static TimePeriodComputeForge ValidateAndEvaluateTimeDeltaFactory(
            string viewName,
            ExprNode expression,
            string expectedMessage,
            int expressionNumber,
            ViewForgeEnv viewForgeEnv,
            int streamNumber)
        {
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(false);
            TimePeriodComputeForge forge;
            if (expression is ExprTimePeriod) {
                var validated = (ExprTimePeriod) ViewForgeSupport.ValidateExpr(
                    viewName,
                    expression,
                    streamTypeService,
                    viewForgeEnv,
                    expressionNumber,
                    streamNumber);
                forge = validated.TimePeriodComputeForge;
            }
            else {
                var validated = ViewForgeSupport.ValidateExpr(
                    viewName,
                    expression,
                    streamTypeService,
                    viewForgeEnv,
                    expressionNumber,
                    streamNumber);
                var returnType = validated.Forge.EvaluationType.GetBoxedType();
                if (!returnType.IsNumeric()) {
                    throw new ViewParameterException(expectedMessage);
                }

                if (validated.Forge.ForgeConstantType.IsCompileTimeConstant) {
                    var timeAbacus = viewForgeEnv.ImportServiceCompileTime.TimeAbacus;
                    var secondsEvaluator = validated.Forge.ExprEvaluator;
                    var time = ViewForgeSupport.Evaluate(secondsEvaluator, 0, viewName);
                    if (!time.IsNumber()) {
                        throw new IllegalStateException(nameof(time) + " is not a number");
                    }

                    if (!ExprTimePeriodUtil.ValidateTime(time, timeAbacus)) {
                        throw new ViewParameterException(ExprTimePeriodUtil.GetTimeInvalidMsg(viewName, "view", time));
                    }

                    var msec = timeAbacus.DeltaForSecondsNumber(time);
                    forge = new TimePeriodComputeConstGivenDeltaForge(msec);
                }
                else {
                    forge = new TimePeriodComputeNCGivenExprForge(
                        validated.Forge,
                        viewForgeEnv.ImportServiceCompileTime.TimeAbacus);
                }
            }

            return forge;
        }
コード例 #11
0
        protected override void InitExec(
            string aliasName,
            StatementSpecCompiled spec,
            StatementRawInfo statementRawInfo,
            StatementCompileTimeServices services)
        {
            StreamTypeServiceImpl assignmentTypeService = new StreamTypeServiceImpl(
                new EventType[] {
                    processor.EventTypeRspInputEvents, null,
                    processor.EventTypeRspInputEvents
                },
                new string[] {aliasName, "", INITIAL_VALUE_STREAM_NAME},
                new bool[] {true, true, true},
                true,
                false);
            assignmentTypeService.IsStreamZeroUnambigous = true;
            ExprValidationContext validationContext =
                new ExprValidationContextBuilder(assignmentTypeService, statementRawInfo, services)
                    .WithAllowBindingConsumption(true)
                    .Build();

            // validate update expressions
            FireAndForgetSpecUpdate updateSpec = (FireAndForgetSpecUpdate) spec.Raw.FireAndForgetSpec;
            try {
                foreach (OnTriggerSetAssignment assignment in updateSpec.Assignments) {
                    ExprNode validated = ExprNodeUtilityValidate.GetValidatedSubtree(
                        ExprNodeOrigin.UPDATEASSIGN,
                        assignment.Expression,
                        validationContext);
                    assignment.Expression = validated;
                    EPStatementStartMethodHelperValidate.ValidateNoAggregations(
                        validated,
                        "Aggregation functions may not be used within an update-clause");
                }
            }
            catch (ExprValidationException e) {
                throw new EPException(e.Message, e);
            }

            // make updater
            //TableUpdateStrategy tableUpdateStrategy = null;
            try {
                bool copyOnWrite = processor is FireAndForgetProcessorNamedWindowForge;
                updateHelper = EventBeanUpdateHelperForgeFactory.Make(
                    processor.NamedWindowOrTableName,
                    (EventTypeSPI) processor.EventTypeRspInputEvents,
                    updateSpec.Assignments,
                    aliasName,
                    null,
                    copyOnWrite,
                    statementRawInfo.StatementName,
                    services.EventTypeAvroHandler);
            }
            catch (ExprValidationException e) {
                throw new EPException(e.Message, e);
            }
        }
コード例 #12
0
        public override EPPreparedExecuteIUDSingleStreamExec GetExecutor(FilterSpecCompiled filter, string aliasName)
        {
            var services         = base.Services;
            var processor        = base.Processor;
            var statementContext = base.StatementContext;
            var statementSpec    = base.StatementSpec;
            var updateSpec       = (FireAndForgetSpecUpdate)statementSpec.FireAndForgetSpec;

            var assignmentTypeService = new StreamTypeServiceImpl(
                new EventType[] { processor.EventTypeResultSetProcessor, null, processor.EventTypeResultSetProcessor },
                new string[] { aliasName, "", EPStatementStartMethodOnTrigger.INITIAL_VALUE_STREAM_NAME },
                new bool[] { true, true, true }, services.EngineURI, true);

            assignmentTypeService.IsStreamZeroUnambigous = true;
            var evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext, true);
            var validationContext    = new ExprValidationContext(
                assignmentTypeService, statementContext.EngineImportService,
                statementContext.StatementExtensionServicesContext, null, statementContext.SchedulingService,
                statementContext.VariableService, statementContext.TableService, evaluatorContextStmt,
                statementContext.EventAdapterService, statementContext.StatementName, statementContext.StatementId,
                statementContext.Annotations, statementContext.ContextDescriptor, statementContext.ScriptingService,
                false, false, true, false, null, false);

            // validate update expressions
            try {
                foreach (OnTriggerSetAssignment assignment in updateSpec.Assignments)
                {
                    ExprNode validated = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.UPDATEASSIGN, assignment.Expression, validationContext);
                    assignment.Expression = validated;
                    EPStatementStartMethodHelperValidate.ValidateNoAggregations(validated, "Aggregation functions may not be used within an update-clause");
                }
            } catch (ExprValidationException e) {
                throw new EPException(e.Message, e);
            }

            // make updater
            EventBeanUpdateHelper updateHelper;
            TableUpdateStrategy   tableUpdateStrategy = null;

            try {
                bool copyOnWrite = !(processor is FireAndForgetProcessorTable);
                updateHelper = EventBeanUpdateHelperFactory.Make(processor.NamedWindowOrTableName,
                                                                 (EventTypeSPI)processor.EventTypeResultSetProcessor, updateSpec.Assignments, aliasName, null, copyOnWrite, statementContext.StatementName, services.EngineURI, services.EventAdapterService);

                if (processor is FireAndForgetProcessorTable)
                {
                    FireAndForgetProcessorTable tableProcessor = (FireAndForgetProcessorTable)processor;
                    tableUpdateStrategy = services.TableService.GetTableUpdateStrategy(tableProcessor.TableMetadata, updateHelper, false);
                    copyOnWrite         = false;
                }
            } catch (ExprValidationException e) {
                throw new EPException(e.Message, e);
            }

            return(new EPPreparedExecuteIUDSingleStreamExecUpdate(filter, statementSpec.FilterRootNode, statementSpec.Annotations, updateHelper, tableUpdateStrategy, statementSpec.TableNodes, services));
        }
コード例 #13
0
ファイル: PerforatorMain.cs プロジェクト: qinfengzhu/nesper
        private static void PerformanceTestIdentNode()
        {
            var bidData    = new BidData("IBM", 0L, 0.50);
            var identNode1 = new ExprIdentNodeImpl("BidPrice");

            var bidDataEventType  = _espServiceProvider.EventAdapterService.GetEventTypeByName("BidData");
            var streamTypeService = new StreamTypeServiceImpl(bidDataEventType, null, false, null);

            identNode1.Validate(
                new ExprValidationContext(
                    _container,
                    streamTypeService,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    null,
                    -1,
                    null,
                    null,
                    null,
                    false,
                    false,
                    false,
                    false,
                    null,
                    false
                    ));

            var exprEvaluatorContext = (ExprEvaluatorContext)null;

            Console.WriteLine("IdentNode");

            for (var nn = 0; nn < 10; nn++)
            {
                var eventBean  = new BeanEventBean(bidData, bidDataEventType);
                var eventBeans = new EventBean[] { eventBean };
                var timeItem   = PerformanceObserver.TimeMicro(
                    delegate
                {
                    for (var ii = 1000000; ii >= 0; ii--)
                    {
                        identNode1.ExprEvaluator.Evaluate(
                            new EvaluateParams(eventBeans, false, exprEvaluatorContext));
                    }
                });

                Console.WriteLine("time: {0} {1:N3} {2:N3}", timeItem, timeItem / 1000000.0m, 1000000.0m / timeItem);
            }
        }
コード例 #14
0
        public ExprNode CompileValidate(
            string expression,
            EventType[] eventTypes,
            string[] streamNames)
        {
            var services = new StatementCompileTimeServices(0, moduleServices);

            ExprNode node;
            try {
                node = services.CompilerServices.CompileExpression(expression, services);
            }
            catch (ExprValidationException e) {
                throw new EPCompileException(
                    "Failed to compile expression '" + expression + "': " + e.Message,
                    e,
                    new EmptyList<EPCompileExceptionItem>());
            }

            try {
                ExprNodeUtilityValidate.ValidatePlainExpression(ExprNodeOrigin.API, node);

                StreamTypeService streamTypeService;

                if (eventTypes == null || eventTypes.Length == 0) {
                    streamTypeService = new StreamTypeServiceImpl(true);
                }
                else {
                    var istreamOnly = new bool[eventTypes.Length];
                    istreamOnly.Fill(true);
                    streamTypeService = new StreamTypeServiceImpl(eventTypes, streamNames, istreamOnly, true, false);
                }
                
                var statementRawInfo = new StatementRawInfo(
                    0,
                    "API-provided",
                    null,
                    StatementType.INTERNAL_USE_API_COMPILE_EXPR,
                    null,
                    null,
                    new CompilableEPL(expression),
                    "API-provided");
                var validationContext = new ExprValidationContextBuilder(streamTypeService, statementRawInfo, services).Build();
                node = ExprNodeUtilityValidate.GetValidatedSubtree(ExprNodeOrigin.API, node, validationContext);
            }
            catch (ExprValidationException e) {
                throw new EPCompileException(
                    "Failed to validate expression '" + expression + "': " + e.Message,
                    e,
                    new EmptyList<EPCompileExceptionItem>());
            }

            return node;
        }
コード例 #15
0
        private static EventAdvancedIndexProvisionCompileTime ValidateAdvanced(
            string indexName,
            string indexType,
            CreateIndexItem columnDesc,
            EventType eventType,
            StatementRawInfo statementRawInfo,
            StatementCompileTimeServices services)
        {
            // validate index expressions: valid and plain expressions
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(eventType, null, false);
            var validationContextColumns =
                new ExprValidationContextBuilder(streamTypeService, statementRawInfo, services)
                    .WithDisablePropertyExpressionEventCollCache(true)
                    .Build();
            var columns = columnDesc.Expressions.ToArray();
            ExprNodeUtilityValidate.GetValidatedSubtree(
                ExprNodeOrigin.CREATEINDEXCOLUMN,
                columns,
                validationContextColumns);
            ExprNodeUtilityValidate.ValidatePlainExpression(ExprNodeOrigin.CREATEINDEXCOLUMN, columns);

            // validate parameters, may not depend on props
            ExprNode[] parameters = null;
            if (columnDesc.Parameters != null && !columnDesc.Parameters.IsEmpty()) {
                parameters = columnDesc.Parameters.ToArray();
                ExprNodeUtilityValidate.GetValidatedSubtree(
                    ExprNodeOrigin.CREATEINDEXPARAMETER,
                    parameters,
                    validationContextColumns);
                ExprNodeUtilityValidate.ValidatePlainExpression(ExprNodeOrigin.CREATEINDEXPARAMETER, parameters);

                // validate no stream dependency of parameters
                var visitor = new ExprNodeIdentifierAndStreamRefVisitor(false);
                foreach (var param in columnDesc.Parameters) {
                    param.Accept(visitor);
                    if (!visitor.Refs.IsEmpty()) {
                        throw new ExprValidationException("Index parameters may not refer to event properties");
                    }
                }
            }

            // obtain provider
            AdvancedIndexFactoryProvider provider;
            try {
                provider = services.ImportServiceCompileTime.ResolveAdvancedIndexProvider(indexType);
            }
            catch (ImportException ex) {
                throw new ExprValidationException(ex.Message, ex);
            }

            return provider.ValidateEventIndex(indexName, indexType, columns, parameters);
        }
コード例 #16
0
ファイル: CreateWindowUtil.cs プロジェクト: lanicon/nesper
        private static IList<NamedWindowSelectedProps> CompileLimitedSelect(
            SelectFromInfo selectFromInfo,
            StatementBaseInfo @base,
            StatementCompileTimeServices compileTimeServices)
        {
            IList<NamedWindowSelectedProps> selectProps = new List<NamedWindowSelectedProps>();
            StreamTypeService streams = new StreamTypeServiceImpl(
                new[] {selectFromInfo.EventType},
                new[] {"stream_0"},
                new[] {false},
                false,
                false);

            var validationContext =
                new ExprValidationContextBuilder(streams, @base.StatementRawInfo, compileTimeServices).Build();
            foreach (var item in @base.StatementSpec.SelectClauseCompiled.SelectExprList) {
                if (!(item is SelectClauseExprCompiledSpec)) {
                    continue;
                }

                var exprSpec = (SelectClauseExprCompiledSpec) item;
                var validatedExpression = ExprNodeUtilityValidate.GetValidatedSubtree(
                    ExprNodeOrigin.SELECT,
                    exprSpec.SelectExpression,
                    validationContext);

                // determine an element name if none assigned
                var asName = exprSpec.ProvidedName;
                if (asName == null) {
                    asName = ExprNodeUtilityPrint.ToExpressionStringMinPrecedenceSafe(validatedExpression);
                }

                // check for fragments
                EventType fragmentType = null;
                if (validatedExpression is ExprIdentNode && !(selectFromInfo.EventType is NativeEventType)) {
                    var identNode = (ExprIdentNode) validatedExpression;
                    var fragmentEventType = selectFromInfo.EventType.GetFragmentType(identNode.FullUnresolvedName);
                    if (fragmentEventType != null && !fragmentEventType.IsNative) {
                        fragmentType = fragmentEventType.FragmentType;
                    }
                }

                var validatedElement = new NamedWindowSelectedProps(
                    validatedExpression.Forge.EvaluationType,
                    asName,
                    fragmentType);
                selectProps.Add(validatedElement);
            }

            return selectProps;
        }
コード例 #17
0
        /// <summary>Validate the view parameter expressions and evaluate the expressions returning the result object. </summary>
        /// <param name="viewName">textual name of view</param>
        /// <param name="statementContext">context with statement services</param>
        /// <param name="expressions">view expression parameter to validate</param>
        /// <returns>object result value of parameter expressions</returns>
        /// <throws>ViewParameterException if the expressions fail to validate</throws>
        public static IList <Object> ValidateAndEvaluate(String viewName, StatementContext statementContext, IList <ExprNode> expressions)
        {
            IList <Object>    results           = new List <Object>();
            var               expressionNumber  = 0;
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(statementContext.EngineURI, false);

            foreach (var expr in expressions)
            {
                var result = ValidateAndEvaluateExpr(viewName, statementContext, expr, streamTypeService, expressionNumber);
                results.Add(result);
                expressionNumber++;
            }
            return(results);
        }
コード例 #18
0
        protected override StatementAgentInstanceFactoryResult NewContextInternal(AgentInstanceContext agentInstanceContext, bool isRecoveringResilient)
        {
            StopCallback stopCallback = new ProxyStopCallback(() => _services.VariableService.DeallocateVariableState(_variableMetaData.VariableName, agentInstanceContext.AgentInstanceId));

            _services.VariableService.AllocateVariableState(
                _variableMetaData.VariableName, agentInstanceContext.AgentInstanceId, _statementContext.StatementExtensionServicesContext, isRecoveringResilient);

            CreateVariableView createView = new CreateVariableView(
                _statementContext.StatementId,
                _services.EventAdapterService,
                _services.VariableService,
                _createDesc.VariableName,
                _statementContext.StatementResultService,
                agentInstanceContext.AgentInstanceId);

            _services.VariableService.RegisterCallback(_createDesc.VariableName, agentInstanceContext.AgentInstanceId, createView.Update);
            _statementContext.StatementStopService.StatementStopped += () => _services.VariableService.UnregisterCallback(_createDesc.VariableName, 0, createView.Update);

            // Create result set processor, use wildcard selection
            _statementSpec.SelectClauseSpec.SetSelectExprList(new SelectClauseElementWildcard());
            _statementSpec.SelectStreamDirEnum = SelectClauseStreamSelectorEnum.RSTREAM_ISTREAM_BOTH;
            var typeService = new StreamTypeServiceImpl(new EventType[] { createView.EventType }, new string[] { "create_variable" }, new bool[] { true }, _services.EngineURI, false);
            OutputProcessViewBase outputViewBase;

            try {
                ResultSetProcessorFactoryDesc resultSetProcessorPrototype = ResultSetProcessorFactoryFactory.GetProcessorPrototype(
                    _statementSpec, _statementContext, typeService, null, new bool[0], true, ContextPropertyRegistryImpl.EMPTY_REGISTRY, null, _services.ConfigSnapshot, _services.ResultSetProcessorHelperFactory, false, false);
                ResultSetProcessor resultSetProcessor = EPStatementStartMethodHelperAssignExpr.GetAssignResultSetProcessor(agentInstanceContext, resultSetProcessorPrototype, false, null, false);

                // Attach output view
                OutputProcessViewFactory outputViewFactory = OutputProcessViewFactoryFactory.Make(
                    _statementSpec,
                    _services.InternalEventRouter,
                    agentInstanceContext.StatementContext,
                    resultSetProcessor.ResultEventType, null,
                    _services.TableService,
                    resultSetProcessorPrototype.ResultSetProcessorFactory.ResultSetProcessorType,
                    _services.ResultSetProcessorHelperFactory,
                    _services.StatementVariableRefService);
                outputViewBase = outputViewFactory.MakeView(resultSetProcessor, agentInstanceContext);
                createView.AddView(outputViewBase);
            }
            catch (ExprValidationException ex)
            {
                throw new EPException("Unexpected exception in create-variable context allocation: " + ex.Message, ex);
            }

            return(new StatementAgentInstanceFactoryCreateVariableResult(outputViewBase, stopCallback, agentInstanceContext));
        }
コード例 #19
0
        public DataFlowOpForgeInitializeResult InitializeForge(DataFlowOpForgeInitializeContext context)
        {
            if (context.OutputPorts.Count != 1) {
                throw new ArgumentException(
                    "EventBusSource operator requires one output stream but produces " +
                    context.OutputPorts.Count +
                    " streams");
            }

            var portZero = context.OutputPorts[0];
            if (portZero.OptionalDeclaredType == null || portZero.OptionalDeclaredType.EventType == null) {
                throw new ArgumentException(
                    "EventBusSource operator requires an event type declated for the output stream");
            }

            var eventType = portZero.OptionalDeclaredType.EventType;
            if (!portZero.OptionalDeclaredType.IsUnderlying) {
                submitEventBean = true;
            }

            DataFlowParameterValidation.Validate("filter", filter, eventType, typeof(bool), context);

            try {
                IList<ExprNode> filters = EmptyList<ExprNode>.Instance;
                if (filter != null) {
                    filters = Collections.SingletonList(filter);
                }

                var streamTypeService = new StreamTypeServiceImpl(eventType, eventType.Name, true);
                var compiledDesc = FilterSpecCompiler.MakeFilterSpec(
                    eventType,
                    eventType.Name,
                    filters,
                    null,
                    null,
                    null,
                    null,
                    streamTypeService,
                    null,
                    context.StatementRawInfo,
                    context.Services);
                FilterSpecCompiled = compiledDesc.FilterSpecCompiled;
            }
            catch (ExprValidationException ex) {
                throw new ExprValidationException("Failed to obtain filter parameters: " + ex.Message, ex);
            }

            return null;
        }
コード例 #20
0
        private static StreamTypeService GetInsertStreamService(
            string optionalStreamName,
            string namedWindowName,
            StreamTypeService insertOnlyTypeSvc,
            StreamTypeServiceImpl twoStreamTypeSvc)
        {
            if (optionalStreamName == null ||
                optionalStreamName.Equals(
                    namedWindowName,
                    StringComparison.InvariantCultureIgnoreCase)) {
                // if no name was provided in "insert into NAME" or the name is the named window we use the empty type in the first column
                return insertOnlyTypeSvc;
            }

            return twoStreamTypeSvc;
        }
コード例 #21
0
        public static ExprNode[] Validate(
            string viewName,
            StatementContext statementContext,
            IList <ExprNode> expressions)
        {
            var results           = new ExprNode[expressions.Count];
            int expressionNumber  = 0;
            var streamTypeService = new StreamTypeServiceImpl(statementContext.EngineURI, false);

            foreach (ExprNode expr in expressions)
            {
                results[expressionNumber] = ValidateExpr(
                    viewName, statementContext, expr, streamTypeService, expressionNumber);
                expressionNumber++;
            }
            return(results);
        }
コード例 #22
0
 public static ExprTimePeriodEvalDeltaConstFactory ValidateAndEvaluateTimeDeltaFactory(
     string viewName,
     StatementContext statementContext,
     ExprNode expression,
     string expectedMessage,
     int expressionNumber)
 {
     var streamTypeService = new StreamTypeServiceImpl(statementContext.EngineURI, false);
     ExprTimePeriodEvalDeltaConstFactory factory;
     if (expression is ExprTimePeriod)
     {
         var validated = (ExprTimePeriod) ViewFactorySupport.ValidateExpr(
             viewName, statementContext, expression, streamTypeService, expressionNumber);
         factory = validated.ConstEvaluator(new ExprEvaluatorContextStatement(statementContext, false));
     }
     else
     {
         var validated = ViewFactorySupport.ValidateExpr(
             viewName, statementContext, expression, streamTypeService, expressionNumber);
         var secondsEvaluator = validated.ExprEvaluator;
         var returnType = secondsEvaluator.ReturnType.GetBoxedType();
         if (!returnType.IsNumeric())
         {
             throw new ViewParameterException(expectedMessage);
         }
         if (validated.IsConstantResult)
         {
             var time = ViewFactorySupport.Evaluate(secondsEvaluator, 0, viewName, statementContext);
             if (!ExprTimePeriodUtil.ValidateTime(time, statementContext.TimeAbacus))
             {
                 throw new ViewParameterException(ExprTimePeriodUtil.GetTimeInvalidMsg(viewName, "view", time));
             }
             var msec = statementContext.TimeAbacus.DeltaForSecondsNumber(time);
             factory = new ExprTimePeriodEvalDeltaConstGivenDelta(msec);
         }
         else
         {
             factory = new ExprTimePeriodEvalDeltaConstFactoryMsec(secondsEvaluator, statementContext.TimeAbacus);
         }
     }
     return factory;
 }
コード例 #23
0
        private static ExprValidationContext GetValidationContext(EventType eventType, StatementContext statementContext)
        {
            var streamTypeService = new StreamTypeServiceImpl(eventType, null, false, statementContext.EngineURI);

            return(new ExprValidationContext(
                       statementContext.Container,
                       streamTypeService,
                       statementContext.EngineImportService,
                       statementContext.StatementExtensionServicesContext, null,
                       statementContext.TimeProvider,
                       statementContext.VariableService,
                       statementContext.TableService,
                       new ExprEvaluatorContextStatement(statementContext, false),
                       statementContext.EventAdapterService,
                       statementContext.StatementName,
                       statementContext.StatementId,
                       statementContext.Annotations,
                       statementContext.ContextDescriptor,
                       statementContext.ScriptingService,
                       true, false, false, false, null, false));
        }
コード例 #24
0
ファイル: EPLValidationUtil.cs プロジェクト: lanicon/nesper
        public static QueryGraphForge ValidateFilterGetQueryGraphSafe(
            ExprNode filterExpression,
            StreamTypeServiceImpl typeService,
            StatementRawInfo statementRawInfo,
            StatementCompileTimeServices services)
        {
            ExcludePlanHint excludePlanHint = null;
            try {
                excludePlanHint = ExcludePlanHint.GetHint(typeService.StreamNames, statementRawInfo, services);
            }
            catch (ExprValidationException ex) {
                Log.Warn("Failed to consider exclude-plan hint: " + ex.Message, ex);
            }

            var queryGraph = new QueryGraphForge(1, excludePlanHint, false);
            if (filterExpression != null) {
                ValidateFilterWQueryGraphSafe(queryGraph, filterExpression, typeService, statementRawInfo, services);
            }

            return queryGraph;
        }
コード例 #25
0
 public ExprValidationContext(StreamTypeServiceImpl types, ExprValidationContext ctx)
     : this(
         types,
         ctx.MethodResolutionService,
         ctx.ViewResourceDelegate,
         ctx.TimeProvider,
         ctx.VariableService,
         ctx.TableService,
         ctx.ExprEvaluatorContext,
         ctx.EventAdapterService,
         ctx.StatementName,
         ctx.StatementId,
         ctx.Annotations,
         ctx.ContextDescriptor,
         ctx.ScriptingService,
         ctx.IsDisablePropertyExpressionEventCollCache, false,
         ctx.IsAllowBindingConsumption,
         ctx.IsResettingAggregations,
         ctx.IntoTableName,
         false)
 {
 }
コード例 #26
0
        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);
        }
コード例 #27
0
ファイル: ViewForgeSupport.cs プロジェクト: lanicon/nesper
        public static ExprNode[] Validate(
            string viewName,
            IList<ExprNode> expressions,
            ViewForgeEnv viewForgeEnv,
            int streamNumber)
        {
            var results = new ExprNode[expressions.Count];
            var expressionNumber = 0;
            StreamTypeService streamTypeService = new StreamTypeServiceImpl(false);
            foreach (var expr in expressions) {
                results[expressionNumber] = ValidateExpr(
                    viewName,
                    expr,
                    streamTypeService,
                    viewForgeEnv,
                    expressionNumber,
                    streamNumber);
                expressionNumber++;
            }

            return results;
        }
コード例 #28
0
ファイル: EPLValidationUtil.cs プロジェクト: lanicon/nesper
        public static ExprNode ValidateSimpleGetSubtree(
            ExprNodeOrigin origin,
            ExprNode expression,
            EventType optionalEventType,
            bool allowBindingConsumption,
            StatementRawInfo statementRawInfo,
            StatementCompileTimeServices services)
        {
            ExprNodeUtilityValidate.ValidatePlainExpression(origin, expression);

            StreamTypeServiceImpl streamTypes;
            if (optionalEventType != null) {
                streamTypes = new StreamTypeServiceImpl(optionalEventType, null, true);
            }
            else {
                streamTypes = new StreamTypeServiceImpl(false);
            }

            var validationContext = new ExprValidationContextBuilder(streamTypes, statementRawInfo, services)
                .WithAllowBindingConsumption(allowBindingConsumption)
                .Build();
            return ExprNodeUtilityValidate.GetValidatedSubtree(origin, expression, validationContext);
        }
コード例 #29
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);
            }
        }
コード例 #30
0
        private ExprDotEvalParam GetBodyAndParameter(
            String enumMethodUsedName,
            int parameterNum,
            ExprNode parameterNode,
            EventType inputEventType,
            Type collectionComponentType,
            ExprValidationContext validationContext,
            IList <ExprDotEvalParam> priorParameters,
            DotMethodFP footprint)
        {
            // handle an expression that is a constant or other (not =>)
            if (!(parameterNode is ExprLambdaGoesNode))
            {
                // no node subtree validation is required here, the chain parameter validation has taken place in ExprDotNode.validate
                // validation of parameter types has taken place in footprint matching
                return(new ExprDotEvalParamExpr(parameterNum, parameterNode, parameterNode.ExprEvaluator));
            }

            var goesNode = (ExprLambdaGoesNode)parameterNode;

            // Get secondary
            var additionalTypes = GetAddStreamTypes(
                enumMethodUsedName, goesNode.GoesToNames, inputEventType, collectionComponentType, priorParameters, validationContext.EventAdapterService);
            var additionalStreamNames = goesNode.GoesToNames.ToArray();

            ValidateDuplicateStreamNames(validationContext.StreamTypeService.StreamNames, additionalStreamNames);

            // add name and type to list of known types
            var addTypes =
                (EventType[])
                CollectionUtil.ArrayExpandAddElements(
                    validationContext.StreamTypeService.EventTypes, additionalTypes);
            var addNames =
                (String[])
                CollectionUtil.ArrayExpandAddElements(
                    validationContext.StreamTypeService.StreamNames, additionalStreamNames);

            var types = new StreamTypeServiceImpl(
                addTypes, addNames, new bool[addTypes.Length], null, false);

            // validate expression body
            var filter = goesNode.ChildNodes[0];

            try
            {
                var filterValidationContext = new ExprValidationContext(types, validationContext);
                filter = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.DECLAREDEXPRBODY, filter, filterValidationContext);
            }
            catch (ExprValidationException ex)
            {
                throw new ExprValidationException(
                          "Error validating enumeration method '" + enumMethodUsedName + "' parameter " + parameterNum + ": " +
                          ex.Message, ex);
            }

            var filterEvaluator = filter.ExprEvaluator;
            var expectedType    = footprint.Parameters[parameterNum].ParamType;

            // Lambda-methods don't use a specific expected return-type, so passing null for type is fine.
            DotMethodUtil.ValidateSpecificType(
                enumMethodUsedName, DotMethodTypeEnum.ENUM, expectedType, null, filterEvaluator.ReturnType, parameterNum,
                filter);

            var numStreamsIncoming = validationContext.StreamTypeService.EventTypes.Length;

            return(new ExprDotEvalParamLambda(
                       parameterNum, filter, filterEvaluator,
                       numStreamsIncoming, goesNode.GoesToNames, additionalTypes));
        }