Пример #1
0
 public static FilterProviderBase GetFilterProvider(string tableName, string filterMemberName, StatementContext modify) {
     FilterProviderBase provider = Providers.Cast<FilterProviderBase>().Where(
         probase => (probase.ObjectType == null || probase.ObjectType.Name == tableName) && probase.FilterMemberName == filterMemberName && (probase.StatementContext == modify || probase.StatementContext == StatementContext.Both)).FirstOrDefault();
     if (provider != null && HasFilterValue(provider) && !provider.UseFilterValueWhenNull)
         return null;
     return provider;
 }
Пример #2
0
 public void Attach(EventType parentEventType, StatementContext statementContext, ViewFactory optionalParentFactory, IList <ViewFactory> parentViewFactories)
 {
 }
Пример #3
0
        private void Login()
        {
            //this._loadingControl.Visibility = System.Windows.Visibility.Visible;
            //this._loadingControl._Refresh();
            try
            {
                if (string.IsNullOrEmpty(_comboBox用户列表.SelectedValue.ToString().Trim()))
                {
                    MessageBox.Show("请先选定用户!");
                    return;
                }
                if (string.IsNullOrEmpty(_textBoxPassword.Password.Trim()))
                {
                    MessageBox.Show("密码不能为空!");
                    return;
                }
                using (StatementContext statement = new StatementContext(typeof(User), typeof(Account)))
                {
                    string userName = _comboBox用户列表.SelectedValue.ToString().Trim();
                    var    users    = statement.Users.Where(o => o.UserName.Trim().Equals(userName));

                    if (users.Count() == 0)
                    {
                        MessageBox.Show(string.Format("数据库错误:本地数据库中不存在用户“{0}”,请联系管理员!", _comboBox用户列表.Text.Trim()));
                    }
                    else if (users.Count() != 1)
                    {
                        MessageBox.Show(string.Format("数据库错误:用户“{0}”在数据库中出现重复数据,请联系管理员!", _comboBox用户列表.Text.Trim()));
                    }
                    else
                    {
                        var user           = users.FirstOrDefault();
                        var passwordServer = user.UserPassword._RSADecrypt();
                        var passwordClient = _textBoxPassword.Password.Trim();
                        if (!passwordServer.Equals(passwordClient))
                        {
                            MessageBox.Show("您输入的密码不正确,请重新输入!");
                            _textBoxPassword.Password = "";
                            _textBoxPassword.Focus();
                            _textProcessMessage.Visibility = System.Windows.Visibility.Hidden;
                            Storyboard story = Resources["OnLoadedStoryboard"] as Storyboard;
                            story.Begin();
                        }
                        else
                        {
                            // 设置会话中的UserId
                            _Session.LoginedUserId = user.Id;

                            //
                            if (statement.Accounts.FirstOrDefault(acc => acc.UserId == user.Id) == null)
                            {
                                if (MessageBox.Show(this, "当前用户没有资金账户,是否添加一个资金账户?", "", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                                {
                                    AddAccountWindow aaf = new AddAccountWindow();
                                    aaf.Owner = this;
                                    aaf.ShowDialog();
                                    //
                                    if (aaf.DialogResult.Value)
                                    {
                                        _Session.SelectedAccountId = Guid.Parse(_Helper.GetParameter(ParameterName.DefaultAccountId.ToString(), new StatementContext(typeof(Account)).Accounts.FirstOrDefault().Id.ToString()));
                                    }
                                    else
                                    {
                                        Show();
                                        return;
                                    }
                                }
                                else
                                {
                                    Show();
                                    return;
                                }
                            }
                            else
                            {
                                _Session.LoginedUserId     = user.Id;
                                _Session.SelectedAccountId = Guid.Parse(_Helper.GetParameter(ParameterName.DefaultAccountId.ToString(), statement.Accounts.FirstOrDefault().Id.ToString()));
                            }

                            MainWindow mw = new MainWindow(this);
                            Hide();
                            mw.ShowDialog();
                            Close();
                            System.Environment.Exit(0);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
            }
            finally
            {
                //this._loadingControl.Visibility = System.Windows.Visibility.Collapsed;
                _textProcessMessage.Visibility = System.Windows.Visibility.Hidden;
                Storyboard story = Resources["OnLoadedStoryboard"] as Storyboard;
                story.Begin();
            }
        }
        public static StreamTypeService BuildDefineStreamTypeServiceDefine(
            StatementContext statementContext,
            LinkedHashMap <String, Pair <int, bool> > variableStreams,
            MatchRecognizeDefineItem defineItem,
            IDictionary <String, ISet <String> > visibilityByIdentifier,
            EventType parentViewType)
        {
            if (!variableStreams.ContainsKey(defineItem.Identifier))
            {
                throw new ExprValidationException("Variable '" + defineItem.Identifier + "' does not occur in pattern");
            }

            var streamNamesDefine = new String[variableStreams.Count + 1];
            var typesDefine       = new EventType[variableStreams.Count + 1];
            var isIStreamOnly     = new bool[variableStreams.Count + 1];

            CompatExtensions.Fill(isIStreamOnly, true);

            var streamNumDefine = variableStreams.Get(defineItem.Identifier).First;

            streamNamesDefine[streamNumDefine] = defineItem.Identifier;
            typesDefine[streamNumDefine]       = parentViewType;

            // add visible single-value
            var visibles             = visibilityByIdentifier.Get(defineItem.Identifier);
            var hasVisibleMultimatch = false;

            if (visibles != null)
            {
                foreach (var visible in visibles)
                {
                    var def = variableStreams.Get(visible);
                    if (!def.Second)
                    {
                        streamNamesDefine[def.First] = visible;
                        typesDefine[def.First]       = parentViewType;
                    }
                    else
                    {
                        hasVisibleMultimatch = true;
                    }
                }
            }

            // compile multi-matching event type (in last position), if any are used
            if (hasVisibleMultimatch)
            {
                IDictionary <String, Object> multievent = new LinkedHashMap <String, Object>();
                foreach (var entry in variableStreams)
                {
                    var identifier = entry.Key;
                    if (entry.Value.Second)
                    {
                        if (visibles.Contains(identifier))
                        {
                            multievent.Put(
                                identifier, new EventType[]
                            {
                                parentViewType
                            });
                        }
                        else
                        {
                            multievent.Put("esper_matchrecog_internal", null);
                        }
                    }
                }
                var multimatch = statementContext.EventAdapterService.CreateAnonymousObjectArrayType(
                    "esper_matchrecog_internal", multievent);
                typesDefine[typesDefine.Length - 1]             = multimatch;
                streamNamesDefine[streamNamesDefine.Length - 1] = multimatch.Name;
            }

            return(new StreamTypeServiceImpl(
                       typesDefine, streamNamesDefine, isIStreamOnly, statementContext.EngineURI, false));
        }
Пример #5
0
        /// <summary>
        /// Validate the view.
        /// </summary>
        /// <param name="engineImportService">The engine import service.</param>
        /// <param name="streamTypeService">supplies the types of streams against which to validate</param>
        /// <param name="methodResolutionService">for resolving imports and classes and methods</param>
        /// <param name="timeProvider">for providing current time</param>
        /// <param name="variableService">for access to variables</param>
        /// <param name="tableService"></param>
        /// <param name="scriptingService">The scripting service.</param>
        /// <param name="exprEvaluatorContext">The expression evaluator context.</param>
        /// <param name="configSnapshot">The config snapshot.</param>
        /// <param name="schedulingService">The scheduling service.</param>
        /// <param name="engineURI">The engine URI.</param>
        /// <param name="sqlParameters">The SQL parameters.</param>
        /// <param name="eventAdapterService">The event adapter service.</param>
        /// <param name="statementContext">The statement context</param>
        /// <throws>  ExprValidationException is thrown to indicate an exception in validating the view </throws>
        public void Validate(EngineImportService engineImportService, StreamTypeService streamTypeService, MethodResolutionService methodResolutionService, TimeProvider timeProvider, VariableService variableService, TableService tableService, ScriptingService scriptingService, ExprEvaluatorContext exprEvaluatorContext, ConfigurationInformation configSnapshot, SchedulingService schedulingService, string engineURI, IDictionary <int, IList <ExprNode> > sqlParameters, EventAdapterService eventAdapterService, StatementContext statementContext)
        {
            _statementContext     = statementContext;
            _evaluators           = new ExprEvaluator[_inputParameters.Count];
            _subordinateStreams   = new SortedSet <int>();
            _exprEvaluatorContext = exprEvaluatorContext;

            var count             = 0;
            var validationContext = new ExprValidationContext(
                streamTypeService, methodResolutionService, null, timeProvider, variableService, tableService,
                exprEvaluatorContext, eventAdapterService,
                statementContext.StatementName,
                statementContext.StatementId,
                statementContext.Annotations, null,
                scriptingService, false, false, true, false, null, false);

            foreach (var inputParam in _inputParameters)
            {
                var raw = FindSQLExpressionNode(_myStreamNumber, count, sqlParameters);
                if (raw == null)
                {
                    throw new ExprValidationException(
                              "Internal error find expression for historical stream parameter " + count + " stream " +
                              _myStreamNumber);
                }
                var evaluator = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.DATABASEPOLL, raw, validationContext);
                _evaluators[count++] = evaluator.ExprEvaluator;

                var visitor = new ExprNodeIdentifierCollectVisitor();
                visitor.Visit(evaluator);
                foreach (var identNode in visitor.ExprProperties)
                {
                    if (identNode.StreamId == _myStreamNumber)
                    {
                        throw new ExprValidationException("Invalid expression '" + inputParam +
                                                          "' resolves to the historical data itself");
                    }
                    _subordinateStreams.Add(identNode.StreamId);
                }
            }
        }
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="statementSpec">is a container for the definition of all statement constructs thatmay have been used in the statement, i.e. if defines the select clauses, insert into, outer joins etc.
        /// </param>
        /// <param name="services">is the service instances for dependency injection</param>
        /// <param name="statementContext">is statement-level information and statement services</param>
        /// <throws>com.espertech.esper.epl.expression.core.ExprValidationException if the preparation failed</throws>
        public EPPreparedExecuteIUDSingleStream(
            StatementSpecCompiled statementSpec,
            EPServicesContext services,
            StatementContext statementContext)
        {
            var queryPlanLogging = services.ConfigSnapshot.EngineDefaults.LoggingConfig.IsEnableQueryPlan;

            if (queryPlanLogging)
            {
                QueryPlanLog.Info("Query plans for Fire-and-forget query '" + statementContext.Expression + "'");
            }

            HasTableAccess = statementSpec.IntoTableSpec != null ||
                             (statementSpec.TableNodes != null && statementSpec.TableNodes.Length > 0);
            if (statementSpec.InsertIntoDesc != null && services.TableService.GetTableMetadata(statementSpec.InsertIntoDesc.EventTypeName) != null)
            {
                HasTableAccess = true;
            }
            if (statementSpec.FireAndForgetSpec is FireAndForgetSpecUpdate ||
                statementSpec.FireAndForgetSpec is FireAndForgetSpecDelete)
            {
                HasTableAccess |= statementSpec.StreamSpecs[0] is TableQueryStreamSpec;
            }

            StatementSpec    = statementSpec;
            Services         = services;
            StatementContext = statementContext;

            // validate general FAF criteria
            EPPreparedExecuteMethodHelper.ValidateFAFQuery(statementSpec);

            // obtain processor
            var streamSpec = statementSpec.StreamSpecs[0];

            Processor = FireAndForgetProcessorFactory.ValidateResolveProcessor(streamSpec, services);

            // obtain name and type
            var processorName = Processor.NamedWindowOrTableName;
            var eventType     = Processor.EventTypeResultSetProcessor;

            // determine alias
            var aliasName = processorName;

            if (streamSpec.OptionalStreamName != null)
            {
                aliasName = streamSpec.OptionalStreamName;
            }

            // compile filter to optimize access to named window
            var typeService = new StreamTypeServiceImpl(new EventType[] { eventType }, new string[] { aliasName }, new bool[] { true }, services.EngineURI, true);
            FilterSpecCompiled filter;

            if (statementSpec.FilterRootNode != null)
            {
                var tagged = new LinkedHashMap <string, Pair <EventType, string> >();
                FilterSpecCompiled filterCompiled;
                try {
                    filterCompiled = FilterSpecCompiler.MakeFilterSpec(eventType, aliasName,
                                                                       Collections.SingletonList(statementSpec.FilterRootNode), null,
                                                                       tagged, tagged, typeService,
                                                                       null, statementContext,
                                                                       Collections.SingletonList(0));
                }
                catch (Exception ex) {
                    Log.Warn("Unexpected exception analyzing filter paths: " + ex.Message, ex);
                    filterCompiled = null;
                }
                filter = filterCompiled;
            }
            else
            {
                filter = null;
            }

            // validate expressions
            EPStatementStartMethodHelperValidate.ValidateNodes(statementSpec, statementContext, typeService, null);

            // get executor
            Executor = GetExecutor(filter, aliasName);
        }
Пример #7
0
 public EventTable[] Index(IList <EventBean> pollResult, bool isActiveCache, StatementContext statementContext)
 {
     return(ProcIndex(pollResult, isActiveCache, statementContext));
 }
Пример #8
0
        private ContextDetailMatchPair ValidateRewriteContextCondition(
            EPServicesContext servicesContext,
            StatementContext statementContext,
            ContextDetailCondition endpoint,
            ISet <string> eventTypesReferenced,
            MatchEventSpec priorMatches,
            ISet <string> priorAllTags)
        {
            if (endpoint is ContextDetailConditionCrontab)
            {
                var crontab = (ContextDetailConditionCrontab)endpoint;
                var scheduleSpecEvaluators = ExprNodeUtility.CrontabScheduleValidate(ExprNodeOrigin.CONTEXTCONDITION, crontab.Crontab, statementContext, false);
                var schedule = ExprNodeUtility.CrontabScheduleBuild(scheduleSpecEvaluators, new ExprEvaluatorContextStatement(statementContext, false));
                crontab.Schedule = schedule;
                return(new ContextDetailMatchPair(crontab, new MatchEventSpec(), new LinkedHashSet <string>()));
            }

            if (endpoint is ContextDetailConditionTimePeriod)
            {
                var timePeriod        = (ContextDetailConditionTimePeriod)endpoint;
                var validationContext =
                    new ExprValidationContext(
                        statementContext.Container,
                        new StreamTypeServiceImpl(servicesContext.EngineURI, false),
                        statementContext.EngineImportService,
                        statementContext.StatementExtensionServicesContext, null,
                        statementContext.SchedulingService,
                        statementContext.VariableService,
                        statementContext.TableService,
                        GetDefaultAgentInstanceContext(statementContext),
                        statementContext.EventAdapterService,
                        statementContext.StatementName, statementContext.StatementId,
                        statementContext.Annotations,
                        statementContext.ContextDescriptor,
                        statementContext.ScriptingService,
                        false, false, false, false,
                        null, false);
                ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.CONTEXTCONDITION, timePeriod.TimePeriod, validationContext);
                if (timePeriod.TimePeriod.IsConstantResult)
                {
                    if (timePeriod.TimePeriod.EvaluateAsSeconds(null, true, null) < 0)
                    {
                        throw new ExprValidationException("Invalid negative time period expression '" + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(timePeriod.TimePeriod) + "'");
                    }
                }
                return(new ContextDetailMatchPair(timePeriod, new MatchEventSpec(), new LinkedHashSet <string>()));
            }

            if (endpoint is ContextDetailConditionPattern)
            {
                var pattern = (ContextDetailConditionPattern)endpoint;
                var matches = ValidatePatternContextConditionPattern(statementContext, pattern, eventTypesReferenced, priorMatches, priorAllTags);
                return(new ContextDetailMatchPair(pattern, matches.First, matches.Second));
            }

            if (endpoint is ContextDetailConditionFilter)
            {
                var filter = (ContextDetailConditionFilter)endpoint;
                ValidateNotTable(servicesContext, filter.FilterSpecRaw.EventTypeName);

                // compile as filter if there are no prior match to consider
                if (priorMatches == null || (priorMatches.ArrayEventTypes.IsEmpty() && priorMatches.TaggedEventTypes.IsEmpty()))
                {
                    var rawExpr  = new FilterStreamSpecRaw(filter.FilterSpecRaw, ViewSpec.EMPTY_VIEWSPEC_ARRAY, null, StreamSpecOptions.DEFAULT);
                    var compiled = (FilterStreamSpecCompiled)rawExpr.Compile(statementContext, eventTypesReferenced, false, Collections.GetEmptyList <int>(), false, true, false, filter.OptionalFilterAsName);
                    filter.FilterSpecCompiled = compiled.FilterSpec;
                    var matchEventSpec = new MatchEventSpec();
                    var filterForType  = compiled.FilterSpec.FilterForEventType;
                    var allTags        = new LinkedHashSet <string>();
                    if (filter.OptionalFilterAsName != null)
                    {
                        matchEventSpec.TaggedEventTypes.Put(filter.OptionalFilterAsName, new Pair <EventType, string>(filterForType, rawExpr.RawFilterSpec.EventTypeName));
                        allTags.Add(filter.OptionalFilterAsName);
                    }
                    return(new ContextDetailMatchPair(filter, matchEventSpec, allTags));
                }

                // compile as pattern if there are prior matches to consider, since this is a type of followed-by relationship
                var factoryNode = servicesContext.PatternNodeFactory.MakeFilterNode(filter.FilterSpecRaw, filter.OptionalFilterAsName, 0);
                var pattern     = new ContextDetailConditionPattern(factoryNode, true, false);
                var matches     = ValidatePatternContextConditionPattern(statementContext, pattern, eventTypesReferenced, priorMatches, priorAllTags);
                return(new ContextDetailMatchPair(pattern, matches.First, matches.Second));
            }
            else if (endpoint is ContextDetailConditionImmediate || endpoint is ContextDetailConditionNever)
            {
                return(new ContextDetailMatchPair(endpoint, new MatchEventSpec(), new LinkedHashSet <string>()));
            }
            else
            {
                throw new IllegalStateException("Unrecognized endpoint type " + endpoint);
            }
        }
        public override EPStatementStartResult StartInternal(
            EPServicesContext services,
            StatementContext statementContext,
            bool isNewStatement,
            bool isRecoveringStatement,
            bool isRecoveringResilient)
        {
            var createDesc = _statementSpec.CreateVariableDesc;

            VariableServiceUtil.CheckAlreadyDeclaredTable(createDesc.VariableName, services.TableService);

            // Get assignment value
            object value = null;

            if (createDesc.Assignment != null)
            {
                // Evaluate assignment expression
                StreamTypeService typeService = new StreamTypeServiceImpl(
                    new EventType[0], new string[0], new bool[0], services.EngineURI, false);
                var evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext, false);
                var validationContext    = new ExprValidationContext(
                    statementContext.Container,
                    typeService,
                    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, false, false, null, false);
                var validated = ExprNodeUtility.GetValidatedSubtree(
                    ExprNodeOrigin.VARIABLEASSIGN, createDesc.Assignment, validationContext);
                value = validated.ExprEvaluator.Evaluate(new EvaluateParams(null, true, evaluatorContextStmt));
            }

            // Create variable
            try
            {
                services.VariableService.CreateNewVariable(
                    _statementSpec.OptionalContextName, createDesc.VariableName, createDesc.VariableType, createDesc.IsConstant,
                    createDesc.IsArray, createDesc.IsArrayOfPrimitive, value, services.EngineImportService);
            }
            catch (VariableExistsException ex)
            {
                // for new statement we don't allow creating the same variable
                if (isNewStatement)
                {
                    throw new ExprValidationException("Cannot create variable: " + ex.Message, ex);
                }
            }
            catch (VariableDeclarationException ex)
            {
                throw new ExprValidationException("Cannot create variable: " + ex.Message, ex);
            }

            var destroyMethod = new EPStatementDestroyCallbackList();
            var stopMethod    = new ProxyEPStatementStopMethod(() => { });

            var      variableMetaData = services.VariableService.GetVariableMetaData(createDesc.VariableName);
            Viewable outputView;
            var      eventType = CreateVariableView.GetEventType(
                statementContext.StatementId, services.EventAdapterService, variableMetaData);
            var contextFactory =
                new StatementAgentInstanceFactoryCreateVariable(
                    createDesc, _statementSpec, statementContext, services, variableMetaData, eventType);

            statementContext.StatementAgentInstanceFactory = contextFactory;

            if (_statementSpec.OptionalContextName != null)
            {
                var mergeView = new ContextMergeView(eventType);
                outputView = mergeView;
                var statement =
                    new ContextManagedStatementCreateVariableDesc(_statementSpec, statementContext, mergeView, contextFactory);
                services.ContextManagementService.AddStatement(
                    _statementSpec.OptionalContextName, statement, isRecoveringResilient);

                var contextManagementService = services.ContextManagementService;
                destroyMethod.AddCallback(new ProxyDestroyCallback(() => contextManagementService.DestroyedStatement(
                                                                       _statementSpec.OptionalContextName, statementContext.StatementName,
                                                                       statementContext.StatementId)));
            }
            else
            {
                var resultOfStart =
                    (StatementAgentInstanceFactoryCreateVariableResult)
                    contextFactory.NewContext(GetDefaultAgentInstanceContext(statementContext), isRecoveringResilient);
                outputView = resultOfStart.FinalView;

                if (statementContext.StatementExtensionServicesContext != null &&
                    statementContext.StatementExtensionServicesContext.StmtResources != null)
                {
                    var holder =
                        statementContext.StatementExtensionServicesContext.ExtractStatementResourceHolder(resultOfStart);
                    statementContext.StatementExtensionServicesContext.StmtResources.Unpartitioned = holder;
                    statementContext.StatementExtensionServicesContext.PostProcessStart(resultOfStart, isRecoveringResilient);
                }
            }

            services.StatementVariableRefService.AddReferences(
                statementContext.StatementName, Collections.SingletonList(createDesc.VariableName), null);
            return(new EPStatementStartResult(outputView, stopMethod, destroyMethod));
        }
Пример #10
0
        public override EPStatementStartResult StartInternal(EPServicesContext services, StatementContext statementContext, bool isNewStatement, bool isRecoveringStatement, bool isRecoveringResilient)
        {
            if (StatementSpec.OptionalContextName != null)
            {
                throw new ExprValidationException("A create-context statement cannot itself be associated to a context, please declare a nested context instead");
            }
            var context = StatementSpec.ContextDesc;
            var agentInstanceContext = GetDefaultAgentInstanceContext(statementContext);

            // compile filter specs, if any
            ISet <String> eventTypesReferenced = new HashSet <String>();

            ValidateContextDetail(services, statementContext, eventTypesReferenced, context.ContextDetail);
            services.StatementEventTypeRefService.AddReferences(statementContext.StatementName, CollectionUtil.ToArray(eventTypesReferenced));

            // define output event type
            var typeName = "EventType_Context_" + context.ContextName;
            var statementResultEventType = services.EventAdapterService.CreateAnonymousMapType(typeName, Collections.GetEmptyMap <String, Object>());

            // add context - does not activate that context
            services.ContextManagementService.AddContextSpec(services, agentInstanceContext, context, isRecoveringResilient, statementResultEventType);

            var stopMethod    = new EPStatementStopMethod(() => { });
            var destroyMethod = new EPStatementDestroyMethod(
                () => services.ContextManagementService.DestroyedContext(context.ContextName));

            return(new EPStatementStartResult(new ZeroDepthStreamNoIterate(statementResultEventType), stopMethod, destroyMethod));
        }
Пример #11
0
        private Pair <MatchEventSpec, ISet <String> > ValidatePatternContextConditionPattern(StatementContext statementContext, ContextDetailConditionPattern pattern, ISet <String> eventTypesReferenced, MatchEventSpec priorMatches, ISet <String> priorAllTags)
        {
            var raw      = new PatternStreamSpecRaw(pattern.PatternRaw, ViewSpec.EMPTY_VIEWSPEC_ARRAY, null, new StreamSpecOptions(), false, false);
            var compiled = raw.Compile(statementContext, eventTypesReferenced, false, Collections.GetEmptyList <int>(), priorMatches, priorAllTags, false, true, false);

            pattern.PatternCompiled = compiled;
            return(new Pair <MatchEventSpec, ISet <String> >(new MatchEventSpec(compiled.TaggedEventTypes, compiled.ArrayEventTypes), compiled.AllTags));
        }
Пример #12
0
 public abstract void Ready(
     StatementContext statementContext,
     ModuleIncidentals moduleIncidentals,
     bool recovery);
        public static EPStatementStartMethodSelectDesc Prepare(
            StatementSpecCompiled statementSpec,
            EPServicesContext services,
            StatementContext statementContext,
            bool recoveringResilient,
            AgentInstanceContext defaultAgentInstanceContext,
            bool queryPlanLogging,
            ViewableActivatorFactory optionalViewableActivatorFactory,
            OutputProcessViewCallback optionalOutputProcessViewCallback,
            SelectExprProcessorDeliveryCallback selectExprProcessorDeliveryCallback)
        {
            // define stop and destroy
            var stopCallbacks    = new List <StopCallback>();
            var destroyCallbacks = new EPStatementDestroyCallbackList();

            // determine context
            var contextName             = statementSpec.OptionalContextName;
            var contextPropertyRegistry = (contextName != null) ? services.ContextManagementService.GetContextDescriptor(contextName).ContextPropertyRegistry : null;

            // Determine stream names for each stream - some streams may not have a name given
            var streamNames = EPStatementStartMethodHelperUtil.DetermineStreamNames(statementSpec.StreamSpecs);
            var numStreams  = streamNames.Length;

            if (numStreams == 0)
            {
                throw new ExprValidationException("The from-clause is required but has not been specified");
            }
            var isJoin     = statementSpec.StreamSpecs.Length > 1;
            var hasContext = statementSpec.OptionalContextName != null;

            // First we create streams for subselects, if there are any
            var subSelectStreamDesc = EPStatementStartMethodHelperSubselect.CreateSubSelectActivation(services, statementSpec, statementContext, destroyCallbacks);

            // Create streams and views
            var eventStreamParentViewableActivators = new ViewableActivator[numStreams];
            var unmaterializedViewChain             = new ViewFactoryChain[numStreams];
            var eventTypeNames           = new string[numStreams];
            var isNamedWindow            = new bool[numStreams];
            var historicalEventViewables = new HistoricalEventViewable[numStreams];

            // verify for joins that required views are present
            var joinAnalysisResult   = VerifyJoinViews(statementSpec, statementContext.NamedWindowMgmtService, defaultAgentInstanceContext);
            var evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext, false);

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

                var isCanIterateUnbound = streamSpec.ViewSpecs.Length == 0 &&
                                          (services.ConfigSnapshot.EngineDefaults.ViewResourcesConfig.IsIterableUnbound ||
                                           AnnotationUtil.FindAttribute(statementSpec.Annotations, typeof(IterableUnboundAttribute)) != null);

                // Create view factories and parent view based on a filter specification
                if (streamSpec is FilterStreamSpecCompiled)
                {
                    var filterStreamSpec = (FilterStreamSpecCompiled)streamSpec;
                    eventTypeNames[i] = filterStreamSpec.FilterSpec.FilterForEventTypeName;

                    // Since only for non-joins we get the existing stream's lock and try to reuse it's views
                    var filterSubselectSameStream = EPStatementStartMethodHelperUtil.DetermineSubquerySameStream(statementSpec, filterStreamSpec);

                    // create activator
                    ViewableActivator activatorDeactivator;
                    if (optionalViewableActivatorFactory != null)
                    {
                        activatorDeactivator = optionalViewableActivatorFactory.CreateActivatorSimple(filterStreamSpec);
                        if (activatorDeactivator == null)
                        {
                            throw new IllegalStateException("Viewable activate is null for " + filterStreamSpec.FilterSpec.FilterForEventType.Name);
                        }
                    }
                    else
                    {
                        if (!hasContext)
                        {
                            activatorDeactivator = services.ViewableActivatorFactory.CreateStreamReuseView(services, statementContext, statementSpec, filterStreamSpec, isJoin, evaluatorContextStmt, filterSubselectSameStream, i, isCanIterateUnbound);
                        }
                        else
                        {
                            InstrumentationAgent instrumentationAgentFilter = null;
                            if (InstrumentationHelper.ENABLED)
                            {
                                var eventTypeName = filterStreamSpec.FilterSpec.FilterForEventType.Name;
                                var streamNumber  = i;
                                instrumentationAgentFilter = new ProxyInstrumentationAgent()
                                {
                                    ProcIndicateQ = () => {
                                        InstrumentationHelper.Get().QFilterActivationStream(eventTypeName, streamNumber);
                                    },
                                    ProcIndicateA = () => {
                                        InstrumentationHelper.Get().AFilterActivationStream();
                                    },
                                };
                            }

                            activatorDeactivator = services.ViewableActivatorFactory.CreateFilterProxy(services, filterStreamSpec.FilterSpec, statementSpec.Annotations, false, instrumentationAgentFilter, isCanIterateUnbound, i);
                        }
                    }
                    eventStreamParentViewableActivators[i] = activatorDeactivator;

                    var resultEventType = filterStreamSpec.FilterSpec.ResultEventType;
                    unmaterializedViewChain[i] = services.ViewService.CreateFactories(i, resultEventType, streamSpec.ViewSpecs, streamSpec.Options, statementContext, false, -1);
                }
                // Create view factories and parent view based on a pattern expression
                else if (streamSpec is PatternStreamSpecCompiled)
                {
                    var patternStreamSpec = (PatternStreamSpecCompiled)streamSpec;
                    var usedByChildViews  = streamSpec.ViewSpecs.Length > 0 || (statementSpec.InsertIntoDesc != null);
                    var patternTypeName   = statementContext.StatementId + "_pattern_" + i;
                    var eventType         = services.EventAdapterService.CreateSemiAnonymousMapType(patternTypeName, patternStreamSpec.TaggedEventTypes, patternStreamSpec.ArrayEventTypes, usedByChildViews);
                    unmaterializedViewChain[i] = services.ViewService.CreateFactories(i, eventType, streamSpec.ViewSpecs, streamSpec.Options, statementContext, false, -1);

                    var rootFactoryNode = services.PatternNodeFactory.MakeRootNode(patternStreamSpec.EvalFactoryNode);
                    var patternContext  = statementContext.PatternContextFactory.CreateContext(statementContext, i, rootFactoryNode, patternStreamSpec.MatchedEventMapMeta, true);

                    // create activator
                    var patternActivator = services.ViewableActivatorFactory.CreatePattern(patternContext, rootFactoryNode, eventType, EPStatementStartMethodHelperUtil.IsConsumingFilters(patternStreamSpec.EvalFactoryNode), patternStreamSpec.IsSuppressSameEventMatches, patternStreamSpec.IsDiscardPartialsOnMatch, isCanIterateUnbound);
                    eventStreamParentViewableActivators[i] = patternActivator;
                }
                // Create view factories and parent view based on a database SQL statement
                else if (streamSpec is DBStatementStreamSpec)
                {
                    ValidateNoViews(streamSpec, "Historical data");
                    var sqlStreamSpec                  = (DBStatementStreamSpec)streamSpec;
                    var typeConversionHook             = (SQLColumnTypeConversion)TypeHelper.GetAnnotationHook(statementSpec.Annotations, HookType.SQLCOL, typeof(SQLColumnTypeConversion), statementContext.MethodResolutionService);
                    var outputRowConversionHook        = (SQLOutputRowConversion)TypeHelper.GetAnnotationHook(statementSpec.Annotations, HookType.SQLROW, typeof(SQLOutputRowConversion), statementContext.MethodResolutionService);
                    var epStatementAgentInstanceHandle = defaultAgentInstanceContext.EpStatementAgentInstanceHandle;
                    var historicalEventViewable        = DatabasePollingViewableFactory.CreateDBStatementView(
                        statementContext.StatementId, i, sqlStreamSpec,
                        services.DatabaseRefService,
                        services.EventAdapterService,
                        epStatementAgentInstanceHandle,
                        statementContext.Annotations,
                        typeConversionHook,
                        outputRowConversionHook,
                        statementContext.ConfigSnapshot.EngineDefaults.LoggingConfig.IsEnableADO,
                        services.DataCacheFactory,
                        statementContext);
                    historicalEventViewables[i]            = historicalEventViewable;
                    unmaterializedViewChain[i]             = ViewFactoryChain.FromTypeNoViews(historicalEventViewable.EventType);
                    eventStreamParentViewableActivators[i] = services.ViewableActivatorFactory.MakeHistorical(historicalEventViewable);
                    stopCallbacks.Add(historicalEventViewable);
                }
                else if (streamSpec is MethodStreamSpec)
                {
                    ValidateNoViews(streamSpec, "Method data");
                    var methodStreamSpec = (MethodStreamSpec)streamSpec;
                    var epStatementAgentInstanceHandle = defaultAgentInstanceContext.EpStatementAgentInstanceHandle;
                    var historicalEventViewable        = MethodPollingViewableFactory.CreatePollMethodView(
                        i, methodStreamSpec, services.EventAdapterService, epStatementAgentInstanceHandle,
                        statementContext.MethodResolutionService, services.EngineImportService,
                        statementContext.SchedulingService, statementContext.ScheduleBucket, evaluatorContextStmt,
                        statementContext.VariableService, statementContext.ContextName, services.DataCacheFactory,
                        statementContext);
                    historicalEventViewables[i]            = historicalEventViewable;
                    unmaterializedViewChain[i]             = ViewFactoryChain.FromTypeNoViews(historicalEventViewable.EventType);
                    eventStreamParentViewableActivators[i] = services.ViewableActivatorFactory.MakeHistorical(historicalEventViewable);
                    stopCallbacks.Add(historicalEventViewable);
                }
                else if (streamSpec is TableQueryStreamSpec)
                {
                    ValidateNoViews(streamSpec, "Table data");
                    var tableStreamSpec = (TableQueryStreamSpec)streamSpec;
                    if (isJoin && tableStreamSpec.FilterExpressions.Count > 0)
                    {
                        throw new ExprValidationException("Joins with tables do not allow table filter expressions, please add table filters to the where-clause instead");
                    }
                    var             metadata         = services.TableService.GetTableMetadata(tableStreamSpec.TableName);
                    ExprEvaluator[] tableFilterEvals = null;
                    if (tableStreamSpec.FilterExpressions.Count > 0)
                    {
                        tableFilterEvals = ExprNodeUtility.GetEvaluators(tableStreamSpec.FilterExpressions);
                    }
                    EPLValidationUtil.ValidateContextName(true, metadata.TableName, metadata.ContextName, statementSpec.OptionalContextName, false);
                    eventStreamParentViewableActivators[i] = services.ViewableActivatorFactory.CreateTable(metadata, tableFilterEvals);
                    unmaterializedViewChain[i]             = ViewFactoryChain.FromTypeNoViews(metadata.InternalEventType);
                    eventTypeNames[i] = tableStreamSpec.TableName;
                    joinAnalysisResult.SetTablesForStream(i, metadata);
                    if (tableStreamSpec.Options.IsUnidirectional)
                    {
                        throw new ExprValidationException("Tables cannot be marked as unidirectional");
                    }
                    if (tableStreamSpec.Options.IsRetainIntersection || tableStreamSpec.Options.IsRetainUnion)
                    {
                        throw new ExprValidationException("Tables cannot be marked with retain");
                    }
                    if (isJoin)
                    {
                        destroyCallbacks.AddCallback(new EPStatementDestroyCallbackTableIdxRef(services.TableService, metadata, statementContext.StatementName));
                    }
                    services.StatementVariableRefService.AddReferences(statementContext.StatementName, metadata.TableName);
                }
                else if (streamSpec is NamedWindowConsumerStreamSpec)
                {
                    var namedSpec       = (NamedWindowConsumerStreamSpec)streamSpec;
                    var processor       = services.NamedWindowMgmtService.GetProcessor(namedSpec.WindowName);
                    var namedWindowType = processor.TailView.EventType;
                    if (namedSpec.OptPropertyEvaluator != null)
                    {
                        namedWindowType = namedSpec.OptPropertyEvaluator.FragmentEventType;
                    }

                    eventStreamParentViewableActivators[i] = services.ViewableActivatorFactory.CreateNamedWindow(processor, namedSpec, statementContext);
                    services.NamedWindowConsumerMgmtService.AddConsumer(statementContext, namedSpec);
                    unmaterializedViewChain[i] = services.ViewService.CreateFactories(i, namedWindowType, namedSpec.ViewSpecs, namedSpec.Options, statementContext, false, -1);
                    joinAnalysisResult.SetNamedWindow(i);
                    eventTypeNames[i] = namedSpec.WindowName;
                    isNamedWindow[i]  = true;

                    // Consumers to named windows cannot declare a data window view onto the named window to avoid duplicate remove streams
                    EPStatementStartMethodHelperValidate.ValidateNoDataWindowOnNamedWindow(unmaterializedViewChain[i].FactoryChain);
                }
                else
                {
                    throw new ExprValidationException("Unknown stream specification type: " + streamSpec);
                }
            }

            // handle match-recognize pattern
            if (statementSpec.MatchRecognizeSpec != null)
            {
                if (isJoin)
                {
                    throw new ExprValidationException("Joins are not allowed when using match-recognize");
                }
                if (joinAnalysisResult.TablesPerStream[0] != null)
                {
                    throw new ExprValidationException("Tables cannot be used with match-recognize");
                }
                var isUnbound = (unmaterializedViewChain[0].FactoryChain.IsEmpty()) && (!(statementSpec.StreamSpecs[0] is NamedWindowConsumerStreamSpec));
                var factoryX  = services.RegexHandlerFactory.MakeViewFactory(unmaterializedViewChain[0], statementSpec.MatchRecognizeSpec, defaultAgentInstanceContext, isUnbound, statementSpec.Annotations, services.ConfigSnapshot.EngineDefaults.MatchRecognizeConfig);
                unmaterializedViewChain[0].FactoryChain.Add(factoryX);

                EPStatementStartMethodHelperAssignExpr.AssignAggregations(factoryX.AggregationService, factoryX.AggregationExpressions);
            }

            // Obtain event types from view factory chains
            var streamEventTypes = new EventType[statementSpec.StreamSpecs.Length];

            for (var i = 0; i < unmaterializedViewChain.Length; i++)
            {
                streamEventTypes[i] = unmaterializedViewChain[i].EventType;
            }

            // Add uniqueness information useful for joins
            joinAnalysisResult.AddUniquenessInfo(unmaterializedViewChain, statementSpec.Annotations);

            // Validate sub-select views
            var subSelectStrategyCollection = EPStatementStartMethodHelperSubselect.PlanSubSelect(services, statementContext, queryPlanLogging, subSelectStreamDesc, streamNames, streamEventTypes, eventTypeNames, statementSpec.DeclaredExpressions, contextPropertyRegistry);

            // Construct type information per stream
            StreamTypeService typeService      = new StreamTypeServiceImpl(streamEventTypes, streamNames, EPStatementStartMethodHelperUtil.GetHasIStreamOnly(isNamedWindow, unmaterializedViewChain), services.EngineURI, false);
            var viewResourceDelegateUnverified = new ViewResourceDelegateUnverified();

            // Validate views that require validation, specifically streams that don't have
            // sub-views such as DB SQL joins
            var historicalViewableDesc = new HistoricalViewableDesc(numStreams);

            for (var stream = 0; stream < historicalEventViewables.Length; stream++)
            {
                var historicalEventViewable = historicalEventViewables[stream];
                if (historicalEventViewable == null)
                {
                    continue;
                }
                historicalEventViewable.Validate(
                    services.EngineImportService,
                    typeService,
                    statementContext.MethodResolutionService,
                    statementContext.TimeProvider,
                    statementContext.VariableService, statementContext.TableService,
                    statementContext.ScriptingService, evaluatorContextStmt,
                    services.ConfigSnapshot, services.SchedulingService, services.EngineURI,
                    statementSpec.SqlParameters,
                    statementContext.EventAdapterService, statementContext);
                historicalViewableDesc.SetHistorical(stream, historicalEventViewable.RequiredStreams);
                if (historicalEventViewable.RequiredStreams.Contains(stream))
                {
                    throw new ExprValidationException("Parameters for historical stream " + stream + " indicate that the stream is subordinate to itself as stream parameters originate in the same stream");
                }
            }

            // unidirectional is not supported with into-table
            if (joinAnalysisResult.IsUnidirectional && statementSpec.IntoTableSpec != null)
            {
                throw new ExprValidationException("Into-table does not allow unidirectional joins");
            }

            // Construct a processor for results posted by views and joins, which takes care of aggregation if required.
            // May return null if we don't need to post-process results posted by views or joins.
            var resultSetProcessorPrototypeDesc = ResultSetProcessorFactoryFactory.GetProcessorPrototype(
                statementSpec, statementContext, typeService, viewResourceDelegateUnverified, joinAnalysisResult.UnidirectionalInd, true, contextPropertyRegistry, selectExprProcessorDeliveryCallback, services.ConfigSnapshot, services.ResultSetProcessorHelperFactory, false, false);

            // Validate where-clause filter tree, outer join clause and output limit expression
            EPStatementStartMethodHelperValidate.ValidateNodes(statementSpec, statementContext, typeService, viewResourceDelegateUnverified);

            // Handle 'prior' function nodes in terms of view requirements
            var viewResourceDelegateVerified = EPStatementStartMethodHelperViewResources.VerifyPreviousAndPriorRequirements(unmaterializedViewChain, viewResourceDelegateUnverified);

            // handle join
            JoinSetComposerPrototype joinSetComposerPrototype = null;

            if (numStreams > 1)
            {
                var selectsRemoveStream =
                    statementSpec.SelectStreamSelectorEnum.IsSelectsRStream() ||
                    statementSpec.OutputLimitSpec != null;
                var hasAggregations = !resultSetProcessorPrototypeDesc.AggregationServiceFactoryDesc.Expressions.IsEmpty();
                joinSetComposerPrototype = JoinSetComposerPrototypeFactory.MakeComposerPrototype(
                    statementContext.StatementName, statementContext.StatementId,
                    statementSpec.OuterJoinDescList, statementSpec.FilterRootNode, typeService.EventTypes, streamNames,
                    joinAnalysisResult, queryPlanLogging, statementContext, historicalViewableDesc, defaultAgentInstanceContext,
                    selectsRemoveStream, hasAggregations, services.TableService, false, services.EventTableIndexService.AllowInitIndex(recoveringResilient));
            }

            // obtain factory for output limiting
            var outputViewFactory = OutputProcessViewFactoryFactory.Make(statementSpec, services.InternalEventRouter, statementContext, resultSetProcessorPrototypeDesc.ResultSetProcessorFactory.ResultEventType, optionalOutputProcessViewCallback, services.TableService, resultSetProcessorPrototypeDesc.ResultSetProcessorFactory.ResultSetProcessorType, services.ResultSetProcessorHelperFactory, services.StatementVariableRefService);

            // Factory for statement-context instances
            var factory = new StatementAgentInstanceFactorySelect(
                numStreams, eventStreamParentViewableActivators,
                statementContext, statementSpec, services,
                typeService, unmaterializedViewChain, resultSetProcessorPrototypeDesc, joinAnalysisResult, recoveringResilient,
                joinSetComposerPrototype, subSelectStrategyCollection, viewResourceDelegateVerified, outputViewFactory);

            EPStatementStopMethod stopMethod = new EPStatementStopMethodImpl(statementContext, stopCallbacks);

            return(new EPStatementStartMethodSelectDesc(factory, subSelectStrategyCollection, viewResourceDelegateUnverified, resultSetProcessorPrototypeDesc, stopMethod, destroyCallbacks));
        }
