Пример #1
0
        private Task ConfigureNEsper()
        {
            return Task.Factory.StartNew(() =>
            {
                Provider = EPServiceProviderManager.GetDefaultProvider();
                Provider.EPAdministrator.Configuration.AddImport<TcpSource>();

                Provider.EPAdministrator.Configuration.AddImport<HostFilter>();
                Provider.EPAdministrator.Configuration.AddImport<EnrichRequestCorrelationFilter>();

                Provider.EPAdministrator.Configuration.AddImport<UnmatchedRequestSink>();
                Provider.EPAdministrator.Configuration.AddImport<RedirectSink>();
                Provider.EPAdministrator.Configuration.AddImport<CatalogRedirectSink>();
                Provider.EPAdministrator.Configuration.AddEventType<HttpContext>("HttpContext");

                var elp1 = Provider.EPAdministrator.CreateEPL($@"create dataflow ArtemisRouting
TcpSource -> requests {{}}
EnrichRequestCorrelationFilter (requests) -> enrichedrequests {{}}
CatalogRedirectSink (enrichedrequests) {{ Use: ""Path"" }}");

                var unity = new UnityContainer();
                unity.RegisterType<IServiceFinder>(new InjectionFactory(x => Catalog));
                unity.RegisterInstance<ILogger>(Logger);
                var dataflowContext = new DataflowContext(unity);

                var init = new com.espertech.esper.client.dataflow.EPDataFlowInstantiationOptions();
                init.SetDataFlowInstanceUserObject(dataflowContext);
                var instance = Provider.EPRuntime.DataFlowRuntime.Instantiate("ArtemisRouting", init);
                instance.Start();
            });
        }
Пример #2
0
        private static void InitializeNesper()
        {
            nesperConf = new com.espertech.esper.client.Configuration();
            nesperConf.AddEventType(typeof(Feed));

            epService = EPServiceProviderManager.GetDefaultProvider(nesperConf);
            _runtime = epService.EPRuntime;
            mHandler = new MessageHandler();
            mHandler.UpdatePrediction += Predict;
        }
 /// <summary>
 /// Creates an EPStatement for each configuration entry
 /// </summary>
 /// <param name="sectionName">the name of the configuration section to look for</param>
 /// <param name="admin">the EPAdministrator which will create the statements</param>
 /// <param name="epService">the EPServiceProvider used to build the JSONEventRenderers</param>
 void CreateStatements(string sectionName, EPAdministrator admin, EPServiceProvider epService)
 {
     var queries = ConfigurationManager.GetSection(sectionName) as NameValueCollection;
     foreach (var c in queries.AllKeys)
     {
         var s = admin.CreateEPL(queries[c], c);
         _statements.Add(s);
         _eventRenderers.Add(c, epService.EPRuntime.EventRenderer.GetJSONRenderer(s.EventType));
     }
 }
 public void start()
 {
     Configuration config = new Configuration();
     config.AddEventType(typeof(XtiveTag));
     this._epService = EPServiceProviderManager.GetDefaultProvider(config);
     this._epRuntime = this._epService.EPRuntime;
     this._epService.EPAdministrator.CreateEPL(this._epl1);
     try
     {
         this._statement = this._epService.EPAdministrator.CreateEPL(this._epl2);
     }
     catch (Exception e1)
     { }
     try
     {
         this._statement.AddEventHandlerWithReplay(new PrefilterListener(this._form).PrefilterEventHandler);
     }
     catch (Exception e1)
     { }
 }
Пример #5
0
 private void SendEvent(EPServiceProvider epService, Object theEvent)
 {
     epService.EPRuntime.SendEvent(theEvent);
 }
        private void RunAssertionFields(
            EPServiceProvider epService, EventRepresentationChoice representationEnum, bool eventbean)
        {
            EPDataFlowInstantiationOptions options;

            epService.EPAdministrator.CreateEPL(
                "create " + representationEnum.GetOutputTypeCreateSchemaName() +
                " schema MyEvent(p0 string, p1 long, p2 double)");
            var stmtGraph = epService.EPAdministrator.CreateEPL(
                "create dataflow MyDataFlowOne " +
                "" +
                "BeaconSource -> BeaconStream<" + (eventbean ? "EventBean<MyEvent>" : "MyEvent") + "> {" +
                "  iterations : 3," +
                "  p0 : 'abc'," +
                "  p1 : MyMath.Round(MyMath.Random() * 10) + 1," +
                "  p2 : 1d," +
                "}" +
                "DefaultSupportCaptureOp(BeaconStream) {}");

            var future = new DefaultSupportCaptureOp(3, SupportContainer.Instance.LockManager());

            options = new EPDataFlowInstantiationOptions()
                      .OperatorProvider(new DefaultSupportGraphOpProvider(future));
            var df = epService.EPRuntime.DataFlowRuntime.Instantiate("MyDataFlowOne", options);

            df.Start();
            var output = future.GetValue(2, TimeUnit.SECONDS);

            Assert.AreEqual(3, output.Length);
            for (var i = 0; i < 3; i++)
            {
                if (!eventbean)
                {
                    if (representationEnum.IsObjectArrayEvent())
                    {
                        var row = (object[])output[i];
                        Assert.AreEqual("abc", row[0]);
                        var val = (long)row[1];
                        Assert.IsTrue(val >= 0 && val <= 11, "val=" + val);
                        Assert.AreEqual(1d, row[2]);
                    }
                    else if (representationEnum.IsMapEvent())
                    {
                        Map row = (Map)output[i];
                        Assert.AreEqual("abc", row.Get("p0"));
                        var val = (long)row.Get("p1");
                        Assert.IsTrue(val >= 0 && val <= 11, "val=" + val);
                        Assert.AreEqual(1d, row.Get("p2"));
                    }
                    else
                    {
                        var row = (GenericRecord)output[i];
                        Assert.AreEqual("abc", row.Get("p0"));
                        var val = (long)row.Get("p1");
                        Assert.IsTrue(val >= 0 && val <= 11, "val=" + val);
                        Assert.AreEqual(1d, row.Get("p2"));
                    }
                }
                else
                {
                    var row = (EventBean)output[i];
                    Assert.AreEqual("abc", row.Get("p0"));
                }
            }

            stmtGraph.Dispose();
            epService.EPAdministrator.Configuration.RemoveEventType("MyEvent", true);
        }
Пример #7
0
 public ReadRunnable(EPServiceProvider epService, SupportUpdateListener listener)
 {
     _epService = epService;
     _listener  = listener;
 }
 private static EPContextPartitionAdminSPI GetSpi(EPServiceProvider epService)
 {
     return((EPContextPartitionAdminSPI)epService.EPAdministrator.ContextPartitionAdmin);
 }
        public EPServicesContext CreateServicesContext(EPServiceProvider epServiceProvider, ConfigurationInformation configSnapshot)
        {
            // Directory for binding resources
            var resourceDirectory = new SimpleServiceDirectory();

            EventTypeIdGenerator eventTypeIdGenerator;

            if (configSnapshot.EngineDefaults.AlternativeContextConfig == null || configSnapshot.EngineDefaults.AlternativeContextConfig.EventTypeIdGeneratorFactory == null)
            {
                eventTypeIdGenerator = new EventTypeIdGeneratorImpl();
            }
            else
            {
                var eventTypeIdGeneratorFactory = TypeHelper.Instantiate <EventTypeIdGeneratorFactory>(
                    configSnapshot.EngineDefaults.AlternativeContextConfig.EventTypeIdGeneratorFactory);
                eventTypeIdGenerator = eventTypeIdGeneratorFactory.Create(new EventTypeIdGeneratorContext(epServiceProvider.URI));
            }

            // Make services that depend on snapshot config entries
            var eventAdapterService = new EventAdapterServiceImpl(eventTypeIdGenerator, configSnapshot.EngineDefaults.EventMetaConfig.AnonymousCacheSize);

            Init(eventAdapterService, configSnapshot);

            // New read-write lock for concurrent event processing
            var eventProcessingRwLock = ReaderWriterLockManager.CreateLock(
                MethodBase.GetCurrentMethod().DeclaringType);

            var timeSourceService     = MakeTimeSource(configSnapshot);
            var schedulingService     = SchedulingServiceProvider.NewService(timeSourceService);
            var schedulingMgmtService = new SchedulingMgmtServiceImpl();
            var engineImportService   = MakeEngineImportService(configSnapshot);
            var engineSettingsService = new EngineSettingsService(configSnapshot.EngineDefaults, configSnapshot.PlugInEventTypeResolutionURIs);
            var databaseConfigService = MakeDatabaseRefService(configSnapshot, schedulingService, schedulingMgmtService);

            var plugInViews = new PluggableObjectCollection();

            plugInViews.AddViews(configSnapshot.PlugInViews, configSnapshot.PlugInVirtualDataWindows);
            var plugInPatternObj = new PluggableObjectCollection();

            plugInPatternObj.AddPatternObjects(configSnapshot.PlugInPatternObjects);

            // exception handling
            ExceptionHandlingService exceptionHandlingService = InitExceptionHandling(
                epServiceProvider.URI,
                configSnapshot.EngineDefaults.ExceptionHandlingConfig,
                configSnapshot.EngineDefaults.ConditionHandlingConfig);

            // Statement context factory
            Type systemVirtualDWViewFactory = null;

            if (configSnapshot.EngineDefaults.AlternativeContextConfig.VirtualDataWindowViewFactory != null)
            {
                try {
                    systemVirtualDWViewFactory = TypeHelper.ResolveType(configSnapshot.EngineDefaults.AlternativeContextConfig.VirtualDataWindowViewFactory);
                    if (!systemVirtualDWViewFactory.IsImplementsInterface(typeof(VirtualDataWindowFactory)))
                    {
                        throw new ConfigurationException("Class " + systemVirtualDWViewFactory.Name + " does not implement the interface " + typeof(VirtualDataWindowFactory).FullName);
                    }
                }
                catch (TypeLoadException e) {
                    throw new ConfigurationException("Failed to look up class " + systemVirtualDWViewFactory);
                }
            }
            StatementContextFactory statementContextFactory = new StatementContextFactoryDefault(plugInViews, plugInPatternObj, systemVirtualDWViewFactory);

            long msecTimerResolution = configSnapshot.EngineDefaults.ThreadingConfig.InternalTimerMsecResolution;

            if (msecTimerResolution <= 0)
            {
                throw new ConfigurationException("Timer resolution configuration not set to a valid value, expecting a non-zero value");
            }
            var timerService = new TimerServiceImpl(epServiceProvider.URI, msecTimerResolution);

            var variableService = new VariableServiceImpl(configSnapshot.EngineDefaults.VariablesConfig.MsecVersionRelease, schedulingService, eventAdapterService, null);

            InitVariables(variableService, configSnapshot.Variables, engineImportService);

            var tableService = new TableServiceImpl();

            var statementLockFactory = new StatementLockFactoryImpl(configSnapshot.EngineDefaults.ExecutionConfig.IsFairlock, configSnapshot.EngineDefaults.ExecutionConfig.IsDisableLocking);
            var streamFactoryService = StreamFactoryServiceProvider.NewService(
                epServiceProvider.URI,
                configSnapshot.EngineDefaults.ViewResourcesConfig.IsShareViews);

            var filterService = FilterServiceProvider.NewService(
                configSnapshot.EngineDefaults.ExecutionConfig.FilterServiceProfile,
                configSnapshot.EngineDefaults.ExecutionConfig.IsAllowIsolatedService);

            var metricsReporting = new MetricReportingServiceImpl(configSnapshot.EngineDefaults.MetricsReportingConfig, epServiceProvider.URI);

            var namedWindowMgmtService = new NamedWindowMgmtServiceImpl(
                configSnapshot.EngineDefaults.LoggingConfig.IsEnableQueryPlan, metricsReporting);
            var namedWindowDispatchService = new NamedWindowDispatchServiceImpl(
                schedulingService,
                variableService,
                tableService,
                engineSettingsService.EngineSettings.ExecutionConfig.IsPrioritized,
                eventProcessingRwLock,
                exceptionHandlingService,
                metricsReporting);

            var valueAddEventService = new ValueAddEventServiceImpl();

            valueAddEventService.Init(configSnapshot.RevisionEventTypes, configSnapshot.VariantStreams, eventAdapterService, eventTypeIdGenerator);

            var statementEventTypeRef = new StatementEventTypeRefImpl();
            var statementVariableRef  = new StatementVariableRefImpl(variableService, tableService, namedWindowMgmtService);

            var threadingService = new ThreadingServiceImpl(
                configSnapshot.EngineDefaults.ThreadingConfig);

            var internalEventRouterImpl = new InternalEventRouterImpl();

            var statementIsolationService = new StatementIsolationServiceImpl();

            DeploymentStateService deploymentStateService = new DeploymentStateServiceImpl();

            StatementMetadataFactory stmtMetadataFactory;

            if (configSnapshot.EngineDefaults.AlternativeContextConfig.StatementMetadataFactory == null)
            {
                stmtMetadataFactory = new StatementMetadataFactoryDefault();
            }
            else
            {
                stmtMetadataFactory = TypeHelper.Instantiate <StatementMetadataFactory>(configSnapshot.EngineDefaults.AlternativeContextConfig.StatementMetadataFactory);
            }

            ContextManagementService contextManagementService = new ContextManagementServiceImpl();

            PatternSubexpressionPoolEngineSvc patternSubexpressionPoolSvc = null;

            if (configSnapshot.EngineDefaults.PatternsConfig.MaxSubexpressions != null)
            {
                patternSubexpressionPoolSvc = new PatternSubexpressionPoolEngineSvc(
                    configSnapshot.EngineDefaults.PatternsConfig.MaxSubexpressions.GetValueOrDefault(),
                    configSnapshot.EngineDefaults.PatternsConfig.IsMaxSubexpressionPreventStart);
            }

            MatchRecognizeStatePoolEngineSvc matchRecognizeStatePoolEngineSvc = null;

            if (configSnapshot.EngineDefaults.MatchRecognizeConfig.MaxStates != null)
            {
                matchRecognizeStatePoolEngineSvc = new MatchRecognizeStatePoolEngineSvc(
                    configSnapshot.EngineDefaults.MatchRecognizeConfig.MaxStates.Value,
                    configSnapshot.EngineDefaults.MatchRecognizeConfig.IsMaxStatesPreventStart);
            }

            var scriptingService = new ScriptingServiceImpl();

            scriptingService.DiscoverEngines();

            // New services context
            EPServicesContext services = new EPServicesContext(
                epServiceProvider.URI,
                schedulingService,
                eventAdapterService,
                engineImportService,
                engineSettingsService,
                databaseConfigService,
                plugInViews,
                statementLockFactory,
                eventProcessingRwLock, null,
                resourceDirectory,
                statementContextFactory,
                plugInPatternObj,
                timerService,
                filterService,
                streamFactoryService,
                namedWindowMgmtService,
                namedWindowDispatchService,
                variableService,
                tableService,
                timeSourceService,
                valueAddEventService,
                metricsReporting,
                statementEventTypeRef,
                statementVariableRef,
                configSnapshot,
                threadingService,
                internalEventRouterImpl,
                statementIsolationService,
                schedulingMgmtService,
                deploymentStateService,
                exceptionHandlingService,
                new PatternNodeFactoryImpl(),
                eventTypeIdGenerator,
                stmtMetadataFactory,
                contextManagementService,
                patternSubexpressionPoolSvc,
                matchRecognizeStatePoolEngineSvc,
                new DataFlowServiceImpl(epServiceProvider, new DataFlowConfigurationStateServiceImpl()),
                new ExprDeclaredServiceImpl(),
                new ContextControllerFactoryFactorySvcImpl(),
                new ContextManagerFactoryServiceImpl(),
                new EPStatementFactoryDefault(),
                new RegexHandlerFactoryDefault(),
                new ViewableActivatorFactoryDefault(),
                new FilterNonPropertyRegisteryServiceImpl(), new ResultSetProcessorHelperFactoryImpl(),
                new ViewServicePreviousFactoryImpl(),
                new EventTableIndexServiceImpl(),
                new EPRuntimeIsolatedFactoryImpl(),
                new FilterBooleanExpressionFactoryImpl(),
                new DataCacheFactory(), new MultiMatchHandlerFactoryImpl(),
                NamedWindowConsumerMgmtServiceImpl.INSTANCE,
                scriptingService);

            // Engine services subset available to statements
            statementContextFactory.StmtEngineServices = services;

            // Circular dependency
            var statementLifecycleSvc = new StatementLifecycleSvcImpl(epServiceProvider, services);

            services.StatementLifecycleSvc = statementLifecycleSvc;

            // Observers to statement events
            statementLifecycleSvc.LifecycleEvent += (s, theEvent) => metricsReporting.Observe(theEvent);

            // Circular dependency
            statementIsolationService.ServicesContext = services;

            return(services);
        }
Пример #10
0
        private void SendSupportBean_A(EPServiceProvider epService, string id)
        {
            var bean = new SupportBean_A(id);

            epService.EPRuntime.SendEvent(bean);
        }
Пример #11
0
 public AutomacaoMonitorBase(DadosGlobais dadosglobais)
 {
     _epService    = dadosglobais.EpService;
     _dadosGlobais = dadosglobais;
     _config       = dadosglobais.Parametros;
 }
Пример #12
0
 public StmtNamedWindowConsumeCallable(String threadKey, EPServiceProvider engine, int numRepeats)
 {
     _engine     = engine;
     _numRepeats = numRepeats;
     _threadKey  = threadKey;
 }
 public StmtNamedWindowMergeCallable(EPServiceProvider engine, int numEvents)
 {
     _engine    = (EPRuntimeSPI)engine.EPRuntime;
     _numEvents = numEvents;
 }
Пример #14
0
        private void SendTimeEvent(EPServiceProvider epService, int day, int hour, int minute, int second, int millis)
        {
            var dateTime = new DateTime(2008, 1, day, hour, minute, second, millis, DateTimeKind.Local);

            epService.EPRuntime.SendEvent(new CurrentTimeEvent(dateTime));
        }
 /// <summary>
 /// Creates a new instance of the EP
 /// </summary>
 /// <param name="sectionName"></param>
 /// <param name="admin"></param>
 public QueryConfiguration(string sectionName, EPAdministrator admin, EPServiceProvider epService)
 {
     _statements = new List<EPStatement>();
     _eventRenderers = new Dictionary<string, JSONEventRenderer>();
     CreateStatements(sectionName, admin, epService);
 }
 public ReadRunnable(EPServiceProvider epService)
 {
     this._epService = epService;
     _listener       = new SupportUpdateListener();
     epService.EPAdministrator.GetStatement("out").Events += _listener.Update;
 }
Пример #17
0
        public void TestOp()
        {
            Configuration config = new Configuration();

            config.EngineDefaults.ThreadingConfig.IsInternalTimerEnabled      = false;
            config.EngineDefaults.ThreadingConfig.IsThreadPoolInbound         = true;
            config.EngineDefaults.ThreadingConfig.ThreadPoolInboundNumThreads = 4;
            config.EngineDefaults.ExpressionConfig.IsUdfCache = false;
            config.AddEventType("MyMap", new Dictionary <String, Object>());
            config.AddEventType <SupportBean>();
            config.AddImport(typeof(SupportStaticMethodLib).FullName);

            ConfigurationEventTypeXMLDOM xmlDOMEventTypeDesc = new ConfigurationEventTypeXMLDOM();

            xmlDOMEventTypeDesc.RootElementName = "myevent";
            config.AddEventType("XMLType", xmlDOMEventTypeDesc);

            EPServiceProvider epService = EPServiceProviderManager.GetDefaultProvider(config);

            epService.Initialize();

            SupportListenerTimerHRes listenerOne   = new SupportListenerTimerHRes();
            SupportListenerTimerHRes listenerTwo   = new SupportListenerTimerHRes();
            SupportListenerTimerHRes listenerThree = new SupportListenerTimerHRes();
            EPStatement stmtOne = epService.EPAdministrator.CreateEPL("select SupportStaticMethodLib.Sleep(100) from MyMap");

            stmtOne.Events += listenerOne.Update;
            EPStatement stmtTwo = epService.EPAdministrator.CreateEPL("select SupportStaticMethodLib.Sleep(100) from SupportBean");

            stmtTwo.Events += listenerTwo.Update;
            EPStatement stmtThree = epService.EPAdministrator.CreateEPL("select SupportStaticMethodLib.Sleep(100) from XMLType");

            stmtThree.Events += listenerThree.Update;

            EventSender senderOne   = epService.EPRuntime.GetEventSender("MyMap");
            EventSender senderTwo   = epService.EPRuntime.GetEventSender("SupportBean");
            EventSender senderThree = epService.EPRuntime.GetEventSender("XMLType");

            long delta = PerformanceObserver.TimeMillis(
                delegate
            {
                for (int i = 0; i < 2; i++)
                {
                    epService.EPRuntime.SendEvent(new Dictionary <String, Object>(), "MyMap");
                    senderOne.SendEvent(new Dictionary <String, Object>());
                    epService.EPRuntime.SendEvent(new SupportBean());
                    senderTwo.SendEvent(new SupportBean());
                    epService.EPRuntime.SendEvent(SupportXML.GetDocument("<myevent/>"));
                    senderThree.SendEvent(SupportXML.GetDocument("<myevent/>"));
                }
            });

            Assert.LessOrEqual(delta, 100);

            Thread.Sleep(1000);
            Assert.AreEqual(4, listenerOne.NewEvents.Count);
            Assert.AreEqual(4, listenerTwo.NewEvents.Count);
            Assert.AreEqual(4, listenerThree.NewEvents.Count);

            EPServiceProviderSPI spi = (EPServiceProviderSPI)epService;

            Assert.AreEqual(0, spi.ThreadingService.InboundQueue.Count);
            Assert.NotNull(spi.ThreadingService.InboundThreadPool);

            stmtOne.Dispose();
            stmtTwo.Dispose();
            stmtThree.Dispose();

            epService.Dispose();
        }
        private void RunAssertionUnboundStreamUnlimitedKey(EPServiceProvider epService)
        {
            // ESPER-396 Unbound stream and aggregating/grouping by unlimited key (i.e. timestamp) configurable state drop
            SendTimer(epService, 0);

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

            stmtOne.Events += listener.Update;

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

                //if (i % 100000 == 0)
                //{
                //    Log.Info("Sending event number " + i);
                //}
            }

            listener.Reset();

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

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

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

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

            stmtOne.Dispose();
            stmtOne         = epService.EPAdministrator.CreateEPL("@Hint('reclaim_group_aged=myAge,reclaim_group_freq=myFreq') select LongPrimitive, count(*) from SupportBean group by LongPrimitive");
            stmtOne.Events += listener.Update;

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

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

                /*
                 * if (i % 100000 == 0)
                 * new object[] {
                 *  Log.Info("Sending event number " + i);
                 * }
                 */
            }

            listener.Reset();

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

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

            stmtOne.Dispose();

            // invalid tests
            TryInvalid(epService, "@Hint('reclaim_group_aged=xyz') select LongPrimitive, count(*) from SupportBean group by LongPrimitive",
                       "Error starting statement: Failed to parse hint parameter value 'xyz' as a double-typed seconds value or variable name [@Hint('reclaim_group_aged=xyz') select LongPrimitive, count(*) from SupportBean group by LongPrimitive]");
            TryInvalid(epService, "@Hint('reclaim_group_aged=30,reclaim_group_freq=xyz') select LongPrimitive, count(*) from SupportBean group by LongPrimitive",
                       "Error starting statement: Failed to parse hint parameter value 'xyz' as a double-typed seconds value or variable name [@Hint('reclaim_group_aged=30,reclaim_group_freq=xyz') select LongPrimitive, count(*) from SupportBean group by LongPrimitive]");
            epService.EPAdministrator.Configuration.AddVariable("MyVar", typeof(string), "");
            TryInvalid(epService, "@Hint('reclaim_group_aged=MyVar') select LongPrimitive, count(*) from SupportBean group by LongPrimitive",
                       "Error starting statement: Variable type of variable 'MyVar' is not numeric [@Hint('reclaim_group_aged=MyVar') select LongPrimitive, count(*) from SupportBean group by LongPrimitive]");
            TryInvalid(epService, "@Hint('reclaim_group_aged=-30,reclaim_group_freq=30') select LongPrimitive, count(*) from SupportBean group by LongPrimitive",
                       "Error starting statement: Hint parameter value '-30' is an invalid value, expecting a double-typed seconds value or variable name [@Hint('reclaim_group_aged=-30,reclaim_group_freq=30') select LongPrimitive, count(*) from SupportBean group by LongPrimitive]");

            /// <summary>Test natural timer - long running test to be commented out.</summary>

            /*
             * epService = EPServiceProviderManager.GetProvider(GetType().FullName);
             * epService.EPAdministrator.Configuration.AddEventType<SupportBean>();
             * EPStatement stmtOne = epService.EPAdministrator.CreateEPL("@Hint('reclaim_group_aged=1,reclaim_group_freq=1') select LongPrimitive, count(*) from SupportBean group by LongPrimitive");
             *
             * int count = 0;
             * While(true)
             * new object[] {
             *  SupportBean @event = new SupportBean();
             *  event.LongPrimitive = DateTimeHelper.CurrentTimeMillis;
             *  epService.EPRuntime.SendEvent(new SupportBean());
             *  count++;
             *  if (count % 100000 == 0)
             *  new object[] {
             *      Log.Info("Sending event number " + count);
             *  }
             * }
             */
        }
