Пример #1
0
        public static ICollection <EventBean> SingleIndexLookup(ExprEvaluator[] evaluators, EventBean[] eventsPerStream, ExprEvaluatorContext exprEvaluatorContext, PropertyIndexedEventTableSingle index)
        {
            var first = true;
            ICollection <EventBean> result = null;
            var evaluateParams             = new EvaluateParams(eventsPerStream, true, exprEvaluatorContext);

            foreach (var evaluator in evaluators)
            {
                var key = evaluator.Evaluate(evaluateParams);
                ICollection <EventBean> found = index.Lookup(key);
                if (found != null && !found.IsEmpty())
                {
                    if (result == null)
                    {
                        result = found;
                    }
                    else if (first)
                    {
                        var copy = new LinkedHashSet <EventBean>();
                        copy.AddAll(result);
                        copy.AddAll(found);
                        result = copy;
                        first  = false;
                    }
                    else
                    {
                        result.AddAll(found);
                    }
                }
            }

            return(result);
        }
Пример #2
0
        protected void ReadConfig(IOrmConfigGroup ormConfigGroup)
        {
            LinkedHashSet <IEntityConfig> entities = new LinkedHashSet <IEntityConfig>();

            entities.AddAll(ormConfigGroup.GetLocalEntityConfigs());
            entities.AddAll(ormConfigGroup.GetExternalEntityConfigs());

            foreach (IEntityConfig entityConfig in entities)
            {
                Type entityType = entityConfig.EntityType;
                if (EntityMetaDataProvider.GetMetaData(entityType, true) != null)
                {
                    continue;
                }
                Type realType = entityConfig.RealType;

                EntityMetaData metaData = new EntityMetaData();
                metaData.EntityType  = entityType;
                metaData.RealType    = realType;
                metaData.LocalEntity = entityConfig.Local;

                EntityMetaDataReader.AddMembers(metaData, entityConfig);

                managedEntityMetaData.Add(metaData);
                lock (EntityMetaDataExtendable)
                {
                    EntityMetaDataExtendable.RegisterEntityMetaData(metaData);
                }
            }
        }
Пример #3
0
        public static ISet<EventBean> SingleIndexLookup(
            ExprEvaluator[] evaluators,
            EventBean[] eventsPerStream,
            ExprEvaluatorContext exprEvaluatorContext,
            PropertyHashedEventTable index)
        {
            bool first = true;
            ISet<EventBean> result = null;

            foreach (ExprEvaluator evaluator in evaluators) {
                object key = evaluator.Evaluate(eventsPerStream, true, exprEvaluatorContext);
                ISet<EventBean> found = index.Lookup(key);
                if (found != null && !found.IsEmpty()) {
                    if (result == null) {
                        result = found;
                    }
                    else if (first) {
                        LinkedHashSet<EventBean> copy = new LinkedHashSet<EventBean>();
                        copy.AddAll(result);
                        copy.AddAll(found);
                        result = copy;
                        first = false;
                    }
                    else {
                        result.AddAll(found);
                    }
                }
            }

            return result;
        }
Пример #4
0
        protected void AddDefaultChildBehavior(Type behaviorType)
        {
            IBytecodeBehavior behavior = BeanContext.RegisterBean <IBytecodeBehavior>(behaviorType).Finish();

            childBehaviors.Add(behavior);
            supportedEnhancements.AddAll(behavior.GetEnhancements());
        }
Пример #5
0
        public static ISet<string> AssignEventAsTagNumber(
            ISet<string> priorAllTags,
            EvalForgeNode evalForgeNode)
        {
            var allTagNamesOrdered = new LinkedHashSet<string>();
            var filterFactoryNodes = EvalNodeUtil.RecursiveGetChildNodes(
                evalForgeNode,
                StreamSpecCompiler.FilterForFilterFactoryNodes.INSTANCE);
            if (priorAllTags != null) {
                allTagNamesOrdered.AddAll(priorAllTags);
            }

            foreach (var filterNode in filterFactoryNodes) {
                var forge = (EvalFilterForgeNode) filterNode;
                int tagNumber;
                if (forge.EventAsName != null) {
                    if (!allTagNamesOrdered.Contains(forge.EventAsName)) {
                        allTagNamesOrdered.Add(forge.EventAsName);
                        tagNumber = allTagNamesOrdered.Count - 1;
                    }
                    else {
                        tagNumber = FindTagNumber(forge.EventAsName, allTagNamesOrdered);
                    }

                    forge.EventAsTagNumber = tagNumber;
                }
            }

            return allTagNamesOrdered;
        }