Пример #14
0
        public ViewFactoryChain CreateFactories(int streamNum, EventType parentEventType, ViewSpec[] viewSpecDefinitions, StreamSpecOptions options, StatementContext context, bool isSubquery, int subqueryNumber)
        {
            // Clone the view spec list to prevent parameter modification
            IList <ViewSpec> viewSpecList = new List <ViewSpec>(viewSpecDefinitions);

            // Inspect views and add merge views if required
            ViewServiceHelper.AddMergeViews(viewSpecList);

            // Instantiate factories, not making them aware of each other yet
            var viewFactories = ViewServiceHelper.InstantiateFactories(streamNum, viewSpecList, context, isSubquery, subqueryNumber);

            ViewFactory         parentViewFactory     = null;
            IList <ViewFactory> attachedViewFactories = new List <ViewFactory>();

            for (var i = 0; i < viewFactories.Count; i++)
            {
                var factoryToAttach = viewFactories[i];
                try
                {
                    factoryToAttach.Attach(parentEventType, context, parentViewFactory, attachedViewFactories);
                    attachedViewFactories.Add(viewFactories[i]);
                    parentEventType = factoryToAttach.EventType;
                }
                catch (ViewParameterException ex)
                {
                    var text = "Error attaching view to parent view";
                    if (i == 0)
                    {
                        text = "Error attaching view to event stream";
                    }
                    throw new ViewProcessingException(text + ": " + ex.Message, ex);
                }
            }

            // obtain count of data windows
            var dataWindowCount         = 0;
            var firstNonDataWindowIndex = -1;

            for (var i = 0; i < viewFactories.Count; i++)
            {
                var factory = viewFactories[i];
                if (factory is DataWindowViewFactory)
                {
                    dataWindowCount++;
                    continue;
                }
                if ((factory is GroupByViewFactoryMarker) || (factory is MergeViewFactory))
                {
                    continue;
                }
                if (firstNonDataWindowIndex == -1)
                {
                    firstNonDataWindowIndex = i;
                }
            }

            var isAllowMultipleExpiry = context.ConfigSnapshot.EngineDefaults.ViewResources.IsAllowMultipleExpiryPolicies;
            var isRetainIntersection  = options.IsRetainIntersection;
            var isRetainUnion         = options.IsRetainUnion;

            // Set the default to retain-intersection unless allow-multiple-expiry is turned on
            if ((!isAllowMultipleExpiry) && (!isRetainUnion))
            {
                isRetainIntersection = true;
            }

            // handle multiple data windows with retain union.
            // wrap view factories into the union view factory and handle a group-by, if present
            if ((isRetainUnion || isRetainIntersection) && dataWindowCount > 1)
            {
                viewFactories = GetRetainViewFactories(parentEventType, viewFactories, isRetainUnion, context);
            }

            return(new ViewFactoryChain(parentEventType, viewFactories));
        }