Пример #19
0
        private void RunAssertionJoinSingleInsertOneWindow(EPServiceProvider epService)
        {
            var fields = new string[] { "a1", "b1", "a2", "b2" };

            // create window
            string      stmtTextCreateOne = "create window MyWindowJSIOne#keepall as select TheString as a1, IntPrimitive as b1 from " + typeof(SupportBean).FullName;
            EPStatement stmtCreateOne     = epService.EPAdministrator.CreateEPL(stmtTextCreateOne);
            var         listenerWindow    = new SupportUpdateListener();

            stmtCreateOne.Events += listenerWindow.Update;

            // create window
            string      stmtTextCreateTwo = "create window MyWindowJSITwo#keepall as select TheString as a2, IntPrimitive as b2 from " + typeof(SupportBean).FullName;
            EPStatement stmtCreateTwo     = epService.EPAdministrator.CreateEPL(stmtTextCreateTwo);
            var         listenerWindowTwo = new SupportUpdateListener();

            stmtCreateTwo.Events += listenerWindowTwo.Update;

            // create delete stmt
            string stmtTextDelete = "on " + typeof(SupportMarketDataBean).FullName + "(volume=1) delete from MyWindowJSIOne where symbol = a1";

            epService.EPAdministrator.CreateEPL(stmtTextDelete);

            stmtTextDelete = "on " + typeof(SupportMarketDataBean).FullName + "(volume=0) delete from MyWindowJSITwo where symbol = a2";
            epService.EPAdministrator.CreateEPL(stmtTextDelete);

            // create insert into
            string stmtTextInsert = "insert into MyWindowJSIOne select TheString as a1, IntPrimitive as b1 from " + typeof(SupportBean).FullName + "(BoolPrimitive = true)";

            epService.EPAdministrator.CreateEPL(stmtTextInsert);

            stmtTextInsert = "insert into MyWindowJSITwo select TheString as a2, IntPrimitive as b2 from " + typeof(SupportBean).FullName + "(BoolPrimitive = false)";
            epService.EPAdministrator.CreateEPL(stmtTextInsert);

            // create consumers
            string stmtTextSelectOne = "select irstream a1, b1, a2, b2 " +
                                       " from MyWindowJSIOne as s0," +
                                       "MyWindowJSITwo as s1 where s0.a1 = s1.a2";
            EPStatement stmtSelectOne   = epService.EPAdministrator.CreateEPL(stmtTextSelectOne);
            var         listenerStmtOne = new SupportUpdateListener();

            stmtSelectOne.Events += listenerStmtOne.Update;

            SendSupportBean(epService, true, "S0", 1);
            Assert.IsFalse(listenerStmtOne.IsInvoked);

            SendSupportBean(epService, false, "S0", 2);
            EPAssertionUtil.AssertProps(listenerStmtOne.AssertOneGetNewAndReset(), fields, new object[] { "S0", 1, "S0", 2 });

            SendSupportBean(epService, false, "S1", 3);
            Assert.IsFalse(listenerStmtOne.IsInvoked);

            SendSupportBean(epService, true, "S1", 4);
            EPAssertionUtil.AssertProps(listenerStmtOne.AssertOneGetNewAndReset(), fields, new object[] { "S1", 4, "S1", 3 });

            SendSupportBean(epService, true, "S1", 5);
            EPAssertionUtil.AssertProps(listenerStmtOne.AssertOneGetNewAndReset(), fields, new object[] { "S1", 5, "S1", 3 });

            SendSupportBean(epService, false, "S1", 6);
            Assert.AreEqual(2, listenerStmtOne.LastNewData.Length);
            listenerStmtOne.Reset();

            // delete and insert back in
            SendMarketBean(epService, "S0", 0);
            EPAssertionUtil.AssertProps(listenerStmtOne.AssertOneGetOldAndReset(), fields, new object[] { "S0", 1, "S0", 2 });

            SendSupportBean(epService, false, "S0", 7);
            EPAssertionUtil.AssertProps(listenerStmtOne.AssertOneGetNewAndReset(), fields, new object[] { "S0", 1, "S0", 7 });

            // delete and insert back in
            SendMarketBean(epService, "S0", 1);
            EPAssertionUtil.AssertProps(listenerStmtOne.AssertOneGetOldAndReset(), fields, new object[] { "S0", 1, "S0", 7 });

            SendSupportBean(epService, true, "S0", 8);
            EPAssertionUtil.AssertProps(listenerStmtOne.AssertOneGetNewAndReset(), fields, new object[] { "S0", 8, "S0", 7 });
        }
        private void RunAssertionAggregationOverGroupedProps(EPServiceProvider epService)
        {
            // test for ESPER-185
            string[] fields = "symbol,price,mycount".Split(',');
            string   epl    = "select irstream symbol,price,count(price) as mycount " +
                              "from " + typeof(SupportMarketDataBean).FullName + "#length(5) " +
                              "group by symbol, price order by symbol asc";

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

            stmt.Events += listener.Update;

            SendEvent(epService, SYMBOL_DELL, 10);
            EPAssertionUtil.AssertProps(listener.LastNewData[0], fields, new object[] { "DELL", 10.0, 1L });
            EPAssertionUtil.AssertProps(listener.LastOldData[0], fields, new object[] { "DELL", 10.0, 0L });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 10.0, 1L } });
            listener.Reset();

            SendEvent(epService, SYMBOL_DELL, 11);
            EPAssertionUtil.AssertProps(listener.LastNewData[0], fields, new object[] { "DELL", 11.0, 1L });
            EPAssertionUtil.AssertProps(listener.LastOldData[0], fields, new object[] { "DELL", 11.0, 0L });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 10.0, 1L }, new object[] { "DELL", 11.0, 1L } });
            listener.Reset();

            SendEvent(epService, SYMBOL_DELL, 10);
            EPAssertionUtil.AssertProps(listener.LastNewData[0], fields, new object[] { "DELL", 10.0, 2L });
            EPAssertionUtil.AssertProps(listener.LastOldData[0], fields, new object[] { "DELL", 10.0, 1L });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 10.0, 2L }, new object[] { "DELL", 11.0, 1L } });
            listener.Reset();

            SendEvent(epService, SYMBOL_IBM, 5);
            Assert.AreEqual(1, listener.NewDataList.Count);
            EPAssertionUtil.AssertProps(listener.LastNewData[0], fields, new object[] { "IBM", 5.0, 1L });
            EPAssertionUtil.AssertProps(listener.LastOldData[0], fields, new object[] { "IBM", 5.0, 0L });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 10.0, 2L }, new object[] { "DELL", 11.0, 1L }, new object[] { "IBM", 5.0, 1L } });
            listener.Reset();

            SendEvent(epService, SYMBOL_IBM, 5);
            Assert.AreEqual(1, listener.LastNewData.Length);
            EPAssertionUtil.AssertProps(listener.LastNewData[0], fields, new object[] { "IBM", 5.0, 2L });
            EPAssertionUtil.AssertProps(listener.LastOldData[0], fields, new object[] { "IBM", 5.0, 1L });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 10.0, 2L }, new object[] { "DELL", 11.0, 1L }, new object[] { "IBM", 5.0, 2L } });
            listener.Reset();

            SendEvent(epService, SYMBOL_IBM, 5);
            Assert.AreEqual(2, listener.LastNewData.Length);
            EPAssertionUtil.AssertProps(listener.LastNewData[1], fields, new object[] { "IBM", 5.0, 3L });
            EPAssertionUtil.AssertProps(listener.LastOldData[1], fields, new object[] { "IBM", 5.0, 2L });
            EPAssertionUtil.AssertProps(listener.LastNewData[0], fields, new object[] { "DELL", 10.0, 1L });
            EPAssertionUtil.AssertProps(listener.LastOldData[0], fields, new object[] { "DELL", 10.0, 2L });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 11.0, 1L }, new object[] { "DELL", 10.0, 1L }, new object[] { "IBM", 5.0, 3L } });
            listener.Reset();

            SendEvent(epService, SYMBOL_IBM, 5);
            Assert.AreEqual(2, listener.LastNewData.Length);
            EPAssertionUtil.AssertProps(listener.LastNewData[1], fields, new object[] { "IBM", 5.0, 4L });
            EPAssertionUtil.AssertProps(listener.LastOldData[1], fields, new object[] { "IBM", 5.0, 3L });
            EPAssertionUtil.AssertProps(listener.LastNewData[0], fields, new object[] { "DELL", 11.0, 0L });
            EPAssertionUtil.AssertProps(listener.LastOldData[0], fields, new object[] { "DELL", 11.0, 1L });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 10.0, 1L }, new object[] { "IBM", 5.0, 4L } });
            listener.Reset();

            stmt.Dispose();
        }