Пример #6
0
        /// <summary>
        ///     NOTE: Code-generation-invoked method, method name and parameter order matters
        ///     Flattens a list of pairs of join result sets.
        /// </summary>
        /// <param name="joinPostings">is the list</param>
        /// <returns>is the consolidate sets</returns>
        public static UniformPair<ISet<MultiKeyArrayOfKeys<EventBean>>> FlattenBatchJoin(
            IList<UniformPair<ISet<MultiKeyArrayOfKeys<EventBean>>>> joinPostings)
        {
            if (joinPostings.IsEmpty()) {
                return new UniformPair<ISet<MultiKeyArrayOfKeys<EventBean>>>(null, null);
            }

            if (joinPostings.Count == 1) {
                return new UniformPair<ISet<MultiKeyArrayOfKeys<EventBean>>>(
                    joinPostings[0].First,
                    joinPostings[0].Second);
            }

            ISet<MultiKeyArrayOfKeys<EventBean>> newEvents = new LinkedHashSet<MultiKeyArrayOfKeys<EventBean>>();
            ISet<MultiKeyArrayOfKeys<EventBean>> oldEvents = new LinkedHashSet<MultiKeyArrayOfKeys<EventBean>>();

            foreach (var pair in joinPostings) {
                var newData = pair.First;
                var oldData = pair.Second;

                if (newData != null) {
                    newEvents.AddAll(newData);
                }

                if (oldData != null) {
                    oldEvents.AddAll(oldData);
                }
            }

            return new UniformPair<ISet<MultiKeyArrayOfKeys<EventBean>>>(newEvents, oldEvents);
        }
Пример #7
0
        /// <summary>Get all of the parents and ancestor elements of the matched elements.</summary>
        /// <returns>all of the parents and ancestor elements of the matched elements</returns>
        public virtual iText.StyledXmlParser.Jsoup.Select.Elements Parents()
        {
            ICollection <Element> combo = new LinkedHashSet <Element>();

            foreach (Element e in this)
            {
                combo.AddAll(e.Parents());
            }
            return(new iText.StyledXmlParser.Jsoup.Select.Elements(combo));
        }
Пример #8
0
        private static CreateSchemaDesc GetSchemaDesc(EsperEPL2GrammarParser.CreateSchemaDefContext ctx, AssignedType assignedType)
        {
            var schemaName  = ctx.name.Text;
            var columnTypes = GetColTypeList(ctx.createColumnList());

            // get model-after types (could be multiple for variants)
            ISet <string> typeNames = new LinkedHashSet <string>();

            if (ctx.variantList() != null)
            {
                IList <EsperEPL2GrammarParser.VariantListElementContext> variantCtxs = ctx.variantList().variantListElement();
                foreach (var variantCtx in variantCtxs)
                {
                    typeNames.Add(variantCtx.GetText().UnmaskTypeName());
                }
            }

            // get inherited and start timestamp and end timestamps
            string        startTimestamp = null;
            string        endTimestamp   = null;
            ISet <string> inherited      = new LinkedHashSet <string>();
            ISet <string> copyFrom       = new LinkedHashSet <string>();

            if (ctx.createSchemaQual() != null)
            {
                IList <EsperEPL2GrammarParser.CreateSchemaQualContext> qualCtxs = ctx.createSchemaQual();
                foreach (var qualCtx in qualCtxs)
                {
                    var qualName      = qualCtx.i.Text.ToLower();
                    var cols          = ASTUtil.GetIdentList(qualCtx.columnList());
                    var qualNameLower = qualName.ToLower();
                    switch (qualNameLower)
                    {
                    case "inherits":
                        inherited.AddAll(cols);
                        continue;

                    case "starttimestamp":
                        startTimestamp = cols[0];
                        continue;

                    case "endtimestamp":
                        endTimestamp = cols[0];
                        continue;

                    case "copyfrom":
                        copyFrom.AddAll(cols);
                        continue;
                    }
                    throw new EPException("Expected 'inherits', 'starttimestamp', 'endtimestamp' or 'copyfrom' keyword after create-schema clause but encountered '" + qualName + "'");
                }
            }

            return(new CreateSchemaDesc(schemaName, typeNames, columnTypes, inherited, assignedType, startTimestamp, endTimestamp, copyFrom));
        }