Пример #15
0
        private IList <ViewFactory> GetRetainViewFactories(EventType parentEventType, IList <ViewFactory> viewFactories, bool isUnion, StatementContext context)
        {
            ICollection <int>   groupByFactory    = new HashSet <int>();
            ICollection <int>   mergeFactory      = new HashSet <int>();
            IList <ViewFactory> derivedValueViews = new List <ViewFactory>();
            IList <ViewFactory> dataWindowViews   = new List <ViewFactory>();

            for (var i = 0; i < viewFactories.Count; i++)
            {
                var factory = viewFactories[i];
                if (factory is GroupByViewFactoryMarker)
                {
                    groupByFactory.Add(i);
                }
                else if (factory is MergeViewFactoryMarker)
                {
                    mergeFactory.Add(i);
                }
                else if (factory is DataWindowViewFactory)
                {
                    dataWindowViews.Add(factory);
                }
                else
                {
                    derivedValueViews.Add(factory);
                }
            }

            if (groupByFactory.Count > 1)
            {
                throw new ViewProcessingException("Multiple groupwin views are not allowed in conjuntion with multiple data windows");
            }
            if ((groupByFactory.IsNotEmpty()) && (groupByFactory.First() != 0))
            {
                throw new ViewProcessingException("The groupwin view must occur in the first position in conjuntion with multiple data windows");
            }
            if ((groupByFactory.IsNotEmpty()) && (mergeFactory.First() != (viewFactories.Count - 1)))
            {
                throw new ViewProcessingException("The merge view cannot be used in conjuntion with multiple data windows");
            }

            GroupByViewFactoryMarker groupByViewFactory = null;
            MergeViewFactoryMarker   mergeViewFactory   = null;

            if (groupByFactory.IsNotEmpty())
            {
                groupByViewFactory = (GroupByViewFactoryMarker)viewFactories[0];
                mergeViewFactory   = (MergeViewFactoryMarker)viewFactories[viewFactories.Count - 1];
                viewFactories.RemoveAt(0);
                viewFactories.RemoveAt(viewFactories.Count - 1);
            }

            var container = context.Container;

            ViewFactory retainPolicy;

            if (isUnion)
            {
                var viewFactory = (UnionViewFactory)context.ViewResolutionService.Create(container, "internal", "union");
                viewFactory.ParentEventType = parentEventType;
                viewFactory.ViewFactories   = dataWindowViews;
                retainPolicy = viewFactory;
            }
            else
            {
                var viewFactory = (IntersectViewFactory)context.ViewResolutionService.Create(container, "internal", "intersect");
                viewFactory.ParentEventType = parentEventType;
                viewFactory.ViewFactories   = dataWindowViews;
                retainPolicy = viewFactory;
            }

            IList <ViewFactory> nonRetainViewFactories = new List <ViewFactory>();

            nonRetainViewFactories.Add(retainPolicy);
            if (groupByViewFactory != null)
            {
                nonRetainViewFactories.Insert(0, (ViewFactory)groupByViewFactory);
                nonRetainViewFactories.AddAll(derivedValueViews);
                nonRetainViewFactories.Add((ViewFactory)mergeViewFactory);
            }
            else
            {
                nonRetainViewFactories.AddAll(derivedValueViews);
            }

            return(nonRetainViewFactories);
        }