Пример #21
0
        private void SendMarketBean(EPServiceProvider epService, string symbol, long volume)
        {
            var bean = new SupportMarketDataBean(symbol, 0, volume, "");

            epService.EPRuntime.SendEvent(bean);
        }
        private void TryAssertionSum(EPServiceProvider epService, EPStatement stmt, SupportUpdateListener listener)
        {
            var fields = new string[] { "symbol", "mySum", "myAvg" };

            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, null);

            // assert select result type
            Assert.AreEqual(typeof(string), stmt.EventType.GetPropertyType("symbol"));
            Assert.AreEqual(typeof(double), stmt.EventType.GetPropertyType("mySum"));
            Assert.AreEqual(typeof(double), stmt.EventType.GetPropertyType("myAvg"));

            SendEvent(epService, SYMBOL_DELL, 10);
            AssertEvents(listener, SYMBOL_DELL,
                         null, null,
                         10d, 10d);
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 10d, 10d } });

            SendEvent(epService, SYMBOL_DELL, 20);
            AssertEvents(listener, SYMBOL_DELL,
                         10d, 10d,
                         30d, 15d);
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 30d, 15d } });

            SendEvent(epService, SYMBOL_DELL, 100);
            AssertEvents(listener, SYMBOL_DELL,
                         30d, 15d,
                         130d, 130d / 3d);
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 130d, 130d / 3d } });

            SendEvent(epService, SYMBOL_DELL, 50);
            AssertEvents(listener, SYMBOL_DELL,
                         130d, 130 / 3d,
                         170d, 170 / 3d); // 20 + 100 + 50
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 170d, 170d / 3d } });

            SendEvent(epService, SYMBOL_DELL, 5);
            AssertEvents(listener, SYMBOL_DELL,
                         170d, 170 / 3d,
                         155d, 155 / 3d); // 100 + 50 + 5
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 155d, 155d / 3d } });

            SendEvent(epService, "AAA", 1000);
            AssertEvents(listener, SYMBOL_DELL,
                         155d, 155d / 3,
                         55d, 55d / 2); // 50 + 5
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, new object[][] { new object[] { "DELL", 55d, 55d / 2d } });

            SendEvent(epService, SYMBOL_IBM, 70);
            AssertEvents(listener, SYMBOL_DELL,
                         55d, 55 / 2d,
                         5, 5,
                         SYMBOL_IBM,
                         null, null,
                         70, 70); // Dell:5
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, new object[][] {
                new object[] { "DELL", 5d, 5d }, new object[] { "IBM", 70d, 70d }
            });

            SendEvent(epService, "AAA", 2000);
            AssertEvents(listener, SYMBOL_DELL,
                         5d, 5d,
                         null, null);
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, new object[][] {
                new object[] { "IBM", 70d, 70d }
            });

            SendEvent(epService, "AAA", 3000);
            Assert.IsFalse(listener.IsInvoked);

            SendEvent(epService, "AAA", 4000);
            AssertEvents(listener, SYMBOL_IBM,
                         70d, 70d,
                         null, null);
            EPAssertionUtil.AssertPropsPerRowAnyOrder(stmt.GetEnumerator(), fields, null);
        }
        private void RunAssertionJoin2Access(EPServiceProvider epService)
        {
            string epl = "select " +
                         "sa.id as ast, " +
                         "sb.id as bst, " +
                         "first(sa.id) as fas, " +
                         "window(sa.id) as was, " +
                         "last(sa.id) as las, " +
                         "first(sb.id) as fbs, " +
                         "window(sb.id) as wbs, " +
                         "last(sb.id) as lbs " +
                         "from SupportBean_A#length(2) as sa, SupportBean_B#length(2) as sb " +
                         "order by ast, bst";
            EPStatement stmt     = epService.EPAdministrator.CreateEPL(epl);
            var         listener = new SupportUpdateListener();

            stmt.Events += listener.Update;

            string[] fields = "ast,bst,fas,was,las,fbs,wbs,lbs".Split(',');

            epService.EPRuntime.SendEvent(new SupportBean_A("A1"));
            epService.EPRuntime.SendEvent(new SupportBean_B("B1"));
            EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, new[] { "A1", "B1", "A1", Split("A1"), "A1", "B1", Split("B1"), "B1" });

            epService.EPRuntime.SendEvent(new SupportBean_A("A2"));
            EPAssertionUtil.AssertPropsPerRow(listener.LastNewData, fields,
                                              new[]
            {
                new[] { "A2", "B1", "A1", Split("A1,A2"), "A2", "B1", Split("B1"), "B1" }
            });

            epService.EPRuntime.SendEvent(new SupportBean_A("A3"));
            EPAssertionUtil.AssertPropsPerRow(listener.LastNewData, fields,
                                              new[]
            {
                new[] { "A3", "B1", "A2", Split("A2,A3"), "A3", "B1", Split("B1"), "B1" }
            });

            epService.EPRuntime.SendEvent(new SupportBean_B("B2"));
            EPAssertionUtil.AssertPropsPerRow(listener.LastNewData, fields,
                                              new[]
            {
                new[] { "A2", "B2", "A2", Split("A2,A3"), "A3", "B1", Split("B1,B2"), "B2" },
                new[] { "A3", "B2", "A2", Split("A2,A3"), "A3", "B1", Split("B1,B2"), "B2" }
            });

            epService.EPRuntime.SendEvent(new SupportBean_B("B3"));
            EPAssertionUtil.AssertPropsPerRow(listener.LastNewData, fields,
                                              new[]
            {
                new[] { "A2", "B3", "A2", Split("A2,A3"), "A3", "B2", Split("B2,B3"), "B3" },
                new[] { "A3", "B3", "A2", Split("A2,A3"), "A3", "B2", Split("B2,B3"), "B3" }
            });

            epService.EPRuntime.SendEvent(new SupportBean_A("A4"));
            EPAssertionUtil.AssertPropsPerRow(listener.LastNewData, fields,
                                              new[]
            {
                new[] { "A4", "B2", "A3", Split("A3,A4"), "A4", "B2", Split("B2,B3"), "B3" },
                new[] { "A4", "B3", "A3", Split("A3,A4"), "A4", "B2", Split("B2,B3"), "B3" }
            });

            stmt.Dispose();
        }
        private void RunAssertionUnboundStreamIterate(EPServiceProvider epService)
        {
            epService.EPAdministrator.Configuration.AddEventType <SupportBean>();

            // with output snapshot
            string[]    fields = "c0,c1".Split(',');
            EPStatement stmt   = epService.EPAdministrator.CreateEPL("select TheString as c0, sum(IntPrimitive) as c1 from SupportBean group by TheString " +
                                                                     "output snapshot every 3 events");
            var listener = new SupportUpdateListener();

            stmt.Events += listener.Update;

            epService.EPRuntime.SendEvent(new SupportBean("E1", 10));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E1", 10 } });
            Assert.IsFalse(listener.IsInvoked);

            epService.EPRuntime.SendEvent(new SupportBean("E2", 20));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E1", 10 }, new object[] { "E2", 20 } });
            Assert.IsFalse(listener.IsInvoked);

            epService.EPRuntime.SendEvent(new SupportBean("E1", 11));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E1", 21 }, new object[] { "E2", 20 } });
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields, new object[][] { new object[] { "E1", 21 }, new object[] { "E2", 20 } });

            epService.EPRuntime.SendEvent(new SupportBean("E0", 30));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E1", 21 }, new object[] { "E2", 20 }, new object[] { "E0", 30 } });
            Assert.IsFalse(listener.IsInvoked);

            stmt.Dispose();

            // with order-by
            stmt = epService.EPAdministrator.CreateEPL("select TheString as c0, sum(IntPrimitive) as c1 from SupportBean group by TheString " +
                                                       "output snapshot every 3 events order by TheString asc");
            stmt.Events += listener.Update;

            epService.EPRuntime.SendEvent(new SupportBean("E1", 10));
            epService.EPRuntime.SendEvent(new SupportBean("E2", 20));
            epService.EPRuntime.SendEvent(new SupportBean("E1", 11));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E1", 21 }, new object[] { "E2", 20 } });
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields, new object[][] { new object[] { "E1", 21 }, new object[] { "E2", 20 } });

            epService.EPRuntime.SendEvent(new SupportBean("E0", 30));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E0", 30 }, new object[] { "E1", 21 }, new object[] { "E2", 20 } });
            Assert.IsFalse(listener.IsInvoked);

            epService.EPRuntime.SendEvent(new SupportBean("E3", 40));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E0", 30 }, new object[] { "E1", 21 }, new object[] { "E2", 20 }, new object[] { "E3", 40 } });
            Assert.IsFalse(listener.IsInvoked);

            stmt.Dispose();

            // test un-grouped case
            stmt         = epService.EPAdministrator.CreateEPL("select null as c0, sum(IntPrimitive) as c1 from SupportBean output snapshot every 3 events");
            stmt.Events += listener.Update;

            epService.EPRuntime.SendEvent(new SupportBean("E1", 10));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { null, 10 } });
            Assert.IsFalse(listener.IsInvoked);

            epService.EPRuntime.SendEvent(new SupportBean("E2", 20));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { null, 30 } });
            Assert.IsFalse(listener.IsInvoked);

            epService.EPRuntime.SendEvent(new SupportBean("E1", 11));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { null, 41 } });
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields, new object[][] { new object[] { null, 41 } });

            stmt.Dispose();

            // test reclaim
            epService.EPRuntime.SendEvent(new CurrentTimeEvent(1000));
            stmt = epService.EPAdministrator.CreateEPL("@Hint('reclaim_group_aged=1,reclaim_group_freq=1') select TheString as c0, sum(IntPrimitive) as c1 from SupportBean group by TheString " +
                                                       "output snapshot every 3 events");
            stmt.Events += listener.Update;

            epService.EPRuntime.SendEvent(new SupportBean("E1", 10));

            epService.EPRuntime.SendEvent(new CurrentTimeEvent(1500));
            epService.EPRuntime.SendEvent(new SupportBean("E0", 11));

            epService.EPRuntime.SendEvent(new CurrentTimeEvent(1800));
            epService.EPRuntime.SendEvent(new SupportBean("E2", 12));
            EPAssertionUtil.AssertPropsPerRow(listener.GetAndResetLastNewData(), fields, new object[][] { new object[] { "E1", 10 }, new object[] { "E0", 11 }, new object[] { "E2", 12 } });
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E1", 10 }, new object[] { "E0", 11 }, new object[] { "E2", 12 } });

            epService.EPRuntime.SendEvent(new CurrentTimeEvent(2200));
            epService.EPRuntime.SendEvent(new SupportBean("E2", 13));
            EPAssertionUtil.AssertPropsPerRow(stmt.GetEnumerator(), fields, new object[][] { new object[] { "E0", 11 }, new object[] { "E2", 25 } });

            stmt.Dispose();
        }