Пример #9
0
        public static IList<FilterSpecParamExprNodeForge> MakeExprNodeList(
            IList<FilterSpecCompiled> filterSpecCompileds,
            IList<FilterSpecParamExprNodeForge> additionalBooleanExpressions)
        {
            ISet<FilterSpecParamExprNodeForge> boolExprs = new LinkedHashSet<FilterSpecParamExprNodeForge>();
            foreach (var spec in filterSpecCompileds) {
                spec.TraverseFilterBooleanExpr(v => boolExprs.Add(v));
            }

            boolExprs.AddAll(additionalBooleanExpressions);
            return new List<FilterSpecParamExprNodeForge>(boolExprs);
        }
Пример #10
0
        internal static ISet <EventBean> Normalize(IDictionary <object, ISet <EventBean> > submapOne, IDictionary <object, ISet <EventBean> > submapTwo)
        {
            if (submapOne.Count == 0)
            {
                return(Normalize(submapTwo));
            }
            if (submapTwo.Count == 0)
            {
                return(Normalize(submapOne));
            }
            ISet <EventBean> result = new LinkedHashSet <EventBean>();

            foreach (var entry in submapOne)
            {
                result.AddAll(entry.Value);
            }
            foreach (var entry in submapTwo)
            {
                result.AddAll(entry.Value);
            }
            return(result);
        }
Пример #11
0
        private ISet <EventBean> NormalizeCollection(IDictionary <object, ISet <EventBean> > submapOne, IDictionary <object, ISet <EventBean> > submapTwo)
        {
            if (submapOne.Count == 0)
            {
                return(NormalizeCollection(submapTwo));
            }
            if (submapTwo.Count == 0)
            {
                return(NormalizeCollection(submapOne));
            }
            var result = new LinkedHashSet <EventBean>();

            foreach (var entry in submapOne)
            {
                result.AddAll(entry.Value);
            }
            foreach (var entry in submapTwo)
            {
                result.AddAll(entry.Value);
            }
            return(result);
        }
Пример #12
0
        protected internal static ISet<EventBean> Normalize(
            IDictionary<object, ISet<EventBean>> submapOne,
            IDictionary<object, ISet<EventBean>> submapTwo)
        {
            if (submapOne.Count == 0) {
                return Normalize(submapTwo);
            }

            if (submapTwo.Count == 0) {
                return Normalize(submapOne);
            }

            ISet<EventBean> result = new LinkedHashSet<EventBean>();
            foreach (KeyValuePair<object, ISet<EventBean>> entry in submapOne) {
                result.AddAll(entry.Value);
            }

            foreach (KeyValuePair<object, ISet<EventBean>> entry in submapTwo) {
                result.AddAll(entry.Value);
            }

            return result;
        }
Пример #13
0
        /// <summary>Normalizes text decoration values.</summary>
        /// <param name="value">the text decoration value</param>
        /// <returns>a set of normalized decoration values</returns>
        private static ICollection <String> NormalizeTextDecoration(String value)
        {
            String[] parts = iText.IO.Util.StringUtil.Split(value, "\\s+");
            // LinkedHashSet to make order invariant of JVM
            ICollection <String> merged = new LinkedHashSet <String>();

            merged.AddAll(JavaUtil.ArraysAsList(parts));
            // if none and any other decoration are used together, none is displayed
            if (merged.Contains(CommonCssConstants.NONE))
            {
                merged.Clear();
            }
            return(merged);
        }
Пример #14
0
        public void RebuildContext(MethodInfo frameworkMethod)
        {
            DisposeContext();
            Properties.ResetApplication();
            Properties.LoadBootstrapPropertyFile();

            Properties baseProps = new Properties(Properties.Application);

            ExtendProperties(frameworkMethod, baseProps);

            LinkedHashSet <Type> testClassLevelTestFrameworkModulesList = new LinkedHashSet <Type>();
            LinkedHashSet <Type> testClassLevelTestModulesList          = new LinkedHashSet <Type>();

            testClassLevelTestModulesList.AddAll(BuildTestModuleList(frameworkMethod));
            testClassLevelTestFrameworkModulesList.AddAll(BuildFrameworkTestModuleList(frameworkMethod));

            Type[] frameworkModules   = testClassLevelTestFrameworkModulesList.ToArray();
            Type[] applicationModules = testClassLevelTestModulesList.ToArray();

            testClassLevelContext = BeanContextFactory.CreateBootstrap(baseProps);
            bool success = false;

            try
            {
                IServiceContext currentBeanContext = testClassLevelContext;
                if (frameworkModules.Length > 0)
                {
                    currentBeanContext = currentBeanContext.CreateService(delegate(IBeanContextFactory childContextFactory)
                    {
                        RebuildContextDetails(childContextFactory);
                    }, frameworkModules);
                }
                if (applicationModules.Length > 0)
                {
                    currentBeanContext = currentBeanContext.CreateService(applicationModules);
                }
                currentBeanContext.RegisterWithLifecycle(originalTestInstance).Finish();
                beanContext = currentBeanContext;
                success     = true;
            }
            finally
            {
                if (!success && testClassLevelContext != null)
                {
                    testClassLevelContext.GetService <IThreadLocalCleanupController>().CleanupThreadLocal();
                }
            }
        }