Пример #16
0
 public ViewableActivator CreateNamedWindow(NamedWindowProcessor processor, NamedWindowConsumerStreamSpec streamSpec, StatementContext statementContext)
 {
     return(new ViewableActivatorNamedWindow(processor, streamSpec.FilterExpressions, streamSpec.OptPropertyEvaluator));
 }
Пример #17
0
 public StatementContextCPPair(int statementId, int agentInstanceId, StatementContext optionalStatementContext)
 {
     StatementId              = statementId;
     AgentInstanceId          = agentInstanceId;
     OptionalStatementContext = optionalStatementContext;
 }
Пример #18
0
 public EPStatementStopMethodImpl(StatementContext statementContext, IList <StopCallback> stopCallbacks)
 {
     _statementContext = statementContext;
     _stopCallbacks    = stopCallbacks.ToArray();
 }
Пример #19
0
        private void ValidateContextDetail(
            EPServicesContext servicesContext,
            StatementContext statementContext,
            ISet <string> eventTypesReferenced,
            ContextDetail contextDetail,
            AgentInstanceContext agentInstanceContext)
        {
            if (contextDetail is ContextDetailPartitioned)
            {
                var segmented = (ContextDetailPartitioned)contextDetail;
                foreach (var partition in segmented.Items)
                {
                    ValidateNotTable(servicesContext, partition.FilterSpecRaw.EventTypeName);
                    var raw      = new FilterStreamSpecRaw(partition.FilterSpecRaw, ViewSpec.EMPTY_VIEWSPEC_ARRAY, null, StreamSpecOptions.DEFAULT);
                    var compiled = raw.Compile(statementContext, eventTypesReferenced, false, Collections.GetEmptyList <int>(), false, true, false, null);
                    if (!(compiled is FilterStreamSpecCompiled))
                    {
                        throw new ExprValidationException("Partition criteria may not include named windows");
                    }
                    var result = (FilterStreamSpecCompiled)compiled;
                    partition.FilterSpecCompiled = result.FilterSpec;
                }
            }
            else if (contextDetail is ContextDetailCategory)
            {
                // compile filter
                var category = (ContextDetailCategory)contextDetail;
                ValidateNotTable(servicesContext, category.FilterSpecRaw.EventTypeName);
                var raw    = new FilterStreamSpecRaw(category.FilterSpecRaw, ViewSpec.EMPTY_VIEWSPEC_ARRAY, null, StreamSpecOptions.DEFAULT);
                var result = (FilterStreamSpecCompiled)raw.Compile(statementContext, eventTypesReferenced, false, Collections.GetEmptyList <int>(), false, true, false, null);
                category.FilterSpecCompiled = result.FilterSpec;
                servicesContext.StatementEventTypeRefService.AddReferences(statementContext.StatementName, CollectionUtil.ToArray(eventTypesReferenced));

                // compile expressions
                foreach (var item in category.Items)
                {
                    ValidateNotTable(servicesContext, category.FilterSpecRaw.EventTypeName);
                    var filterSpecRaw = new FilterSpecRaw(category.FilterSpecRaw.EventTypeName, Collections.SingletonList(item.Expression), null);
                    var rawExpr       = new FilterStreamSpecRaw(filterSpecRaw, ViewSpec.EMPTY_VIEWSPEC_ARRAY, null, StreamSpecOptions.DEFAULT);
                    var compiled      = (FilterStreamSpecCompiled)rawExpr.Compile(statementContext, eventTypesReferenced, false, Collections.GetEmptyList <int>(), false, true, false, null);
                    item.SetCompiledFilter(compiled.FilterSpec, agentInstanceContext);
                }
            }
            else if (contextDetail is ContextDetailHash)
            {
                var hashed = (ContextDetailHash)contextDetail;
                foreach (var hashItem in hashed.Items)
                {
                    var raw = new FilterStreamSpecRaw(hashItem.FilterSpecRaw, ViewSpec.EMPTY_VIEWSPEC_ARRAY, null, StreamSpecOptions.DEFAULT);
                    ValidateNotTable(servicesContext, hashItem.FilterSpecRaw.EventTypeName);
                    var result = (FilterStreamSpecCompiled)raw.Compile(statementContext, eventTypesReferenced, false, Collections.GetEmptyList <int>(), false, true, false, null);
                    hashItem.FilterSpecCompiled = result.FilterSpec;

                    // validate parameters
                    var streamTypes       = new StreamTypeServiceImpl(result.FilterSpec.FilterForEventType, null, true, statementContext.EngineURI);
                    var validationContext = new ExprValidationContext(
                        statementContext.Container,
                        streamTypes,
                        statementContext.EngineImportService,
                        statementContext.StatementExtensionServicesContext, null,
                        statementContext.SchedulingService,
                        statementContext.VariableService, statementContext.TableService,
                        GetDefaultAgentInstanceContext(statementContext),
                        statementContext.EventAdapterService,
                        statementContext.StatementName,
                        statementContext.StatementId,
                        statementContext.Annotations,
                        statementContext.ContextDescriptor,
                        statementContext.ScriptingService,
                        false, false, false, false,
                        null, false);
                    ExprNodeUtility.Validate(ExprNodeOrigin.CONTEXT, Collections.SingletonList(hashItem.Function), validationContext);
                }
            }
            else if (contextDetail is ContextDetailInitiatedTerminated)
            {
                var def            = (ContextDetailInitiatedTerminated)contextDetail;
                var startCondition = ValidateRewriteContextCondition(servicesContext, statementContext, def.Start, eventTypesReferenced, new MatchEventSpec(), new LinkedHashSet <string>());
                var endCondition   = ValidateRewriteContextCondition(servicesContext, statementContext, def.End, eventTypesReferenced, startCondition.Matches, startCondition.AllTags);
                def.Start = startCondition.Condition;
                def.End   = endCondition.Condition;

                if (def.DistinctExpressions != null)
                {
                    if (!(startCondition.Condition is ContextDetailConditionFilter))
                    {
                        throw new ExprValidationException("Distinct-expressions require a stream as the initiated-by condition");
                    }
                    var distinctExpressions = def.DistinctExpressions;
                    if (distinctExpressions.Length == 0)
                    {
                        throw new ExprValidationException("Distinct-expressions have not been provided");
                    }
                    var filter = (ContextDetailConditionFilter)startCondition.Condition;
                    if (filter.OptionalFilterAsName == null)
                    {
                        throw new ExprValidationException("Distinct-expressions require that a stream name is assigned to the stream using 'as'");
                    }
                    var types             = new StreamTypeServiceImpl(filter.FilterSpecCompiled.FilterForEventType, filter.OptionalFilterAsName, true, servicesContext.EngineURI);
                    var validationContext = new ExprValidationContext(
                        statementContext.Container,
                        types,
                        statementContext.EngineImportService,
                        statementContext.StatementExtensionServicesContext, null,
                        statementContext.SchedulingService,
                        statementContext.VariableService,
                        statementContext.TableService,
                        GetDefaultAgentInstanceContext(statementContext),
                        statementContext.EventAdapterService,
                        statementContext.StatementName,
                        statementContext.StatementId,
                        statementContext.Annotations,
                        statementContext.ContextDescriptor,
                        statementContext.ScriptingService,
                        false, false, true, false, null, false
                        );
                    for (var i = 0; i < distinctExpressions.Length; i++)
                    {
                        ExprNodeUtility.ValidatePlainExpression(ExprNodeOrigin.CONTEXTDISTINCT, distinctExpressions[i]);
                        distinctExpressions[i] = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.CONTEXTDISTINCT, distinctExpressions[i], validationContext);
                    }
                }
            }
            else if (contextDetail is ContextDetailNested)
            {
                var nested = (ContextDetailNested)contextDetail;
                foreach (var nestedContext in nested.Contexts)
                {
                    ValidateContextDetail(servicesContext, statementContext, eventTypesReferenced, nestedContext.ContextDetail, agentInstanceContext);
                }
            }
            else
            {
                throw new IllegalStateException("Unrecognized context detail " + contextDetail);
            }
        }