Пример #25
0
        public override void Run(EPServiceProvider epService)
        {
            string epl;

            // no parameter while one is expected
            epl = "select Contained.take() from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.take()': Parameters mismatch for enumeration method 'take', the method requires an (non-lambda) expression providing count [select Contained.take() from SupportBean_ST0_Container]");

            // primitive array property
            epl = "select ArrayProperty.where(x=>x.BoolPrimitive) from SupportBeanComplexProps";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'ArrayProperty.where()': Error validating enumeration method 'where' parameter 0: Failed to validate declared expression body expression 'x.BoolPrimitive': Failed to resolve property 'x.BoolPrimitive' to a stream or nested property in a stream [select ArrayProperty.where(x=>x.BoolPrimitive) from SupportBeanComplexProps]");

            // property not there
            epl = "select Contained.where(x=>x.dummy = 1) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.where()': Error validating enumeration method 'where' parameter 0: Failed to validate declared expression body expression 'x.dummy=1': Failed to resolve property 'x.dummy' to a stream or nested property in a stream [select Contained.where(x=>x.dummy = 1) from SupportBean_ST0_Container]");
            epl = "select * from SupportBean(products.where(p => code = '1'))";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Failed to validate filter expression 'products.where()': Failed to resolve 'products.where' to a property, single-row function, aggregation function, script, stream or class name ");

            // test not an enumeration method
            epl = "select Contained.notAMethod(x=>x.BoolPrimitive) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.notAMethod()': Could not find event property, enumeration method or instance method named 'notAMethod' in collection of events of type 'SupportBean_ST0' [select Contained.notAMethod(x=>x.BoolPrimitive) from SupportBean_ST0_Container]");

            // invalid lambda expression for non-lambda func
            epl = "select makeTest(x=>1) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'makeTest()': Unexpected lambda-expression encountered as parameter to UDF or static method 'MakeTest' [select makeTest(x=>1) from SupportBean_ST0_Container]");

            // invalid lambda expression for non-lambda func
            epl = "select SupportBean_ST0_Container.makeTest(x=>1) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'SupportBean_ST0_Container.makeTest()': Unexpected lambda-expression encountered as parameter to UDF or static method 'makeTest' [select SupportBean_ST0_Container.makeTest(x=>1) from SupportBean_ST0_Container]");

            // invalid incompatible params
            epl = "select Contained.take('a') from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.take('a')': Failed to resolve enumeration method, date-time method or mapped property 'Contained.take('a')': Error validating enumeration method 'take', expected a number-type result for expression parameter 0 but received System.String [select Contained.take('a') from SupportBean_ST0_Container]");

            // invalid incompatible params
            epl = "select Contained.take(x => x.p00) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.take()': Parameters mismatch for enumeration method 'take', the method requires an (non-lambda) expression providing count, but receives a lambda expression [select Contained.take(x => x.p00) from SupportBean_ST0_Container]");

            // invalid too many lambda parameter
            epl = "select Contained.where((x,y,z) => true) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.where()': Parameters mismatch for enumeration method 'where', the method requires a lambda expression providing predicate, but receives a 3-parameter lambda expression [select Contained.where((x,y,z) => true) from SupportBean_ST0_Container]");

            // invalid no parameter
            epl = "select Contained.where() from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.where()': Parameters mismatch for enumeration method 'where', the method has multiple footprints accepting a lambda expression providing predicate, or a 2-parameter lambda expression providing (predicate, index), but receives no parameters [select Contained.where() from SupportBean_ST0_Container]");

            // invalid no parameter
            epl = "select window(IntPrimitive).takeLast() from SupportBean#length(2)";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'window(IntPrimitive).takeLast()': Parameters mismatch for enumeration method 'takeLast', the method requires an (non-lambda) expression providing count [select window(IntPrimitive).takeLast() from SupportBean#length(2)]");

            // invalid wrong parameter
            epl = "select Contained.where(x=>true,y=>true) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.where(,)': Parameters mismatch for enumeration method 'where', the method has multiple footprints accepting a lambda expression providing predicate, or a 2-parameter lambda expression providing (predicate, index), but receives a lambda expression and a lambda expression [select Contained.where(x=>true,y=>true) from SupportBean_ST0_Container]");

            // invalid wrong parameter
            epl = "select Contained.where(1) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.where(1)': Parameters mismatch for enumeration method 'where', the method requires a lambda expression providing predicate, but receives an (non-lambda) expression [select Contained.where(1) from SupportBean_ST0_Container]");

            // invalid too many parameter
            epl = "select Contained.where(1,2) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.where(1,2)': Parameters mismatch for enumeration method 'where', the method has multiple footprints accepting a lambda expression providing predicate, or a 2-parameter lambda expression providing (predicate, index), but receives an (non-lambda) expression and an (non-lambda) expression [select Contained.where(1,2) from SupportBean_ST0_Container]");

            // subselect multiple columns
            epl = "select (select TheString, IntPrimitive from SupportBean#lastevent).where(x=>x.BoolPrimitive) from SupportBean_ST0";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'TheString.where()': Error validating enumeration method 'where' parameter 0: Failed to validate declared expression body expression 'x.BoolPrimitive': Failed to resolve property 'x.BoolPrimitive' to a stream or nested property in a stream [select (select TheString, IntPrimitive from SupportBean#lastevent).where(x=>x.BoolPrimitive) from SupportBean_ST0]");

            // subselect individual column
            epl = "select (select TheString from SupportBean#lastevent).where(x=>x.BoolPrimitive) from SupportBean_ST0";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'TheString.where()': Error validating enumeration method 'where' parameter 0: Failed to validate declared expression body expression 'x.BoolPrimitive': Failed to resolve property 'x.BoolPrimitive' (property 'x' is an indexed property and requires an index or enumeration method to access values) [select (select TheString from SupportBean#lastevent).where(x=>x.BoolPrimitive) from SupportBean_ST0]");

            // aggregation
            epl = "select avg(IntPrimitive).where(x=>x.BoolPrimitive) from SupportBean_ST0";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Incorrect syntax near '(' ('avg' is a reserved keyword) at line 1 column 10");

            // invalid incompatible params
            epl = "select Contained.allOf(x => 1) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, string.Format("Error starting statement: Failed to validate select-clause expression 'Contained.allOf()': Error validating enumeration method 'allOf', expected a bool-type result for expression parameter 0 but received {0} [select Contained.allOf(x => 1) from SupportBean_ST0_Container]",
                                                                              typeof(int).GetCleanName()));

            // invalid incompatible params
            epl = "select Contained.allOf(x => 1) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, string.Format("Error starting statement: Failed to validate select-clause expression 'Contained.allOf()': Error validating enumeration method 'allOf', expected a bool-type result for expression parameter 0 but received {0} [select Contained.allOf(x => 1) from SupportBean_ST0_Container]",
                                                                              typeof(int).GetCleanName()));

            // invalid incompatible params
            epl = "select Contained.aggregate(0, (result, item) => result || ',') from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, string.Format("Error starting statement: Failed to validate select-clause expression 'Contained.aggregate(0,)': Error validating enumeration method 'aggregate' parameter 1: Failed to validate declared expression body expression 'result||\",\"': Implicit conversion from datatype '{0}' to string is not allowed [select Contained.aggregate(0, (result, item) => result || ',') from SupportBean_ST0_Container]",
                                                                              typeof(int?).GetCleanName()));

            // invalid incompatible params
            epl = "select Contained.average(x => x.id) from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, "Error starting statement: Failed to validate select-clause expression 'Contained.average()': Error validating enumeration method 'average', expected a number-type result for expression parameter 0 but received System.String [select Contained.average(x => x.id) from SupportBean_ST0_Container]");

            // not a property
            epl = "select Contained.firstof().dummy from SupportBean_ST0_Container";
            SupportMessageAssertUtil.TryInvalid(epService, epl, string.Format("Error starting statement: Failed to validate select-clause expression 'Contained.firstof().dummy()': Failed to resolve method 'dummy': Could not find enumeration method, date-time method or instance method named 'dummy' in class '{0}' taking no parameters [select Contained.firstof().dummy from SupportBean_ST0_Container]",
                                                                              typeof(SupportBean_ST0).GetCleanName()));
        }
        private void SendEvent(EPServiceProvider epService, string symbol, double price)
        {
            var bean = new SupportMarketDataBean(symbol, price, 0L, null);

            epService.EPRuntime.SendEvent(bean);
        }
        private void RunAssertionBeaconFields(EPServiceProvider epService)
        {
            EnumHelper.ForEach <EventRepresentationChoice>(
                rep =>
            {
                RunAssertionFields(epService, rep, true);
                RunAssertionFields(epService, rep, false);
            });

#if NOT_SEEMS_INCORRECT
            foreach (var rep in new EventRepresentationChoice[] { EventRepresentationChoice.AVRO })
            {
                RunAssertionFields(epService, rep, true);
                RunAssertionFields(epService, rep, false);
            }
#endif

            // test doc samples
            epService.EPAdministrator.Configuration.AddPlugInSingleRowFunction(
                "generateTagId", GetType(), "GenerateTagId");
            var epl = "create dataflow MyDataFlow\n" +
                      "  create schema SampleSchema(tagId string, locX double, locY double)," +
                      "  " +
                      "  // BeaconSource that produces empty object-array events without delay or interval\n" +
                      "  // until cancelled.\n" +
                      "  BeaconSource -> stream.one {}\n" +
                      "  \n" +
                      "  // BeaconSource that produces one RFIDSchema event populating event properties\n" +
                      "  // from a user-defined function \"generateTagId\" and values.\n" +
                      "  BeaconSource -> stream.two<SampleSchema> {\n" +
                      "    iterations : 1,\n" +
                      "    tagId : generateTagId(),\n" +
                      "    locX : 10,\n" +
                      "    locY : 20 \n" +
                      "  }\n" +
                      "  \n" +
                      "  // BeaconSource that produces 10 object-array events populating the price property \n" +
                      "  // with a random value.\n" +
                      "  BeaconSource -> stream.three {\n" +
                      "    iterations : 1,\n" +
                      "    interval : 10, // every 10 seconds\n" +
                      "    initialDelay : 5, // start after 5 seconds\n" +
                      "    price : MyMath.Random() * 100,\n" +
                      "  }";
            epService.EPAdministrator.CreateEPL(epl);
            epService.EPRuntime.DataFlowRuntime.Instantiate("MyDataFlow");

            // test options-provided beacon field
            epService.EPAdministrator.Configuration.AddEventType <SupportBean>();
            var eplMinimal = "create dataflow MyGraph " +
                             "BeaconSource -> outstream<SupportBean> {iterations:1} " +
                             "EventBusSink(outstream) {}";
            epService.EPAdministrator.CreateEPL(eplMinimal);

            var options = new EPDataFlowInstantiationOptions();
            options.AddParameterURI("BeaconSource/TheString", "E1");
            var instance = epService.EPRuntime.DataFlowRuntime.Instantiate("MyGraph", options);

            var listener = new SupportUpdateListener();
            epService.EPAdministrator.CreateEPL("select * from SupportBean").Events += listener.Update;
            instance.Run();
            Thread.Sleep(200);
            EPAssertionUtil.AssertProps(
                listener.AssertOneGetNewAndReset(), "TheString".Split(','), new object[] { "E1" });

            // invalid: no output stream
            SupportDataFlowAssertionUtil.TryInvalidInstantiate(
                epService, "DF1", "create dataflow DF1 BeaconSource {}",
                "Failed to instantiate data flow 'DF1': Failed initialization for operator 'BeaconSource': BeaconSource operator requires one output stream but produces 0 streams");
        }