Пример #15
0
        protected internal static ISet<EventBean> Normalize(IDictionary<object, ISet<EventBean>> submap)
        {
            if (submap.Count == 0) {
                return null;
            }

            if (submap.Count == 1) {
                return submap.Get(submap.Keys.First());
            }

            ISet<EventBean> result = new LinkedHashSet<EventBean>();
            foreach (KeyValuePair<object, ISet<EventBean>> entry in submap) {
                result.AddAll(entry.Value);
            }

            return result;
        }
Пример #16
0
        public override void Visit(TypeAttributes access, String name, Type superName, Type[] interfaces)
        {
            LinkedHashSet <Type> ints = new LinkedHashSet <Type>(interfaces);

            ints.AddAll(newInterfaces);
            Type type = State.CurrentType;

            while (type != null && type != typeof(Object))
            {
                foreach (Type alreadyImplementedInterface in type.GetInterfaces())
                {
                    ints.Remove(alreadyImplementedInterface);
                }
                type = type.BaseType;
            }
            base.Visit(access, name, superName, ints.ToArray());
        }
Пример #17
0
        internal static ISet <EventBean> Normalize(IDictionary <object, ISet <EventBean> > submap)
        {
            if (submap.Count == 0)
            {
                return(null);
            }
            if (submap.Count == 1)
            {
                return(submap.Get(submap.Keys.First()));
            }
            ISet <EventBean> result = new LinkedHashSet <EventBean>();

            foreach (var entry in submap)
            {
                result.AddAll(entry.Value);
            }
            return(result);
        }
Пример #18
0
        private ISet <EventBean> NormalizeCollection(IDictionary <Object, ISet <EventBean> > submap)
        {
            if (submap.Count == 0)
            {
                return(null);
            }
            if (submap.Count == 1)
            {
                return(submap.Get(submap.First().Key));
            }
            var result = new LinkedHashSet <EventBean>();

            foreach (var entry in submap)
            {
                result.AddAll(entry.Value);
            }
            return(result);
        }
Пример #19
0
        private PatternStreamSpecCompiled CompileInternal(
            StatementContext context,
            ICollection <string> eventTypeReferences,
            bool isInsertInto,
            ICollection <int> assignedTypeNumberStack,
            MatchEventSpec tags,
            IEnumerable <string> priorAllTags,
            bool isJoin,
            bool isContextDeclaration,
            bool isOnTrigger)
        {
            // validate
            if ((_suppressSameEventMatches || _discardPartialsOnMatch) &&
                (isJoin || isContextDeclaration || isOnTrigger))
            {
                throw new ExprValidationException(
                          "Discard-partials and suppress-matches is not supported in a joins, context declaration and on-action");
            }

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

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

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

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

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

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

            return(new PatternStreamSpecCompiled(
                       compiledEvalFactoryNode, tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, ViewSpecs,
                       OptionalStreamName, Options, _suppressSameEventMatches, _discardPartialsOnMatch));
        }