Пример #20
0
        /// <summary>
        /// Validates expression nodes and returns a list of validated nodes.
        /// </summary>
        /// <param name="exprNodeOrigin">The expr node origin.</param>
        /// <param name="exprNodes">is the nodes to validate</param>
        /// <param name="streamTypeService">is provding type information for each stream</param>
        /// <param name="statementContext">context</param>
        /// <param name="taggedEventTypes">pattern tagged types</param>
        /// <param name="arrayEventTypes">@return list of validated expression nodes</param>
        /// <returns>
        /// expr nodes
        /// </returns>
        /// <exception cref="ExprValidationException">
        /// Failed to validate  + EPStatementStartMethodHelperSubselect.GetSubqueryInfoText(count, subselect) + :  + ex.Message
        /// or
        /// Filter expression not returning a boolean value: ' + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(validated) + '
        /// </exception>
        /// <throws>ExprValidationException for validation errors</throws>
        public static IList <ExprNode> ValidateAllowSubquery(
            ExprNodeOrigin exprNodeOrigin,
            IList <ExprNode> exprNodes,
            StreamTypeService streamTypeService,
            StatementContext statementContext,
            IDictionary <string, Pair <EventType, string> > taggedEventTypes,
            IDictionary <string, Pair <EventType, string> > arrayEventTypes)
        {
            IList <ExprNode> validatedNodes = new List <ExprNode>();

            var evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext, false);
            var validationContext    = new ExprValidationContext(
                streamTypeService, statementContext.MethodResolutionService, null, statementContext.TimeProvider,
                statementContext.VariableService,
                statementContext.TableService,
                evaluatorContextStmt,
                statementContext.EventAdapterService,
                statementContext.StatementName,
                statementContext.StatementId,
                statementContext.Annotations,
                statementContext.ContextDescriptor,
                statementContext.ScriptingService,
                false, false, true, false, null, true);

            foreach (var node in exprNodes)
            {
                // Determine subselects
                var visitor = new ExprNodeSubselectDeclaredDotVisitor();
                node.Accept(visitor);

                // Compile subselects
                if (!visitor.Subselects.IsEmpty())
                {
                    // The outer event type is the filtered-type itself
                    var subselectStreamNumber = 2048;
                    var count = -1;
                    foreach (var subselect in visitor.Subselects)
                    {
                        count++;
                        subselectStreamNumber++;
                        try {
                            HandleSubselectSelectClauses(subselectStreamNumber, statementContext, subselect,
                                                         streamTypeService.EventTypes[0], streamTypeService.StreamNames[0], streamTypeService.StreamNames[0],
                                                         taggedEventTypes, arrayEventTypes);
                        }
                        catch (ExprValidationException ex) {
                            throw new ExprValidationException("Failed to validate " + EPStatementStartMethodHelperSubselect.GetSubqueryInfoText(count, subselect) + ": " + ex.Message, ex);
                        }
                    }
                }

                var validated = ExprNodeUtility.GetValidatedSubtree(exprNodeOrigin, node, validationContext);
                validatedNodes.Add(validated);

                if ((validated.ExprEvaluator.ReturnType != typeof(bool?)) && ((validated.ExprEvaluator.ReturnType != typeof(bool))))
                {
                    throw new ExprValidationException("Filter expression not returning a boolean value: '" + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(validated) + "'");
                }
            }

            return(validatedNodes);
        }