Пример #28
0
        public void TestPerfConstantParameters()
        {
            if (InstrumentationHelper.ENABLED)
            {
                InstrumentationHelper.EndTest();
            }                                                                       // not instrumented

            var configuration = SupportConfigFactory.GetConfiguration();

            configuration.AddImport(typeof(SupportStaticMethodLib).FullName);
            configuration.AddEventType("Temperature", typeof(SupportTemperatureBean));
            configuration.AddPlugInSingleRowFunction("sleepme", typeof(SupportStaticMethodLib).FullName, "Sleep", ValueCache.ENABLED);
            _epService = EPServiceProviderManager.GetDefaultProvider(configuration);
            _epService.Initialize();

            var text = "select " +
                       "SupportStaticMethodLib.Sleep(100) as val" +
                       " from Temperature as temp";
            var stmt     = _epService.EPAdministrator.CreateEPL(text);
            var listener = new SupportUpdateListener();

            stmt.Events += listener.Update;

            long startTime = Environment.TickCount;

            for (var i = 0; i < 1000; i++)
            {
                _epService.EPRuntime.SendEvent(new SupportTemperatureBean("a"));
            }
            long endTime = Environment.TickCount;
            var  delta   = endTime - startTime;

            Assert.IsTrue(delta < 2000, "Failed perf test, delta=" + delta);
            stmt.Dispose();

            // test case with non-cache
            configuration.EngineDefaults.ExpressionConfig.IsUdfCache = false;
            _epService = EPServiceProviderManager.GetDefaultProvider(configuration);
            _epService.Initialize();

            stmt         = _epService.EPAdministrator.CreateEPL(text);
            listener     = new SupportUpdateListener();
            stmt.Events += listener.Update;

            startTime = Environment.TickCount;
            _epService.EPRuntime.SendEvent(new SupportTemperatureBean("a"));
            _epService.EPRuntime.SendEvent(new SupportTemperatureBean("a"));
            _epService.EPRuntime.SendEvent(new SupportTemperatureBean("a"));
            endTime = Environment.TickCount;
            delta   = endTime - startTime;

            Assert.IsTrue(delta > 120, "Failed perf test, delta=" + delta);
            stmt.Dispose();

            // test plug-in single-row function
            var textSingleRow = "select " +
                                "sleepme(100) as val" +
                                " from Temperature as temp";
            var stmtSingleRow     = _epService.EPAdministrator.CreateEPL(textSingleRow);
            var listenerSingleRow = new SupportUpdateListener();

            stmtSingleRow.Events += listenerSingleRow.Update;

            startTime = Environment.TickCount;
            for (var i = 0; i < 1000; i++)
            {
                _epService.EPRuntime.SendEvent(new SupportTemperatureBean("a"));
            }
            delta = Environment.TickCount - startTime;

            Assert.IsTrue(delta < 1000, "Failed perf test, delta=" + delta);
            stmtSingleRow.Dispose();
        }
        private void RunAssertionBeaconNoType(EPServiceProvider epService)
        {
            EPDataFlowInstantiationOptions options;

            object[] output;

            epService.EPAdministrator.CreateEPL(
                "create dataflow MyDataFlowOne " +
                "BeaconSource -> BeaconStream {}" +
                "DefaultSupportCaptureOp(BeaconStream) {}");

            var countExpected = 10;
            var futureAtLeast = new DefaultSupportCaptureOp(countExpected, SupportContainer.Instance.LockManager());

            options = new EPDataFlowInstantiationOptions()
                      .OperatorProvider(new DefaultSupportGraphOpProvider(futureAtLeast));
            var df = epService.EPRuntime.DataFlowRuntime.Instantiate("MyDataFlowOne", options);

            df.Start();
            output = futureAtLeast.GetValue(1, TimeUnit.SECONDS);
            Assert.IsTrue(countExpected <= output.Length);
            df.Cancel();

            // BeaconSource with given number of iterations
            epService.EPAdministrator.CreateEPL(
                "create dataflow MyDataFlowTwo " +
                "BeaconSource -> BeaconStream {" +
                "  iterations: 5" +
                "}" +
                "DefaultSupportCaptureOp(BeaconStream) {}");

            var futureExactTwo = new DefaultSupportCaptureOp(5, SupportContainer.Instance.LockManager());

            options = new EPDataFlowInstantiationOptions()
                      .OperatorProvider(new DefaultSupportGraphOpProvider(futureExactTwo));
            epService.EPRuntime.DataFlowRuntime.Instantiate("MyDataFlowTwo", options).Start();
            output = futureExactTwo.GetValue(1, TimeUnit.SECONDS);
            Assert.AreEqual(5, output.Length);

            // BeaconSource with delay
            epService.EPAdministrator.CreateEPL(
                "create dataflow MyDataFlowThree " +
                "BeaconSource -> BeaconStream {" +
                "  iterations: 2," +
                "  initialDelay: 0.5" +
                "}" +
                "DefaultSupportCaptureOp(BeaconStream) {}");

            var futureExactThree = new DefaultSupportCaptureOp(2, SupportContainer.Instance.LockManager());

            options = new EPDataFlowInstantiationOptions()
                      .OperatorProvider(new DefaultSupportGraphOpProvider(futureExactThree));
            var start = PerformanceObserver.MilliTime;

            epService.EPRuntime.DataFlowRuntime.Instantiate("MyDataFlowThree", options).Start();
            output = futureExactThree.GetValue(1, TimeUnit.SECONDS);
            var end = PerformanceObserver.MilliTime;

            Assert.AreEqual(2, output.Length);
            Assert.IsTrue(end - start > 490, "delta=" + (end - start));

            // BeaconSource with period
            epService.EPAdministrator.CreateEPL(
                "create dataflow MyDataFlowFour " +
                "BeaconSource -> BeaconStream {" +
                "  interval: 0.5" +
                "}" +
                "DefaultSupportCaptureOp(BeaconStream) {}");

            var futureFour = new DefaultSupportCaptureOp(2, SupportContainer.Instance.LockManager());

            options = new EPDataFlowInstantiationOptions()
                      .OperatorProvider(new DefaultSupportGraphOpProvider(futureFour));
            epService.EPRuntime.DataFlowRuntime.Instantiate("MyDataFlowFour", options).Start();
            output = futureFour.GetValue(1, TimeUnit.SECONDS);
            Assert.AreEqual(2, output.Length);

            // test Beacon with define typed
            epService.EPAdministrator.CreateEPL("create objectarray schema MyTestOAType(p1 string)");
            epService.EPAdministrator.CreateEPL(
                "create dataflow MyDataFlowFive " +
                "BeaconSource -> BeaconStream<MyTestOAType> {" +
                "  interval: 0.5," +
                "  p1 : 'abc'" +
                "}");
            epService.EPRuntime.DataFlowRuntime.Instantiate("MyDataFlowFive");
        }