Пример #20
0
        public static SerdeEventPropertyDesc ForgeForEventProperty(
            EventType eventTypeSerde,
            string propertyName,
            object propertyType,
            StatementRawInfo raw,
            SerdeCompileTimeResolver resolver)
        {
            DataInputOutputSerdeForge forge;

            if (propertyType == null)
            {
                return(new SerdeEventPropertyDesc(new DataInputOutputSerdeForgeSingleton(typeof(DIOSkipSerde)), EmptySet <EventType> .Instance));
            }

            if (propertyType is Type propertyTypeType)
            {
                // handle special Json catch-all types
                if (eventTypeSerde is JsonEventType)
                {
                    forge = null;
                    if (propertyTypeType == typeof(IDictionary <string, object>))
                    {
                        forge = new DataInputOutputSerdeForgeSingleton(typeof(DIOJsonObjectSerde));
                    }
                    else if (propertyTypeType == typeof(object[]))
                    {
                        forge = new DataInputOutputSerdeForgeSingleton(typeof(DIOJsonArraySerde));
                    }
                    else if (propertyTypeType == typeof(object))
                    {
                        forge = new DataInputOutputSerdeForgeSingleton(typeof(DIOJsonAnyValueSerde));
                    }

                    if (forge != null)
                    {
                        return(new SerdeEventPropertyDesc(forge, EmptySet <EventType> .Instance));
                    }
                }

                // handle all Class-type properties
                var typedProperty = (Type)propertyType;
                if (typedProperty == typeof(object) && propertyName.Equals(INTERNAL_RESERVED_PROPERTY))
                {
                    forge = new DataInputOutputSerdeForgeSingleton(
                        typeof(DIOSkipSerde));                         // for expression data window or others that include transient references in the field
                }
                else
                {
                    forge = resolver.SerdeForEventProperty(typedProperty, eventTypeSerde.Name, propertyName, raw);
                }

                return(new SerdeEventPropertyDesc(forge, EmptySet <EventType> .Instance));
            }

            if (propertyType is EventType)
            {
                var eventType = (EventType)propertyType;
                Func <DataInputOutputSerdeForgeParameterizedVars, CodegenExpression> func = vars =>
                                                                                            ResolveTypeCodegenGivenResolver(eventType, vars.OptionalEventTypeResolver);
                forge = new DataInputOutputSerdeForgeEventSerde("NullableEvent", func);
                return(new SerdeEventPropertyDesc(forge, Collections.SingletonSet(eventType)));
            }
            else if (propertyType is EventType[])
            {
                var eventType = ((EventType[])propertyType)[0];
                Func <DataInputOutputSerdeForgeParameterizedVars, CodegenExpression> func = vars =>
                                                                                            ResolveTypeCodegenGivenResolver(eventType, vars.OptionalEventTypeResolver);
                forge = new DataInputOutputSerdeForgeEventSerde("NullableEventArray", func);
                return(new SerdeEventPropertyDesc(forge, Collections.SingletonSet(eventType)));
            }
            else if (propertyType is TypeBeanOrUnderlying)
            {
                var eventType = ((TypeBeanOrUnderlying)propertyType).EventType;
                Func <DataInputOutputSerdeForgeParameterizedVars, CodegenExpression> func = vars =>
                                                                                            ResolveTypeCodegenGivenResolver(eventType, vars.OptionalEventTypeResolver);
                forge = new DataInputOutputSerdeForgeEventSerde("NullableEventOrUnderlying", func);
                return(new SerdeEventPropertyDesc(forge, Collections.SingletonSet(eventType)));
            }
            else if (propertyType is TypeBeanOrUnderlying[])
            {
                var eventType = ((TypeBeanOrUnderlying[])propertyType)[0].EventType;
                Func <DataInputOutputSerdeForgeParameterizedVars, CodegenExpression> func = vars =>
                                                                                            ResolveTypeCodegenGivenResolver(eventType, vars.OptionalEventTypeResolver);
                forge = new DataInputOutputSerdeForgeEventSerde("NullableEventArrayOrUnderlying", func);
                return(new SerdeEventPropertyDesc(forge, Collections.SingletonSet(eventType)));
            }
            else if (propertyType is IDictionary <string, object> keyValueProperties)
            {
                var keys        = new string[keyValueProperties.Count];
                var serdes      = new DataInputOutputSerdeForge[keyValueProperties.Count];
                var index       = 0;
                var nestedTypes = new LinkedHashSet <EventType>();

                // Rewrite all properties where the value is a string.  First, gather all instances that need
                // to be rewritten into the class that matches the type.
                keyValueProperties
                .Where(entry => entry.Value is string)
                .ToList()
                .ForEach(
                    entry => {
                    var value = entry.Value.ToString()?.Trim();
                    var clazz = TypeHelper.GetPrimitiveTypeForName(value);
                    if (clazz != null)
                    {
                        keyValueProperties[entry.Key] = clazz;
                    }
                });

                foreach (var entry in keyValueProperties)
                {
                    keys[index] = entry.Key;
                    var desc = ForgeForEventProperty(eventTypeSerde, entry.Key, entry.Value, raw, resolver);
                    nestedTypes.AddAll(desc.NestedTypes);
                    serdes[index] = desc.Forge;
                    index++;
                }

                var functions = new Func <DataInputOutputSerdeForgeParameterizedVars, CodegenExpression> [2];
                functions[0] = vars => Constant(keys);
                functions[1] = vars => DataInputOutputSerdeForgeExtensions.CodegenArray(serdes, vars.Method, vars.Scope, vars.OptionalEventTypeResolver);
                forge        = new DataInputOutputSerdeForgeParameterized(typeof(DIOMapPropertySerde).Name, functions);
                return(new SerdeEventPropertyDesc(forge, nestedTypes));
            }
            else
            {
                throw new EPException(
                          "Failed to determine serde for unrecognized property value type '" +
                          propertyType +
                          "' for property '" +
                          propertyName +
                          "' of type '" +
                          eventTypeSerde.Name +
                          "'");
            }
        }