Пример #21
0
        public static ViewFactoryContext MakeViewContext()
        {
            StatementContext stmtContext = MakeContext();

            return(new ViewFactoryContext(stmtContext, 1, "somenamespacetest", "somenametest", false, -1, false));
        }
Пример #22
0
        private static void HandleSubselectSelectClauses(
            int subselectStreamNumber,
            StatementContext statementContext,
            ExprSubselectNode subselect,
            EventType outerEventType,
            string outerEventTypeName,
            string outerStreamName,
            IDictionary <string, Pair <EventType, string> > taggedEventTypes,
            IDictionary <string, Pair <EventType, string> > arrayEventTypes)
        {
            var statementSpec    = subselect.StatementSpecCompiled;
            var filterStreamSpec = statementSpec.StreamSpecs[0];

            ViewFactoryChain viewFactoryChain;
            string           subselecteventTypeName = null;

            // construct view factory chain
            try {
                if (statementSpec.StreamSpecs[0] is FilterStreamSpecCompiled)
                {
                    var filterStreamSpecCompiled = (FilterStreamSpecCompiled)statementSpec.StreamSpecs[0];
                    subselecteventTypeName = filterStreamSpecCompiled.FilterSpec.FilterForEventTypeName;

                    // A child view is required to limit the stream
                    if (filterStreamSpec.ViewSpecs.Length == 0)
                    {
                        throw new ExprValidationException("Subqueries require one or more views to limit the stream, consider declaring a length or time window");
                    }

                    // Register filter, create view factories
                    viewFactoryChain       = statementContext.ViewService.CreateFactories(subselectStreamNumber, filterStreamSpecCompiled.FilterSpec.ResultEventType, filterStreamSpec.ViewSpecs, filterStreamSpec.Options, statementContext);
                    subselect.RawEventType = viewFactoryChain.EventType;
                }
                else
                {
                    var namedSpec = (NamedWindowConsumerStreamSpec)statementSpec.StreamSpecs[0];
                    var processor = statementContext.NamedWindowService.GetProcessor(namedSpec.WindowName);
                    viewFactoryChain       = statementContext.ViewService.CreateFactories(0, processor.NamedWindowType, namedSpec.ViewSpecs, namedSpec.Options, statementContext);
                    subselecteventTypeName = namedSpec.WindowName;
                    EPLValidationUtil.ValidateContextName(false, processor.NamedWindowName, processor.ContextName, statementContext.ContextName, true);
                }
            }
            catch (ViewProcessingException ex) {
                throw new ExprValidationException("Error validating subexpression: " + ex.Message, ex);
            }

            // the final event type
            var eventType = viewFactoryChain.EventType;

            // determine a stream name unless one was supplied
            var subexpressionStreamName = filterStreamSpec.OptionalStreamName;

            if (subexpressionStreamName == null)
            {
                subexpressionStreamName = "$subselect_" + subselectStreamNumber;
            }

            // Named windows don't allow data views
            if (filterStreamSpec is NamedWindowConsumerStreamSpec)
            {
                EPStatementStartMethodHelperValidate.ValidateNoDataWindowOnNamedWindow(viewFactoryChain.FactoryChain);
            }

            // Streams event types are the original stream types with the stream zero the subselect stream
            var namesAndTypes = new LinkedHashMap <string, Pair <EventType, string> >();

            namesAndTypes.Put(subexpressionStreamName, new Pair <EventType, string>(eventType, subselecteventTypeName));
            namesAndTypes.Put(outerStreamName, new Pair <EventType, string>(outerEventType, outerEventTypeName));
            if (taggedEventTypes != null)
            {
                foreach (KeyValuePair <string, Pair <EventType, string> > entry in taggedEventTypes)
                {
                    namesAndTypes.Put(entry.Key, new Pair <EventType, string>(entry.Value.First, entry.Value.Second));
                }
            }
            if (arrayEventTypes != null)
            {
                foreach (KeyValuePair <string, Pair <EventType, string> > entry in arrayEventTypes)
                {
                    namesAndTypes.Put(entry.Key, new Pair <EventType, string>(entry.Value.First, entry.Value.Second));
                }
            }
            StreamTypeService subselectTypeService = new StreamTypeServiceImpl(namesAndTypes, statementContext.EngineURI, true, true);
            var viewResourceDelegateSubselect      = new ViewResourceDelegateUnverified();

            subselect.FilterSubqueryStreamTypes = subselectTypeService;

            // Validate select expression
            var selectClauseSpec = subselect.StatementSpecCompiled.SelectClauseSpec;

            if (selectClauseSpec.SelectExprList.Length > 0)
            {
                if (selectClauseSpec.SelectExprList.Length > 1)
                {
                    throw new ExprValidationException("Subquery multi-column select is not allowed in this context.");
                }

                var element = selectClauseSpec.SelectExprList[0];
                if (element is SelectClauseExprCompiledSpec)
                {
                    // validate
                    var compiled             = (SelectClauseExprCompiledSpec)element;
                    var selectExpression     = compiled.SelectExpression;
                    var evaluatorContextStmt = new ExprEvaluatorContextStatement(statementContext, false);
                    var validationContext    = new ExprValidationContext(
                        subselectTypeService, statementContext.MethodResolutionService, viewResourceDelegateSubselect,
                        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);
                    selectExpression        = ExprNodeUtility.GetValidatedSubtree(ExprNodeOrigin.SUBQUERYSELECT, selectExpression, validationContext);
                    subselect.SelectClause  = new ExprNode[] { selectExpression };
                    subselect.SelectAsNames = new string[] { compiled.AssignedName };

                    // handle aggregation
                    var aggExprNodes = new List <ExprAggregateNode>();
                    ExprAggregateNodeUtil.GetAggregatesBottomUp(selectExpression, aggExprNodes);
                    if (aggExprNodes.Count > 0)
                    {
                        // Other stream properties, if there is aggregation, cannot be under aggregation.
                        foreach (var aggNode in aggExprNodes)
                        {
                            var propertiesNodesAggregated = ExprNodeUtility.GetExpressionProperties(aggNode, true);
                            foreach (var pair in propertiesNodesAggregated)
                            {
                                if (pair.First != 0)
                                {
                                    throw new ExprValidationException("Subselect aggregation function cannot aggregate across correlated properties");
                                }
                            }
                        }

                        // This stream (stream 0) properties must either all be under aggregation, or all not be.
                        var propertiesNotAggregated = ExprNodeUtility.GetExpressionProperties(selectExpression, false);
                        foreach (var pair in propertiesNotAggregated)
                        {
                            if (pair.First == 0)
                            {
                                throw new ExprValidationException("Subselect properties must all be within aggregation functions");
                            }
                        }
                    }
                }
            }
        }