Пример #30
0
        private void RunAssertionJoinIndexChoice(EPServiceProvider epService)
        {
            epService.EPAdministrator.Configuration.AddEventType("SSB1", typeof(SupportSimpleBeanOne));
            epService.EPAdministrator.Configuration.AddEventType("SSB2", typeof(SupportSimpleBeanTwo));

            var preloadedEventsOne = new object[] { new SupportSimpleBeanOne("E1", 10, 11, 12), new SupportSimpleBeanOne("E2", 20, 21, 22) };
            var listener           = new SupportUpdateListener();
            var eventSendAssertion = new IndexAssertionEventSend(() => {
                string[] fields = "ssb2.s2,ssb1.s1,ssb1.i1".Split(',');
                epService.EPRuntime.SendEvent(new SupportSimpleBeanTwo("E2", 50, 21, 22));
                EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, new object[] { "E2", "E2", 20 });
                epService.EPRuntime.SendEvent(new SupportSimpleBeanTwo("E1", 60, 11, 12));
                EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, new object[] { "E1", "E1", 10 });
            });

            // no index, since this is "Unique(s1)" we don't need one
            var noindexes = new string[] {};

            AssertIndexChoice(epService, listener, noindexes, preloadedEventsOne, "std:unique(s1)",
                              new IndexAssertion[] {
                new IndexAssertion(null, "s1 = s2", true, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2 and l1 = l2", true, eventSendAssertion),
            });

            // single index one field (duplicate in essence, since "Unique(s1)"
            var indexOneField = new string[] { "create unique index One on MyWindow (s1)" };

            AssertIndexChoice(epService, listener, indexOneField, preloadedEventsOne, "std:unique(s1)",
                              new IndexAssertion[] {
                new IndexAssertion(null, "s1 = s2", true, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2 and l1 = l2", true, eventSendAssertion),
            });

            // single index two field (includes "Unique(s1)")
            var indexTwoField = new string[] { "create unique index One on MyWindow (s1, l1)" };

            AssertIndexChoice(epService, listener, indexTwoField, preloadedEventsOne, "std:unique(s1)",
                              new IndexAssertion[] {
                new IndexAssertion(null, "s1 = s2", true, eventSendAssertion),
                new IndexAssertion(null, "d1 = d2", false, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2 and l1 = l2", true, eventSendAssertion),
            });

            // two index one unique ("Unique(s1)")
            var indexSetTwo = new string[] {
                "create index One on MyWindow (s1)",
                "create unique index Two on MyWindow (s1, d1)"
            };

            AssertIndexChoice(epService, listener, indexSetTwo, preloadedEventsOne, "std:unique(s1)",
                              new IndexAssertion[] {
                new IndexAssertion(null, "d1 = d2", false, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2", true, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2 and l1 = l2", true, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2 and d1 = d2 and l1 = l2", true, eventSendAssertion),
            });

            // two index one unique ("win:keepall()")
            AssertIndexChoice(epService, listener, indexSetTwo, preloadedEventsOne, "win:keepall()",
                              new IndexAssertion[] {
                new IndexAssertion(null, "d1 = d2", false, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2", false, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2 and l1 = l2", false, eventSendAssertion),
                new IndexAssertion(null, "s1 = s2 and d1 = d2 and l1 = l2", true, eventSendAssertion),
                new IndexAssertion(null, "d1 = d2 and s1 = s2", true, eventSendAssertion),
            });
        }
 public WriteRunnable(EPServiceProvider epService)
 {
     this._epService = epService;
 }
Пример #32
0
        private void RunAssertionRightOuterJoinLateStart(EPServiceProvider epService)
        {
            // Test for ESPER-186 Iterator not honoring order by clause for grouped join query with output-rate clause
            // Test for ESPER-187 Join of two or more named windows on late start may not return correct aggregation state on iterate

            // create window for Leave events
            string stmtTextCreate = "create window WindowLeave#time(6000) as select timeLeave, id, location from " + typeof(SupportQueueLeave).FullName;

            epService.EPAdministrator.CreateEPL(stmtTextCreate);
            string stmtTextInsert = "insert into WindowLeave select timeLeave, id, location from " + typeof(SupportQueueLeave).FullName;

            epService.EPAdministrator.CreateEPL(stmtTextInsert);

            // create second window for enter events
            stmtTextCreate = "create window WindowEnter#time(6000) as select location, sku, timeEnter, id from " + typeof(SupportQueueEnter).FullName;
            epService.EPAdministrator.CreateEPL(stmtTextCreate);
            stmtTextInsert = "insert into WindowEnter select location, sku, timeEnter, id from " + typeof(SupportQueueEnter).FullName;
            epService.EPAdministrator.CreateEPL(stmtTextInsert);

            // fill data
            for (int i = 0; i < 8; i++)
            {
                string location = Convert.ToString(i / 2);
                epService.EPRuntime.SendEvent(new SupportQueueLeave(i + 1, location, 247));
            }

            for (int i = 0; i < 10; i++)
            {
                string location = Convert.ToString(i / 2);
                string sku      = (i % 2 == 0) ? "166583" : "169254";
                epService.EPRuntime.SendEvent(new SupportQueueEnter(i + 1, location, sku, 123));
            }

            string stmtTextOne = "select s1.location as loc, sku, avg((coalesce(timeLeave, 250) - timeEnter)) as avgTime, " +
                                 "count(timeEnter) as cntEnter, count(timeLeave) as cntLeave, (count(timeEnter) - count(timeLeave)) as diff " +
                                 "from WindowLeave as s0 right outer join WindowEnter as s1 " +
                                 "on s0.id = s1.id and s0.location = s1.location " +
                                 "group by s1.location, sku " +
                                 "output every 1.0 seconds " +
                                 "order by s1.location, sku";
            EPStatement stmtOne = epService.EPAdministrator.CreateEPL(stmtTextOne);

            string stmtTextTwo = "select s1.location as loc, sku, avg((coalesce(timeLeave, 250) - timeEnter)) as avgTime, " +
                                 "count(timeEnter) as cntEnter, count(timeLeave) as cntLeave, (count(timeEnter) - count(timeLeave)) as diff " +
                                 "from WindowEnter as s1 left outer join WindowLeave as s0 " +
                                 "on s0.id = s1.id and s0.location = s1.location " +
                                 "group by s1.location, sku " +
                                 "output every 1.0 seconds " +
                                 "order by s1.location, sku";
            EPStatement stmtTwo = epService.EPAdministrator.CreateEPL(stmtTextTwo);

            var expected = new object[][] {
                new object[] { "0", "166583", 124.0, 1L, 1L, 0L },
                new object[] { "0", "169254", 124.0, 1L, 1L, 0L },
                new object[] { "1", "166583", 124.0, 1L, 1L, 0L },
                new object[] { "1", "169254", 124.0, 1L, 1L, 0L },
                new object[] { "2", "166583", 124.0, 1L, 1L, 0L },
                new object[] { "2", "169254", 124.0, 1L, 1L, 0L },
                new object[] { "3", "166583", 124.0, 1L, 1L, 0L },
                new object[] { "3", "169254", 124.0, 1L, 1L, 0L },
                new object[] { "4", "166583", 127.0, 1L, 0L, 1L },
                new object[] { "4", "169254", 127.0, 1L, 0L, 1L }
            };

            // assert iterator results
            EventBean[] received = EPAssertionUtil.EnumeratorToArray(stmtTwo.GetEnumerator());
            EPAssertionUtil.AssertPropsPerRow(received, "loc,sku,avgTime,cntEnter,cntLeave,diff".Split(','), expected);
            received = EPAssertionUtil.EnumeratorToArray(stmtOne.GetEnumerator());
            EPAssertionUtil.AssertPropsPerRow(received, "loc,sku,avgTime,cntEnter,cntLeave,diff".Split(','), expected);

            epService.EPAdministrator.DestroyAllStatements();
        }
 public override void Run(EPServiceProvider epService)
 {
     TryMT(epService, 2);
 }
Пример #34
0
        private void RunAssertionFullOuterJoinNamedAggregationLateStart(EPServiceProvider epService)
        {
            // create window
            string      stmtTextCreate = "create window MyWindowFO#groupwin(TheString, IntPrimitive)#length(3) as select TheString, IntPrimitive, BoolPrimitive from " + typeof(SupportBean).FullName;
            EPStatement stmtCreate     = epService.EPAdministrator.CreateEPL(stmtTextCreate);

            // create insert into
            string stmtTextInsert = "insert into MyWindowFO select TheString, IntPrimitive, BoolPrimitive from " + typeof(SupportBean).FullName;

            epService.EPAdministrator.CreateEPL(stmtTextInsert);

            // fill window
            var stringValues = new string[] { "c0", "c1", "c2" };

            for (int i = 0; i < stringValues.Length; i++)
            {
                for (int j = 0; j < 3; j++)
                {
                    for (int k = 0; k < 2; k++)
                    {
                        var beanX = new SupportBean(stringValues[i], j);
                        beanX.BoolPrimitive = true;
                        epService.EPRuntime.SendEvent(beanX);
                    }
                }
            }
            var bean = new SupportBean("c1", 2);

            bean.BoolPrimitive = true;
            epService.EPRuntime.SendEvent(bean);

            EventBean[] received = EPAssertionUtil.EnumeratorToArray(stmtCreate.GetEnumerator());
            Assert.AreEqual(19, received.Length);

            // create select stmt
            string stmtTextSelect = "select TheString, IntPrimitive, count(BoolPrimitive) as cntBool, symbol " +
                                    "from MyWindowFO full outer join " + typeof(SupportMarketDataBean).FullName + "#keepall " +
                                    "on TheString = symbol " +
                                    "group by TheString, IntPrimitive, symbol order by TheString, IntPrimitive, symbol";
            EPStatement stmtSelect = epService.EPAdministrator.CreateEPL(stmtTextSelect);

            // send outer join events
            this.SendMarketBean(epService, "c0");
            this.SendMarketBean(epService, "c3");

            // get iterator results
            received = EPAssertionUtil.EnumeratorToArray(stmtSelect.GetEnumerator());
            EPAssertionUtil.AssertPropsPerRow(received, "TheString,IntPrimitive,cntBool,symbol".Split(','),
                                              new object[][] {
                new object[] { null, null, 0L, "c3" },
                new object[] { "c0", 0, 2L, "c0" },
                new object[] { "c0", 1, 2L, "c0" },
                new object[] { "c0", 2, 2L, "c0" },
                new object[] { "c1", 0, 2L, null },
                new object[] { "c1", 1, 2L, null },
                new object[] { "c1", 2, 3L, null },
                new object[] { "c2", 0, 2L, null },
                new object[] { "c2", 1, 2L, null },
                new object[] { "c2", 2, 2L, null },
            });

            /*
             * for (int i = 0; i < received.Length; i++)
             * {
             *  Log.Info("string=" + received[i].Get("string") +
             *          " IntPrimitive=" + received[i].Get("IntPrimitive") +
             *          " cntBool=" + received[i].Get("cntBool") +
             *          " symbol=" + received[i].Get("symbol"));
             * }
             */

            stmtSelect.Dispose();
            stmtCreate.Dispose();
        }
Пример #35
0
 public HomeController(EPServiceProvider provider)
 {
     Provider = provider;
 }
Пример #36
0
        private void RunAssertionJoinNamedAndStream(EPServiceProvider epService)
        {
            // create window
            string      stmtTextCreate = "create window MyWindowJNS#keepall as select TheString as a, IntPrimitive as b from " + typeof(SupportBean).FullName;
            EPStatement stmtCreate     = epService.EPAdministrator.CreateEPL(stmtTextCreate);
            var         listenerWindow = new SupportUpdateListener();

            stmtCreate.Events += listenerWindow.Update;

            // create delete stmt
            string stmtTextDelete = "on " + typeof(SupportBean_A).FullName + " delete from MyWindowJNS where id = a";

            epService.EPAdministrator.CreateEPL(stmtTextDelete);

            // create insert into
            string stmtTextInsertOne = "insert into MyWindowJNS select TheString as a, IntPrimitive as b from " + typeof(SupportBean).FullName;

            epService.EPAdministrator.CreateEPL(stmtTextInsertOne);

            // create consumer
            var    fields            = new string[] { "symbol", "a", "b" };
            string stmtTextSelectOne = "select irstream symbol, a, b " +
                                       " from " + typeof(SupportMarketDataBean).FullName + "#length(10) as s0," +
                                       "MyWindowJNS as s1 where s1.a = symbol";
            EPStatement stmtSelectOne = epService.EPAdministrator.CreateEPL(stmtTextSelectOne);
            var         listener      = new SupportUpdateListener();

            stmtSelectOne.Events += listener.Update;
            EPAssertionUtil.AssertEqualsAnyOrder(stmtSelectOne.EventType.PropertyNames, new string[] { "symbol", "a", "b" });
            Assert.AreEqual(typeof(string), stmtSelectOne.EventType.GetPropertyType("symbol"));
            Assert.AreEqual(typeof(string), stmtSelectOne.EventType.GetPropertyType("a"));
            Assert.AreEqual(typeof(int), stmtSelectOne.EventType.GetPropertyType("b"));

            SendMarketBean(epService, "S1");
            Assert.IsFalse(listener.IsInvoked);

            SendSupportBean(epService, "S1", 1);
            EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, new object[] { "S1", "S1", 1 });

            SendSupportBean_A(epService, "S1"); // deletes from window
            EPAssertionUtil.AssertProps(listener.AssertOneGetOldAndReset(), fields, new object[] { "S1", "S1", 1 });

            SendMarketBean(epService, "S1");
            Assert.IsFalse(listener.IsInvoked);

            SendSupportBean(epService, "S2", 2);
            Assert.IsFalse(listener.IsInvoked);

            SendMarketBean(epService, "S2");
            EPAssertionUtil.AssertProps(listener.AssertOneGetNewAndReset(), fields, new object[] { "S2", "S2", 2 });

            SendSupportBean(epService, "S3", 3);
            SendSupportBean(epService, "S3", 4);
            Assert.IsFalse(listener.IsInvoked);

            SendMarketBean(epService, "S3");
            Assert.AreEqual(2, listener.LastNewData.Length);
            listener.Reset();

            SendSupportBean_A(epService, "S3"); // deletes from window
            Assert.AreEqual(2, listener.LastOldData.Length);
            listener.Reset();

            SendMarketBean(epService, "S3");
            Assert.IsFalse(listener.IsInvoked);
        }