Пример #21
0
        /// <summary>
        ///     Performs the initialization.
        /// </summary>
        /// <param name="startTime">optional start time</param>
        protected void DoInitialize(long? startTime)
        {
            Log.Info("Initializing runtime URI '" + URI + "' version " + RuntimeVersion.RUNTIME_VERSION);

            // Retain config-at-initialization since config-last-provided can be set to new values and "initialize" can be called
            _configAtInitialization = _configLastProvided;

            // Verify settings
            if (_configLastProvided.Runtime.Threading.IsInternalTimerEnabled &&
                _configLastProvided.Common.TimeSource.TimeUnit != TimeUnit.MILLISECONDS) {
                throw new ConfigurationException("Internal timer requires millisecond time resolution");
            }

            // This setting applies to all runtimes in a given VM
            ExecutionPathDebugLog.IsDebugEnabled = _configLastProvided.Runtime.Logging.IsEnableExecutionDebug;
            ExecutionPathDebugLog.IsTimerDebugEnabled = _configLastProvided.Runtime.Logging.IsEnableTimerDebug;

            // This setting applies to all runtimes in a given VM
            AuditPath.AuditPattern = _configLastProvided.Runtime.Logging.AuditPattern;

            if (_runtimeEnvironment != null) {
                if (ServiceStatusProvider != null) {
                    ServiceStatusProvider.Set(false);
                }

                _runtimeEnvironment.Services.TimerService.StopInternalClock(false);

                if (_configLastProvided.Runtime.MetricsReporting.IsRuntimeMetrics) {
                    DestroyEngineMetrics(_runtimeEnvironment.Services.RuntimeURI);
                }

                _runtimeEnvironment.Runtime.Initialize();

                _runtimeEnvironment.Services.Destroy();
            }

            ServiceStatusProvider = new AtomicBoolean(true);
            // Make EP services context factory
            var epServicesContextFactoryClassName = _configLastProvided.Runtime.EPServicesContextFactoryClassName;
            EPServicesContextFactory epServicesContextFactory;
            if (epServicesContextFactoryClassName == null) {
                // Check system properties
                epServicesContextFactoryClassName = Environment.GetEnvironmentVariable("ESPER_EPSERVICE_CONTEXT_FACTORY_CLASS");
            }

            if (epServicesContextFactoryClassName == null) {
                epServicesContextFactory = new EPServicesContextFactoryDefault(Container);
            }
            else {
                Type clazz;
                try {
                    clazz = TransientConfigurationResolver.ResolveClassForNameProvider(_configLastProvided.Common.TransientConfiguration)
                        .ClassForName(epServicesContextFactoryClassName);
                }
                catch (TypeLoadException) {
                    throw new ConfigurationException("Class '" + epServicesContextFactoryClassName + "' cannot be loaded");
                }

                object obj;
                try {
                    obj = TypeHelper.Instantiate(clazz);
                }
                catch (Exception) {
                    throw new ConfigurationException("Class '" + clazz + "' cannot be instantiated");
                }

                epServicesContextFactory = (EPServicesContextFactory) obj;
            }

            EPServicesContext services;
            try {
                services = epServicesContextFactory.CreateServicesContext(this, _configLastProvided);
            }
            catch (EPException ex) {
                throw new ConfigurationException("Failed runtime startup: " + ex.Message, ex);
                //throw;
            }
            catch (Exception ex) {
                throw new ConfigurationException("Failed runtime startup: " + ex.Message, ex);
            }

            // new runtime
            EPEventServiceImpl eventService = epServicesContextFactory.CreateEPRuntime(services, ServiceStatusProvider);

            eventService.InternalEventRouter = services.InternalEventRouter;
            services.InternalEventRouteDest = eventService;

            // set current time, if applicable
            if (startTime != null) {
                services.SchedulingService.Time = startTime.Value;
            }

            // Configure services to use the new runtime
            services.TimerService.Callback = eventService;

            // New services
            EPDeploymentServiceSPI deploymentService = new EPDeploymentServiceImpl(services, this);
            var eventTypeService = new EPEventTypeServiceImpl(services);
            EPContextPartitionService contextPartitionService = new EPContextPartitionServiceImpl(services);
            EPVariableService variableService = new EPVariableServiceImpl(services);
            EPMetricsService metricsService = new EPMetricsServiceImpl(services);
            EPFireAndForgetService fireAndForgetService = new EpFireAndForgetServiceImpl(services, ServiceStatusProvider);
            EPStageServiceSPI stageService = new EPStageServiceImpl(services, ServiceStatusProvider);

            // Build runtime environment
            _runtimeEnvironment = new EPRuntimeEnv(
                services,
                eventService,
                deploymentService,
                eventTypeService,
                contextPartitionService,
                variableService,
                metricsService,
                fireAndForgetService,
                stageService);

            // Stage Recovery
            var stageIterator = services.StageRecoveryService.StagesIterate();
            while (stageIterator.MoveNext()) {
                var entry = stageIterator.Current;

                long currentTimeStage;
                if (services.EpServicesHA.CurrentTimeAsRecovered == null) {
                    currentTimeStage = services.SchedulingService.Time;
                } else if (!services.EpServicesHA.CurrentTimeStageAsRecovered.TryGetValue(entry.Value, out currentTimeStage)) {
                    currentTimeStage = services.SchedulingService.Time;
                }
                
                stageService.RecoverStage(entry.Key, entry.Value, currentTimeStage);
            }

            // Deployment Recovery
            var deploymentIterator = services.DeploymentRecoveryService.Deployments();
            ISet<EventType> protectedVisibleTypes = new LinkedHashSet<EventType>();
            while (deploymentIterator.MoveNext()) {
                var entry = deploymentIterator.Current;
                var deploymentId = entry.Key;

                StatementUserObjectRuntimeOption userObjectResolver = new ProxyStatementUserObjectRuntimeOption {
                    ProcGetUserObject = env => entry.Value.UserObjectsRuntime.Get(env.StatementId)
                };

                StatementNameRuntimeOption statementNameResolver =
                    env => entry.Value.StatementNamesWhenProvidedByAPI.Get(env.StatementId);

                StatementSubstitutionParameterOption substitutionParameterResolver = env => {
                    var param = entry.Value.SubstitutionParameters.Get(env.StatementId);
                    if (param == null) {
                        return;
                    }

                    if (env.SubstitutionParameterNames != null) {
                        foreach (var name in env.SubstitutionParameterNames) {
                            env.SetObject(name.Key, param.Get(name.Value));
                        }
                    }
                    else {
                        for (var i = 0; i < env.SubstitutionParameterTypes.Length; i++) {
                            env.SetObject(i + 1, param.Get(i + 1));
                        }
                    }
                };

                DeploymentInternal deployerResult;
                try {
                    deployerResult = Deployer.DeployRecover(
                        deploymentId,
                        entry.Value.StatementIdFirstStatement,
                        entry.Value.Compiled,
                        statementNameResolver,
                        userObjectResolver,
                        substitutionParameterResolver,
                        null,
                        this);
                }
                catch (EPDeployException ex) {
                    throw new EPException(ex.Message, ex);
                }

                foreach (var eventType in deployerResult.DeploymentTypes.Values) {
                    if (eventType.Metadata.BusModifier == EventTypeBusModifier.BUS ||
                        eventType.Metadata.TypeClass == EventTypeTypeClass.NAMED_WINDOW ||
                        eventType.Metadata.TypeClass == EventTypeTypeClass.STREAM) {
                        protectedVisibleTypes.Add(eventType);
                    }
                }
                
                // handle staged deployments
                var stageUri = services.StageRecoveryService.DeploymentGetStage(deploymentId);
                if (stageUri != null) {
                    stageService.RecoverDeployment(stageUri, deployerResult);
                }
            }

            // Event Handler Recovery
            var eventHandlers = services.ListenerRecoveryService.Listeners;
            while (eventHandlers.MoveNext()) {
                var deployment = eventHandlers.Current;
                var epStatement = services.StatementLifecycleService.GetStatementById(deployment.Key);
                epStatement.RecoveryUpdateEventHandlers(new EPStatementListenerSet(deployment.Value));
            }

            // Filter service init
            ISet<EventType> filterServiceTypes = new LinkedHashSet<EventType>(services.EventTypeRepositoryBus.AllTypes);
            filterServiceTypes.AddAll(protectedVisibleTypes);
            Supplier<ICollection<EventType>> availableTypes = () => filterServiceTypes;
            services.FilterServiceSPI.Init(availableTypes);

            // Schedule service init
            services.SchedulingServiceSPI.Init();
            
            // Stage services init
            stageService.RecoveredStageInitialize(availableTypes);

            // Start clocking
            if (_configLastProvided.Runtime.Threading.IsInternalTimerEnabled) {
                services.TimerService.StartInternalClock();
            }

            // Load and initialize adapter loader classes
            LoadAdapters(services);

            // Initialize extension services
            if (services.RuntimeExtensionServices != null) {
                ((RuntimeExtensionServicesSPI) services.RuntimeExtensionServices).Init(services, eventService, deploymentService, stageService);
            }

            // Start metrics reporting, if any
            if (_configLastProvided.Runtime.MetricsReporting.IsEnableMetricsReporting) {
                services.MetricReportingService.SetContext(services.FilterService, services.SchedulingService, eventService);
            }

            // Start runtimes metrics report
            if (_configLastProvided.Runtime.MetricsReporting.IsRuntimeMetrics) {
                StartEngineMetrics(services, eventService);
            }

            // call initialize listeners
            foreach (var listener in _serviceListeners) {
                try {
                    listener.OnEPRuntimeInitialized(this);
                }
                catch (Exception ex) {
                    Log.Error("Runtime exception caught during an onEPRuntimeInitialized callback:" + ex.Message, ex);
                }
            }
        }