Пример #23
0
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="whenExpressionNode">the expression to evaluate, returning true when to output</param>
        /// <param name="assignments">is the optional then-clause variable assignments, or null or empty if none</param>
        /// <throws>ExprValidationException when validation fails</throws>
        public OutputConditionPolledExpressionFactory(ExprNode whenExpressionNode, IList <OnTriggerSetAssignment> assignments, StatementContext statementContext)
        {
            _whenExpressionNode = whenExpressionNode.ExprEvaluator;

            // determine if using properties
            var containsBuiltinProperties = false;

            if (ContainsBuiltinProperties(whenExpressionNode))
            {
                containsBuiltinProperties = true;
            }
            else
            {
                if (assignments != null)
                {
                    foreach (var assignment in assignments)
                    {
                        if (ContainsBuiltinProperties(assignment.Expression))
                        {
                            containsBuiltinProperties = true;
                        }
                    }
                }
            }

            if (containsBuiltinProperties)
            {
                _oatypeBuiltinProperties = statementContext.EventAdapterService.CreateAnonymousObjectArrayType(typeof(OutputConditionPolledExpressionFactory).Name, OutputConditionExpressionTypeUtil.TYPEINFO);
            }
            else
            {
                _oatypeBuiltinProperties = null;
            }

            if (assignments != null)
            {
                _variableReadWritePackage = new VariableReadWritePackage(assignments, statementContext.VariableService, statementContext.EventAdapterService);
            }
            else
            {
                _variableReadWritePackage = null;
            }
        }
Пример #24
0
        public StreamSpecCompiled Compile(StatementContext context, ICollection <String> eventTypeReferences, bool isInsertInto, ICollection <int> assignedTypeNumberStack, bool isJoin, bool isContextDeclaration, bool isOnTrigger, String optionalStreamName)
        {
            StreamTypeService streamTypeService;

            // Determine the event type
            var eventName = _rawFilterSpec.EventTypeName;

            if (context.TableService != null && context.TableService.GetTableMetadata(eventName) != null)
            {
                if (this.ViewSpecs != null && this.ViewSpecs.Length > 0)
                {
                    throw new ExprValidationException("Views are not supported with tables");
                }
                if (this.RawFilterSpec.OptionalPropertyEvalSpec != null)
                {
                    throw new ExprValidationException("Contained-event expressions are not supported with tables");
                }
                var tableMetadata      = context.TableService.GetTableMetadata(eventName);
                var streamTypeServiceX = new StreamTypeServiceImpl(new EventType[] { tableMetadata.InternalEventType }, new String[] { optionalStreamName }, new bool[] { true }, context.EngineURI, false);
                var validatedNodes     = FilterSpecCompiler.ValidateAllowSubquery(ExprNodeOrigin.FILTER, _rawFilterSpec.FilterExpressions, streamTypeServiceX, context, null, null);
                return(new TableQueryStreamSpec(this.OptionalStreamName, this.ViewSpecs, this.Options, eventName, validatedNodes));
            }

            // Could be a named window
            if (context.NamedWindowMgmtService.IsNamedWindow(eventName))
            {
                var namedWindowType = context.NamedWindowMgmtService.GetProcessor(eventName).TailView.EventType;
                streamTypeService = new StreamTypeServiceImpl(new EventType[] { namedWindowType }, new String[] { optionalStreamName }, new bool[] { true }, context.EngineURI, false);

                var validatedNodes = FilterSpecCompiler.ValidateAllowSubquery(
                    ExprNodeOrigin.FILTER, _rawFilterSpec.FilterExpressions, streamTypeService, context, null, null);

                PropertyEvaluator optionalPropertyEvaluator = null;
                if (_rawFilterSpec.OptionalPropertyEvalSpec != null)
                {
                    optionalPropertyEvaluator =
                        PropertyEvaluatorFactory.MakeEvaluator(
                            _rawFilterSpec.OptionalPropertyEvalSpec, namedWindowType, OptionalStreamName,
                            context.EventAdapterService,
                            context.MethodResolutionService,
                            context.TimeProvider,
                            context.VariableService,
                            context.ScriptingService,
                            context.TableService,
                            context.EngineURI,
                            context.StatementId,
                            context.StatementName,
                            context.Annotations, assignedTypeNumberStack,
                            context.ConfigSnapshot,
                            context.NamedWindowMgmtService);
                }
                eventTypeReferences.Add(((EventTypeSPI)namedWindowType).Metadata.PrimaryName);
                return(new NamedWindowConsumerStreamSpec(eventName, OptionalStreamName, ViewSpecs, validatedNodes, Options, optionalPropertyEvaluator));
            }

            EventType eventType = null;

            if (context.ValueAddEventService.IsRevisionTypeName(eventName))
            {
                eventType = context.ValueAddEventService.GetValueAddUnderlyingType(eventName);
                eventTypeReferences.Add(((EventTypeSPI)eventType).Metadata.PrimaryName);
            }

            if (eventType == null)
            {
                eventType = ResolveType(context.EngineURI, eventName, context.EventAdapterService, context.PlugInTypeResolutionURIs);
                if (eventType is EventTypeSPI)
                {
                    eventTypeReferences.Add(((EventTypeSPI)eventType).Metadata.PrimaryName);
                }
            }

            // Validate all nodes, make sure each returns a bool and types are good;
            // Also decompose all AND super nodes into individual expressions
            streamTypeService = new StreamTypeServiceImpl(new EventType[] { eventType }, new String[] { base.OptionalStreamName }, new bool[] { true }, context.EngineURI, false);

            var spec = FilterSpecCompiler.MakeFilterSpec(eventType, eventName, _rawFilterSpec.FilterExpressions, _rawFilterSpec.OptionalPropertyEvalSpec,
                                                         null, null, // no tags
                                                         streamTypeService, OptionalStreamName, context, assignedTypeNumberStack);

            return(new FilterStreamSpecCompiled(spec, ViewSpecs, OptionalStreamName, Options));
        }
Пример #25
0
 public EventTable[] Index(IList <EventBean> pollResult, bool isActiveCache, StatementContext statementContext)
 {
     return(new EventTable[]
     {
         new UnindexedEventTableList(pollResult, -1)
     });
 }
        public static OutputConditionPolledFactory CreateConditionFactory(OutputLimitSpec outputLimitSpec, StatementContext statementContext)
        {
            if (outputLimitSpec == null)
            {
                throw new ArgumentNullException("Output condition by count requires a non-null callback");
            }

            // check variable use
            VariableMetaData variableMetaData = null;

            if (outputLimitSpec.VariableName != null)
            {
                variableMetaData = statementContext.VariableService.GetVariableMetaData(outputLimitSpec.VariableName);
                if (variableMetaData == null)
                {
                    throw new ArgumentException("Variable named '" + outputLimitSpec.VariableName + "' has not been declared");
                }
            }

            if (outputLimitSpec.RateType == OutputLimitRateType.CRONTAB)
            {
                return(new OutputConditionPolledCrontabFactory(outputLimitSpec.CrontabAtSchedule, statementContext));
            }
            else if (outputLimitSpec.RateType == OutputLimitRateType.WHEN_EXPRESSION)
            {
                return(new OutputConditionPolledExpressionFactory(outputLimitSpec.WhenExpressionNode, outputLimitSpec.ThenExpressions, statementContext));
            }
            else if (outputLimitSpec.RateType == OutputLimitRateType.EVENTS)
            {
                int rate = -1;
                if (outputLimitSpec.Rate != null)
                {
                    rate = outputLimitSpec.Rate.AsInt();
                }
                return(new OutputConditionPolledCountFactory(rate, statementContext, outputLimitSpec.VariableName));
            }
            else
            {
                if (variableMetaData != null && (!variableMetaData.VariableType.IsNumeric()))
                {
                    throw new ArgumentException("Variable named '" + outputLimitSpec.VariableName + "' must be of numeric type");
                }
                return(new OutputConditionPolledTimeFactory(outputLimitSpec.TimePeriodExpr, statementContext));
            }
        }
Пример #27
0
 public ContextManagedStatementCreateVariableDesc(StatementSpecCompiled statementSpec, StatementContext statementContext, ContextMergeView mergeView, StatementAgentInstanceFactory factory)
     : base(statementSpec, statementContext, mergeView, factory)
 {
 }
Пример #28
0
        public NamedWindowOnMergeHelper(StatementContext statementContext,
                                        OnTriggerMergeDesc onTriggerDesc,
                                        EventType triggeringEventType,
                                        string triggeringStreamName,
                                        InternalEventRouter internalEventRouter,
                                        string namedWindowName,
                                        EventTypeSPI namedWindowType)

        {
            Matched   = new List <NamedWindowOnMergeMatch>();
            Unmatched = new List <NamedWindowOnMergeMatch>();

            var count = 1;

            foreach (var matchedItem in onTriggerDesc.Items)
            {
                IList <NamedWindowOnMergeAction> actions = new List <NamedWindowOnMergeAction>();
                foreach (var item in matchedItem.Actions)
                {
                    try {
                        if (item is OnTriggerMergeActionInsert)
                        {
                            var insertDesc = (OnTriggerMergeActionInsert)item;
                            actions.Add(SetupInsert(namedWindowName, internalEventRouter, namedWindowType, count, insertDesc, triggeringEventType, triggeringStreamName, statementContext));
                        }
                        else if (item is OnTriggerMergeActionUpdate)
                        {
                            var updateDesc   = (OnTriggerMergeActionUpdate)item;
                            var updateHelper = EventBeanUpdateHelperFactory.Make(namedWindowName, namedWindowType, updateDesc.Assignments, onTriggerDesc.OptionalAsName, triggeringEventType, true);
                            var filterEval   = updateDesc.OptionalWhereClause == null ? null : updateDesc.OptionalWhereClause.ExprEvaluator;
                            actions.Add(new NamedWindowOnMergeActionUpd(filterEval, updateHelper));
                        }
                        else if (item is OnTriggerMergeActionDelete)
                        {
                            var deleteDesc = (OnTriggerMergeActionDelete)item;
                            var filterEval = deleteDesc.OptionalWhereClause == null ? null : deleteDesc.OptionalWhereClause.ExprEvaluator;
                            actions.Add(new NamedWindowOnMergeActionDel(filterEval));
                        }
                        else
                        {
                            throw new ArgumentException("Invalid type of merge item '" + item.GetType() + "'");
                        }
                        count++;
                    }
                    catch (ExprValidationException ex) {
                        var isNot   = item is OnTriggerMergeActionInsert;
                        var message = "Validation failed in when-" + (isNot?"not-":"") + "matched (clause " + count + "): " + ex.Message;
                        throw new ExprValidationException(message, ex);
                    }
                }

                if (matchedItem.IsMatchedUnmatched)
                {
                    Matched.Add(new NamedWindowOnMergeMatch(matchedItem.OptionalMatchCond, actions));
                }
                else
                {
                    Unmatched.Add(new NamedWindowOnMergeMatch(matchedItem.OptionalMatchCond, actions));
                }
            }
        }