Пример #22
0
        public static PatternStreamSpecCompiled CompilePatternWTags(
            PatternStreamSpecRaw streamSpecRaw,
            ISet<string> eventTypeReferences,
            bool isInsertInto,
            MatchEventSpec tags,
            ISet<string> priorAllTags,
            bool isJoin,
            bool isContextDeclaration,
            bool isOnTrigger,
            int streamNum,
            StatementRawInfo statementRawInfo,
            StatementCompileTimeServices services)
        {
            // validate
            if ((streamSpecRaw.IsSuppressSameEventMatches || streamSpecRaw.IsDiscardPartialsOnMatch) &&
                (isJoin || isContextDeclaration || isOnTrigger)) {
                throw new ExprValidationException(
                    "Discard-partials and suppress-matches is not supported in a joins, context declaration and on-action");
            }

            if (tags == null) {
                tags = new MatchEventSpec();
            }

            var nodeStack = new Stack<EvalForgeNode>();

            // detemine ordered tags
            var allTagNamesOrdered = new LinkedHashSet<string>();
            var filterFactoryNodes = EvalNodeUtil.RecursiveGetChildNodes(
                streamSpecRaw.EvalForgeNode,
                FilterForFilterFactoryNodes.INSTANCE);
            if (priorAllTags != null) {
                allTagNamesOrdered.AddAll(priorAllTags);
            }

            foreach (var filterNode in filterFactoryNodes) {
                var forge = (EvalFilterForgeNode) filterNode;
                int tagNumber;
                if (forge.EventAsName != null) {
                    if (!allTagNamesOrdered.Contains(forge.EventAsName)) {
                        allTagNamesOrdered.Add(forge.EventAsName);
                        tagNumber = allTagNamesOrdered.Count - 1;
                    }
                    else {
                        tagNumber = FindTagNumber(forge.EventAsName, allTagNamesOrdered);
                    }

                    forge.EventAsTagNumber = tagNumber;
                }
            }

            // construct root : assigns factory node ids
            var top = streamSpecRaw.EvalForgeNode;
            var root = new EvalRootForgeNode(top, statementRawInfo.Annotations);
            RecursiveCompile(
                top,
                eventTypeReferences,
                isInsertInto,
                tags,
                nodeStack,
                allTagNamesOrdered,
                streamNum,
                statementRawInfo,
                services);

            var hook = (PatternCompileHook) ImportUtil.GetAnnotationHook(
                statementRawInfo.Annotations,
                HookType.INTERNAL_PATTERNCOMPILE,
                typeof(PatternCompileHook),
                services.ImportServiceCompileTime);
            if (hook != null) {
                hook.Pattern(root);
            }

            return new PatternStreamSpecCompiled(
                root,
                tags.TaggedEventTypes,
                tags.ArrayEventTypes,
                allTagNamesOrdered,
                streamSpecRaw.ViewSpecs,
                streamSpecRaw.OptionalStreamName,
                streamSpecRaw.Options,
                streamSpecRaw.IsSuppressSameEventMatches,
                streamSpecRaw.IsDiscardPartialsOnMatch);
        }