Пример #29
0
        private void _linkLabel忘记密码_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            try
            {
                using (StatementContext statement = new StatementContext(typeof(User)))
                {
                    var user = statement.Users.FirstOrDefault(model => model.UserName.Equals(_comboBox用户列表.Text.Trim()));
                    //
                    if (MessageBox.Show(string.Format("是否向用户<{0}>的密保邮箱发送新密码?", user.UserName), "发送新密码确认", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                    {
                        //确定smtp服务器地址。实例化一个Smtp客户端
                        SmtpClient client = new SmtpClient("smtp.163.com");

                        //构造一个发件人地址对象
                        MailAddress from = new MailAddress("*****@*****.**", "期货助手", Encoding.UTF8);
                        //构造一个收件人地址对象
                        MailAddress to = new MailAddress(user.Email, _comboBox用户列表.Text.Trim(), Encoding.UTF8);

                        //构造一个Email的Message对
                        MailMessage message = new MailMessage(from, to);

                        Random random      = new Random();
                        string newPassword = string.Format("{0}{1}{2}{3}{4}{5}", random.Next(10), random.Next(10), random.Next(10), random.Next(10), random.Next(10), random.Next(10));



                        //添加邮件主题和内容
                        message.Subject         = "期货助手 - 新密码";
                        message.SubjectEncoding = Encoding.UTF8;
                        message.Body            = string.Format("您的新密码是:{0}", newPassword);
                        message.BodyEncoding    = Encoding.UTF8;

                        //设置邮件的信息
                        client.DeliveryMethod = SmtpDeliveryMethod.Network;
                        message.BodyEncoding  = System.Text.Encoding.UTF8;
                        message.IsBodyHtml    = false;

                        //设置用户名和密码。
                        client.UseDefaultCredentials = false;
                        string username = "******";
                        string passwd   = "mail351489";
                        //用户登陆信息
                        NetworkCredential myCredentials = new NetworkCredential(username, passwd);
                        client.Credentials = myCredentials;
                        //发送邮件
                        client.Send(message);

                        //
                        user.UserPassword = newPassword._RSAEcrypt();
                        statement.EditUser(user);
                        statement.SaveChanged();

                        //提示发送成功
                        MessageBox.Show("新密码已经发送到您的邮箱中,请及时查收!");
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message + "\n" + ex.StackTrace);
            }
        }
Пример #30
0
        private NamedWindowOnMergeActionIns SetupInsert(
            string namedWindowName,
            InternalEventRouter internalEventRouter,
            EventTypeSPI eventTypeNamedWindow,
            int selectClauseNumber,
            OnTriggerMergeActionInsert desc,
            EventType triggeringEventType,
            string triggeringStreamName,
            StatementContext statementContext)
        {
            // Compile insert-into info
            var 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
            EventType         dummyTypeNoProperties = new MapEventType(EventTypeMetadata.CreateAnonymous("merge_named_window_insert"), "merge_named_window_insert", 0, null, Collections.GetEmptyMap <string, object>(), null, null, null);
            var               eventTypes            = new EventType[] { dummyTypeNoProperties, triggeringEventType };
            var               streamNames           = new string[] { UuidGenerator.Generate(), triggeringStreamName };
            StreamTypeService 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(
                Collections.SingletonSet <int>(selectClauseNumber),
                selectNoWildcard.ToArray(), false, insertIntoDesc, null, null, streamTypeService,
                statementContext.EventAdapterService,
                statementContext.StatementResultService,
                statementContext.ValueAddEventService,
                selectExprEventTypeRegistry,
                statementContext.MethodResolutionService,
                exprEvaluatorContext,
                statementContext.VariableService,
                statementContext.ScriptingService,
                statementContext.TableService,
                statementContext.TimeProvider,
                statementContext.EngineURI,
                statementContext.StatementId,
                statementContext.StatementName,
                statementContext.Annotations,
                statementContext.ContextDescriptor,
                statementContext.ConfigSnapshot, null,
                statementContext.NamedWindowService, null);
            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));
        }
Пример #31
0
        /// <summary>
        /// Creates the viewable for polling via database SQL query.
        /// </summary>
        /// <param name="statementId">The statement id.</param>
        /// <param name="streamNumber">is the stream number of the view</param>
        /// <param name="databaseStreamSpec">provides the SQL statement, database name and additional info</param>
        /// <param name="databaseConfigService">for getting database connection and settings</param>
        /// <param name="eventAdapterService">for generating event beans from database information</param>
        /// <param name="epStatementAgentInstanceHandle">The ep statement agent instance handle.</param>
        /// <param name="contextAttributes">The db attributes.</param>
        /// <param name="columnTypeConversionHook">The column type conversion hook.</param>
        /// <param name="outputRowConversionHook">The output row conversion hook.</param>
        /// <param name="enableAdoLogging">if set to <c>true</c> [enable JDBC logging].</param>
        /// <param name="dataCacheFactory">The data cache factory.</param>
        /// <param name="statementContext">The statement context.</param>
        /// <returns>
        /// viewable providing poll functionality
        /// </returns>
        /// <exception cref="ExprValidationException">the validation failed</exception>
        public static HistoricalEventViewable CreateDBStatementView(
            int statementId,
            int streamNumber,
            DBStatementStreamSpec databaseStreamSpec,
            DatabaseConfigService databaseConfigService,
            EventAdapterService eventAdapterService,
            EPStatementAgentInstanceHandle epStatementAgentInstanceHandle,
            IEnumerable <Attribute> contextAttributes,
            SQLColumnTypeConversion columnTypeConversionHook,
            SQLOutputRowConversion outputRowConversionHook,
            bool enableAdoLogging,
            DataCacheFactory dataCacheFactory,
            StatementContext statementContext)
        {
            // Parse the SQL for placeholders and text fragments
            var            sqlFragments = GetSqlFragments(databaseStreamSpec);
            IList <String> invocationInputParameters = new List <string>();

            foreach (var fragment in sqlFragments)
            {
                if ((fragment.IsParameter) && (fragment.Value != SAMPLE_WHERECLAUSE_PLACEHOLDER))
                {
                    invocationInputParameters.Add(fragment.Value);
                }
            }

            // Get the database information
            var databaseName = databaseStreamSpec.DatabaseName;
            var dbDriver     = GetDatabaseConnectionFactory(databaseConfigService, databaseName).Driver;
            var dbCommand    = dbDriver.CreateCommand(
                sqlFragments,
                GetMetaDataSettings(databaseConfigService, databaseName),
                contextAttributes);

            if (Log.IsDebugEnabled)
            {
                Log.Debug(".CreateDBStatementView dbCommand=" + dbCommand);
            }

            var queryMetaData = GetQueryMetaData(
                databaseStreamSpec,
                databaseConfigService,
                dbCommand,
                contextAttributes);

            Func <SQLColumnTypeContext, Type> columnTypeConversionFunc = null;

            if (columnTypeConversionHook != null)
            {
                columnTypeConversionFunc = columnTypeConversionHook.GetColumnType;
            }

            Func <SQLOutputRowTypeContext, Type> outputRowConversionFunc = null;

            if (outputRowConversionHook != null)
            {
                outputRowConversionFunc = outputRowConversionHook.GetOutputRowType;
            }

            // Construct an event type from SQL query result metadata
            var eventType = CreateEventType(
                statementId,
                streamNumber,
                queryMetaData,
                eventAdapterService,
                databaseStreamSpec,
                columnTypeConversionFunc,
                outputRowConversionFunc);

            // Get a proper connection and data cache
            ConnectionCache connectionCache;
            DataCache       dataCache;

            try
            {
                connectionCache = databaseConfigService.GetConnectionCache(
                    databaseName, dbCommand.PseudoText, contextAttributes);
                dataCache = databaseConfigService.GetDataCache(
                    databaseName, statementContext, epStatementAgentInstanceHandle, dataCacheFactory, streamNumber);
            }
            catch (DatabaseConfigException e)
            {
                const string text = "Error obtaining cache configuration";
                Log.Error(text, e);
                throw new ExprValidationException(text + ", reason: " + e.Message, e);
            }

            var dbPollStrategy = new PollExecStrategyDBQuery(
                eventAdapterService,
                eventType,
                connectionCache,
                dbCommand.CommandText,
                queryMetaData.OutputParameters,
                columnTypeConversionHook,
                outputRowConversionHook);

            return(new DatabasePollingViewable(
                       streamNumber,
                       invocationInputParameters,
                       dbPollStrategy,
                       dataCache,
                       eventType,
                       statementContext.ThreadLocalManager));
        }
Пример #32
0
	public StatementContext statement() {
		StatementContext _localctx = new StatementContext(_ctx, State);
		EnterRule(_localctx, 184, RULE_statement);
		try {
			State = 1061;
			switch ( Interpreter.AdaptivePredict(_input,120,_ctx) ) {
			case 1:
				EnterOuterAlt(_localctx, 1);
				{
				State = 1049; labeled_statement();
				}
				break;

			case 2:
				EnterOuterAlt(_localctx, 2);
				{
				State = 1050; expression();
				State = 1051; Match(SEMI);
				}
				break;

			case 3:
				EnterOuterAlt(_localctx, 3);
				{
				State = 1053; compound_statement();
				}
				break;

			case 4:
				EnterOuterAlt(_localctx, 4);
				{
				State = 1054; selection_statement();
				}
				break;

			case 5:
				EnterOuterAlt(_localctx, 5);
				{
				State = 1055; iteration_statement();
				}
				break;

			case 6:
				EnterOuterAlt(_localctx, 6);
				{
				State = 1056; jump_statement();
				}
				break;

			case 7:
				EnterOuterAlt(_localctx, 7);
				{
				State = 1057; synchronized_statement();
				}
				break;

			case 8:
				EnterOuterAlt(_localctx, 8);
				{
				State = 1058; autorelease_statement();
				}
				break;

			case 9:
				EnterOuterAlt(_localctx, 9);
				{
				State = 1059; try_block();
				}
				break;

			case 10:
				EnterOuterAlt(_localctx, 10);
				{
				State = 1060; Match(SEMI);
				}
				break;
			}
		}
		catch (RecognitionException re) {
			_localctx.exception = re;
			_errHandler.ReportError(this, re);
			_errHandler.Recover(this, re);
		}
		finally {
			ExitRule();
		}
		return _localctx;
	}