Ejemplo n.º 1
0
        protected override FragmentEventType DoResolveFragmentType(String property)
        {
            if ((!ConfigurationEventTypeXMLDOM.IsAutoFragment) || (ConfigurationEventTypeXMLDOM.IsXPathPropertyExpr))
            {
                return(null);
            }

            Property prop = PropertyParser.ParseAndWalk(property);

            SchemaItem item = prop.GetPropertyTypeSchema(_schemaModelRoot, EventAdapterService);

            if ((item == null) || (!CanFragment(item)))
            {
                return(null);
            }
            var complex = (SchemaElementComplex)item;

            // build name of event type
            String[] atomicProps          = prop.ToPropertyArray();
            String   delimiterDot         = ".";
            var      eventTypeNameBuilder = new StringBuilder(Name);

            foreach (String atomic in atomicProps)
            {
                eventTypeNameBuilder.Append(delimiterDot);
                eventTypeNameBuilder.Append(atomic);
            }
            String eventTypeName = eventTypeNameBuilder.ToString();

            // check if the type exists, use the existing type if found
            EventType existingType = EventAdapterService.GetEventTypeByName(eventTypeName);

            if (existingType != null)
            {
                return(new FragmentEventType(existingType, complex.IsArray, false));
            }

            // add a new type
            var xmlDom = new ConfigurationEventTypeXMLDOM();

            xmlDom.RootElementName                  = "//" + complex.Name; // such the reload of the type can resolve it
            xmlDom.RootElementNamespace             = complex.Namespace;
            xmlDom.IsAutoFragment                   = ConfigurationEventTypeXMLDOM.IsAutoFragment;
            xmlDom.IsEventSenderValidatesRoot       = ConfigurationEventTypeXMLDOM.IsEventSenderValidatesRoot;
            xmlDom.IsXPathPropertyExpr              = ConfigurationEventTypeXMLDOM.IsXPathPropertyExpr;
            xmlDom.IsXPathResolvePropertiesAbsolute = ConfigurationEventTypeXMLDOM.IsXPathResolvePropertiesAbsolute;
            xmlDom.SchemaResource                   = ConfigurationEventTypeXMLDOM.SchemaResource;
            xmlDom.SchemaText            = ConfigurationEventTypeXMLDOM.SchemaText;
            xmlDom.XPathFunctionResolver = ConfigurationEventTypeXMLDOM.XPathFunctionResolver;
            xmlDom.XPathVariableResolver = ConfigurationEventTypeXMLDOM.XPathVariableResolver;
            xmlDom.DefaultNamespace      = ConfigurationEventTypeXMLDOM.DefaultNamespace;
            xmlDom.AddNamespacePrefixes(ConfigurationEventTypeXMLDOM.NamespacePrefixes);

            EventType newType;

            try {
                newType = EventAdapterService.AddXMLDOMType(eventTypeName, xmlDom, _schemaModel, true);
            }
            catch (Exception ex) {
                Log.Error(
                    "Failed to add dynamic event type for fragment of XML schema for property '" + property + "' :" +
                    ex.Message, ex);
                return(null);
            }
            return(new FragmentEventType(newType, complex.IsArray, false));
        }
Ejemplo n.º 2
0
        /// <summary>Resolves a given event name to an event type. </summary>
        /// <param name="eventName">is the name to resolve</param>
        /// <param name="eventAdapterService">for resolving event types</param>
        /// <param name="engineURI">the provider URI</param>
        /// <param name="optionalResolutionURIs">is URIs for resolving the event name against plug-inn event representations, if any</param>
        /// <returns>event type</returns>
        /// <throws>ExprValidationException if the info cannot be resolved</throws>
        public static EventType ResolveType(String engineURI, String eventName, EventAdapterService eventAdapterService, IList <Uri> optionalResolutionURIs)
        {
            var eventType = eventAdapterService.GetEventTypeByName(eventName);

            // may already be known
            if (eventType != null)
            {
                return(eventType);
            }

            var engineURIQualifier = engineURI;

            if (engineURI == null || EPServiceProviderConstants.DEFAULT_ENGINE_URI.Equals(engineURI))
            {
                engineURIQualifier = EPServiceProviderConstants.DEFAULT_ENGINE_URI__QUALIFIER;
            }

            // The event name can be prefixed by the engine URI, i.e. "select * from default.MyEvent"
            if (eventName.StartsWith(engineURIQualifier))
            {
                var indexDot = eventName.IndexOf('.');
                if (indexDot > 0)
                {
                    var eventNameURI       = eventName.Substring(0, indexDot);
                    var eventNameRemainder = eventName.Substring(indexDot + 1);

                    if (engineURIQualifier.Equals(eventNameURI))
                    {
                        eventType = eventAdapterService.GetEventTypeByName(eventNameRemainder);
                    }
                }
            }

            // may now be known
            if (eventType != null)
            {
                return(eventType);
            }

            // The type is not known yet, attempt to add as an object type with the same name
            String message = null;

            try
            {
                eventType = eventAdapterService.AddBeanType(eventName, eventName, true, false, false, false);
            }
            catch (EventAdapterException ex)
            {
                Log.Debug(".resolveType Event type named '" + eventName + "' not resolved as Type event");
                message = "Failed to resolve event type: " + ex.Message;
            }

            // Attempt to use plug-in event types
            try
            {
                eventType = eventAdapterService.AddPlugInEventType(eventName, optionalResolutionURIs, null);
            }
            catch (EventAdapterException)
            {
                Log.Debug(".resolveType Event type named '" + eventName + "' not resolved by plug-in event representations");
                // remains unresolved
            }

            if (eventType == null)
            {
                throw new ExprValidationException(message);
            }
            return(eventType);
        }
Ejemplo n.º 3
0
        public void CreateNewVariable(string optionalContextName, string variableName, string variableType, bool constant, bool array, bool arrayOfPrimitive, object value, EngineImportService engineImportService)
        {
            // Determime the variable type
            var       primitiveType = TypeHelper.GetPrimitiveTypeForName(variableType);
            var       type          = TypeHelper.GetTypeForSimpleName(variableType);
            Type      arrayType     = null;
            EventType eventType     = null;

            if (type == null)
            {
                if (variableType.ToLower() == "object")
                {
                    type = typeof(Object);
                }
                if (type == null)
                {
                    eventType = _eventAdapterService.GetEventTypeByName(variableType);
                    if (eventType != null)
                    {
                        type = eventType.UnderlyingType;
                    }
                }
                if (type == null)
                {
                    try
                    {
                        type = engineImportService.ResolveType(variableType);
                        if (array)
                        {
                            arrayType = TypeHelper.GetArrayType(type.GetBoxedType());
                        }
                    }
                    catch (EngineImportException e)
                    {
                        Log.Debug("Not found '" + type + "': " + e.Message, e);
                        // expected
                    }
                }
                if (type == null)
                {
                    throw new VariableTypeException("Cannot create variable '" + variableName + "', type '" +
                                                    variableType + "' is not a recognized type");
                }
                if (array && eventType != null)
                {
                    throw new VariableTypeException("Cannot create variable '" + variableName + "', type '" +
                                                    variableType + "' cannot be declared as an array type");
                }
            }
            else
            {
                if (array)
                {
                    if (arrayOfPrimitive)
                    {
                        if (primitiveType == null)
                        {
                            throw new VariableTypeException("Cannot create variable '" + variableName + "', type '" +
                                                            variableType + "' is not a primitive type");
                        }
                        arrayType = TypeHelper.GetArrayType(primitiveType);
                    }
                    else
                    {
                        arrayType = TypeHelper.GetArrayType(type.GetBoxedType());
                    }
                }
            }

            if ((eventType == null) && (!type.IsBuiltinDataType()) && (type != typeof(object)) && !type.IsArray && !type.IsEnum)
            {
                if (array)
                {
                    throw new VariableTypeException("Cannot create variable '" + variableName + "', type '" +
                                                    variableType + "' cannot be declared as an array, only scalar types can be array");
                }
                eventType = _eventAdapterService.AddBeanType(type.Name, type, false, false, false);
            }

            if (arrayType != null)
            {
                type = arrayType;
            }

            CreateNewVariable(variableName, optionalContextName, type, eventType, constant, value);
        }
Ejemplo n.º 4
0
        /// <summary>Valiate the revision configuration. </summary>
        /// <param name="revisioneventTypeName">name of revision types</param>
        /// <param name="config">configures revision type</param>
        /// <param name="eventAdapterService">event adapters</param>
        /// <returns>revision specification</returns>
        /// <throws>ConfigurationException if the configs are invalid</throws>
        internal static RevisionSpec ValidateRevision(String revisioneventTypeName, ConfigurationRevisionEventType config, EventAdapterService eventAdapterService)
        {
            if ((config.NameBaseEventTypes == null) || (config.NameBaseEventTypes.Count == 0))
            {
                throw new ConfigurationException("Required base event type name is not set in the configuration for revision event type '" + revisioneventTypeName + "'");
            }

            if (config.NameBaseEventTypes.Count > 1)
            {
                throw new ConfigurationException("Only one base event type name may be added to revision event type '" + revisioneventTypeName + "', multiple base types are not yet supported");
            }

            // get base types
            String    baseeventTypeName = config.NameBaseEventTypes.FirstOrDefault();
            EventType baseEventType     = eventAdapterService.GetEventTypeByName(baseeventTypeName);

            if (baseEventType == null)
            {
                throw new ConfigurationException("Could not locate event type for name '" + baseeventTypeName + "' in the configuration for revision event type '" + revisioneventTypeName + "'");
            }

            // get name types
            var deltaTypes = new EventType[config.NameDeltaEventTypes.Count];
            var deltaNames = new String[config.NameDeltaEventTypes.Count];
            int count      = 0;

            foreach (String deltaName in config.NameDeltaEventTypes)
            {
                EventType deltaEventType = eventAdapterService.GetEventTypeByName(deltaName);
                if (deltaEventType == null)
                {
                    throw new ConfigurationException("Could not locate event type for name '" + deltaName + "' in the configuration for revision event type '" + revisioneventTypeName + "'");
                }
                deltaTypes[count] = deltaEventType;
                deltaNames[count] = deltaName;
                count++;
            }

            // the key properties must be set
            if ((config.KeyPropertyNames == null) || (config.KeyPropertyNames.Length == 0))
            {
                throw new ConfigurationException("Required key properties are not set in the configuration for revision event type '" + revisioneventTypeName + "'");
            }

            // make sure the key properties exist the base type and all delta types
            CheckKeysExist(baseEventType, baseeventTypeName, config.KeyPropertyNames, revisioneventTypeName);
            for (int i = 0; i < deltaTypes.Length; i++)
            {
                CheckKeysExist(deltaTypes[i], deltaNames[i], config.KeyPropertyNames, revisioneventTypeName);
            }

            // key property names shared between base and delta must have the same type
            String[] keyPropertyNames = PropertyUtility.CopyAndSort(config.KeyPropertyNames);
            foreach (String key in keyPropertyNames)
            {
                var typeProperty = baseEventType.GetPropertyType(key);
                foreach (EventType dtype in deltaTypes)
                {
                    var dtypeProperty = dtype.GetPropertyType(key);
                    if ((dtypeProperty != null) && (typeProperty != dtypeProperty))
                    {
                        throw new ConfigurationException("Key property named '" + key + "' does not have the same type for base and delta types of revision event type '" + revisioneventTypeName + "'");
                    }
                }
            }

            // In the "declared" type the change set properties consist of only :
            //   (base event type properties) minus (key properties) minus (properties only on base event type)
            if (config.PropertyRevision == PropertyRevisionEnum.OVERLAY_DECLARED)
            {
                // determine non-key properties: those overridden by any delta, and those simply only present on the base event type
                String[]             nonkeyPropertyNames     = PropertyUtility.UniqueExclusiveSort(baseEventType.PropertyNames, keyPropertyNames);
                ICollection <String> baseEventOnlyProperties = new HashSet <String>();
                ICollection <String> changesetPropertyNames  = new HashSet <String>();
                foreach (String nonKey in nonkeyPropertyNames)
                {
                    var overriddenProperty = false;
                    foreach (EventType type in deltaTypes)
                    {
                        if (type.IsProperty(nonKey))
                        {
                            changesetPropertyNames.Add(nonKey);
                            overriddenProperty = true;
                            break;
                        }
                    }
                    if (!overriddenProperty)
                    {
                        baseEventOnlyProperties.Add(nonKey);
                    }
                }

                String[] changesetProperties        = changesetPropertyNames.ToArray();
                String[] baseEventOnlyPropertyNames = baseEventOnlyProperties.ToArray();

                // verify that all changeset properties match event type
                foreach (String changesetProperty in changesetProperties)
                {
                    var typeProperty = baseEventType.GetPropertyType(changesetProperty);
                    foreach (EventType dtype in deltaTypes)
                    {
                        var dtypeProperty = dtype.GetPropertyType(changesetProperty);
                        if ((dtypeProperty != null) && (typeProperty != dtypeProperty))
                        {
                            throw new ConfigurationException("Property named '" + changesetProperty + "' does not have the same type for base and delta types of revision event type '" + revisioneventTypeName + "'");
                        }
                    }
                }

                return(new RevisionSpec(config.PropertyRevision, baseEventType, deltaTypes, deltaNames, keyPropertyNames, changesetProperties, baseEventOnlyPropertyNames, false, null));
            }
            else
            {
                // In the "exists" type the change set properties consist of all properties: base event properties plus delta types properties
                ICollection <String> allProperties = new HashSet <String>();
                allProperties.AddAll(baseEventType.PropertyNames);
                foreach (EventType deltaType in deltaTypes)
                {
                    allProperties.AddAll(deltaType.PropertyNames);
                }

                String[] allPropertiesArr    = allProperties.ToArray();
                String[] changesetProperties = PropertyUtility.UniqueExclusiveSort(allPropertiesArr, keyPropertyNames);

                // All properties must have the same type, if a property exists for any given type
                bool   hasContributedByDelta = false;
                bool[] contributedByDelta    = new bool[changesetProperties.Length];
                count = 0;
                foreach (String property in changesetProperties)
                {
                    Type basePropertyType = baseEventType.GetPropertyType(property);
                    Type typeTemp         = null;
                    if (basePropertyType != null)
                    {
                        typeTemp = basePropertyType;
                    }
                    else
                    {
                        hasContributedByDelta     = true;
                        contributedByDelta[count] = true;
                    }
                    foreach (EventType dtype in deltaTypes)
                    {
                        Type dtypeProperty = dtype.GetPropertyType(property);
                        if (dtypeProperty != null)
                        {
                            if ((typeTemp != null) && (dtypeProperty != typeTemp))
                            {
                                throw new ConfigurationException("Property named '" + property + "' does not have the same type for base and delta types of revision event type '" + revisioneventTypeName + "'");
                            }
                        }
                        typeTemp = dtypeProperty;
                    }
                    count++;
                }

                // Compile changeset
                return(new RevisionSpec(config.PropertyRevision, baseEventType, deltaTypes, deltaNames, keyPropertyNames, changesetProperties, new String[0], hasContributedByDelta, contributedByDelta));
            }
        }
Ejemplo n.º 5
0
        private DataMap ConstructPropertyTypes(String eventTypeName,
                                               DataMap propertyTypesGiven,
                                               EventAdapterService eventAdapterService)
        {
            var propertyTypes = new Dictionary <string, object>();
            var eventType     = eventAdapterService.GetEventTypeByName(eventTypeName);

            if (eventType == null)
            {
                if (propertyTypesGiven != null)
                {
                    eventAdapterService.AddNestableMapType(eventTypeName, new Dictionary <string, object>(propertyTypesGiven), null, true, true, true, false, false);
                }
                return(propertyTypesGiven);
            }
            if (eventType.UnderlyingType != typeof(DataMap))
            {
                _beanType = eventType.UnderlyingType;
            }
            if (propertyTypesGiven != null && eventType.PropertyNames.Length != propertyTypesGiven.Count)
            {
                // allow this scenario for beans as we may want to bring in a subset of properties
                if (_beanType != null)
                {
                    return(propertyTypesGiven);
                }

                throw new EPException("Event type " + eventTypeName + " has already been declared with a different number of parameters");
            }

            foreach (var property in eventType.PropertyNames)
            {
                Type type;
                try {
                    type = eventType.GetPropertyType(property);
                }
                catch (PropertyAccessException e) {
                    // thrown if trying to access an invalid property on an EventBean
                    throw new EPException(e);
                }

                if (propertyTypesGiven != null && propertyTypesGiven.Get(property) == null)
                {
                    throw new EPException("Event type " + eventTypeName +
                                          "has already been declared with different parameters");
                }
                if (propertyTypesGiven != null && !Equals(propertyTypesGiven.Get(property), type))
                {
                    throw new EPException("Event type " + eventTypeName +
                                          "has already been declared with a different type for property " + property);
                }
                // we can't set read-only properties for bean
                if (eventType.UnderlyingType != typeof(DataMap))
                {
                    var magicType     = MagicType.GetCachedType(_beanType);
                    var magicProperty = magicType.ResolveProperty(property, PropertyResolutionStyle.CASE_SENSITIVE);
                    if (magicProperty == null)
                    {
                        continue;
                    }
                    if (!magicProperty.CanWrite)
                    {
                        if (propertyTypesGiven == null)
                        {
                            continue;
                        }
                        else
                        {
                            throw new EPException("Event type " + eventTypeName + "property " + property +
                                                  " is read only");
                        }
                    }
                }

                propertyTypes[property] = type;
            }

            // flatten nested types
            var flattenPropertyTypes = new Dictionary <string, object>();

            foreach (var prop in propertyTypes)
            {
                var name   = prop.Key;
                var type   = prop.Value;
                var asType = type as Type;

                if ((asType != null) &&
                    (asType.IsGenericStringDictionary()) &&
                    (eventType is MapEventType))
                {
                    var mapEventType = (MapEventType)eventType;
                    var nested       = (DataMap)mapEventType.Types.Get(name);
                    foreach (var nestedProperty in nested.Keys)
                    {
                        flattenPropertyTypes.Put(name + "." + nestedProperty, nested.Get(nestedProperty));
                    }
                }
                else if (asType != null)
                {
                    if (asType.IsNullable())
                    {
                        asType = Nullable.GetUnderlyingType(asType);
                    }

                    if ((!asType.IsPrimitive) && (asType != typeof(string)))
                    {
                        var magicType = MagicType.GetCachedType(asType);
                        foreach (var magicProperty in magicType.GetAllProperties(false))
                        {
                            if (magicProperty.CanWrite)
                            {
                                flattenPropertyTypes[name + '.' + magicProperty.Name] = magicProperty.PropertyType;
                            }
                        }
                    }
                    else
                    {
                        flattenPropertyTypes[name] = type;
                    }
                }
                else
                {
                    flattenPropertyTypes[name] = type;
                }
            }

            return(flattenPropertyTypes);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Makes the property evaluator.
        /// </summary>
        /// <param name="container">The container.</param>
        /// <param name="spec">is the property specification</param>
        /// <param name="sourceEventType">the event type</param>
        /// <param name="optionalSourceStreamName">the source stream name</param>
        /// <param name="eventAdapterService">for event instances</param>
        /// <param name="engineImportService">The engine import service.</param>
        /// <param name="timeProvider">provides time</param>
        /// <param name="variableService">for resolving variables</param>
        /// <param name="scriptingService">The scripting service.</param>
        /// <param name="tableService">The table service.</param>
        /// <param name="engineURI">engine URI</param>
        /// <param name="statementId">The statement identifier.</param>
        /// <param name="statementName">Name of the statement.</param>
        /// <param name="annotations">The annotations.</param>
        /// <param name="assignedTypeNumberStack">The assigned type number stack.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="namedWindowMgmtService">The named window service.</param>
        /// <param name="statementExtensionSvcContext">The statement extension SVC context.</param>
        /// <returns>
        /// property evaluator
        /// </returns>
        public static PropertyEvaluator MakeEvaluator(
            IContainer container,
            PropertyEvalSpec spec,
            EventType sourceEventType,
            string optionalSourceStreamName,
            EventAdapterService eventAdapterService,
            EngineImportService engineImportService,
            TimeProvider timeProvider,
            VariableService variableService,
            ScriptingService scriptingService,
            TableService tableService,
            string engineURI,
            int statementId,
            string statementName,
            Attribute[] annotations,
            ICollection <int> assignedTypeNumberStack,
            ConfigurationInformation configuration,
            NamedWindowMgmtService namedWindowMgmtService,
            StatementExtensionSvcContext statementExtensionSvcContext)
        {
            var length = spec.Atoms.Count;
            var containedEventEvals = new ContainedEventEval[length];
            var fragmentEventTypes  = new FragmentEventType[length];
            var currentEventType    = sourceEventType;
            var whereClauses        = new ExprEvaluator[length];

            var streamEventTypes    = new List <EventType>();
            var streamNames         = new List <string>();
            var streamNameAndNumber = new Dictionary <string, int>().WithNullSupport();
            var expressionTexts     = new List <string>();
            var validateContext     = new ExprEvaluatorContextTimeOnly(container, timeProvider);

            streamEventTypes.Add(sourceEventType);
            streamNames.Add(optionalSourceStreamName);
            streamNameAndNumber.Put(optionalSourceStreamName, 0);
            expressionTexts.Add(sourceEventType.Name);

            IList <SelectClauseElementCompiled> cumulativeSelectClause = new List <SelectClauseElementCompiled>();

            for (var i = 0; i < length; i++)
            {
                var atom = spec.Atoms[i];
                ContainedEventEval containedEventEval = null;
                string             expressionText     = null;
                EventType          streamEventType    = null;
                FragmentEventType  fragmentEventType  = null;

                // Resolve directly as fragment event type if possible
                if (atom.SplitterExpression is ExprIdentNode)
                {
                    var propertyName = ((ExprIdentNode)atom.SplitterExpression).FullUnresolvedName;
                    fragmentEventType = currentEventType.GetFragmentType(propertyName);
                    if (fragmentEventType != null)
                    {
                        var getter = currentEventType.GetGetter(propertyName);
                        if (getter != null)
                        {
                            containedEventEval = new ContainedEventEvalGetter(getter);
                            expressionText     = propertyName;
                            streamEventType    = fragmentEventType.FragmentType;
                        }
                    }
                }

                // evaluate splitter expression
                if (containedEventEval == null)
                {
                    ExprNodeUtility.ValidatePlainExpression(ExprNodeOrigin.CONTAINEDEVENT, atom.SplitterExpression);

                    var availableTypes       = streamEventTypes.ToArray();
                    var availableStreamNames = streamNames.ToArray();
                    var isIStreamOnly        = new bool[streamNames.Count];
                    isIStreamOnly.Fill(true);
                    StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                        availableTypes, availableStreamNames, isIStreamOnly, engineURI, false);
                    var validationContext = new ExprValidationContext(
                        container,
                        streamTypeService,
                        engineImportService,
                        statementExtensionSvcContext, null,
                        timeProvider,
                        variableService,
                        tableService,
                        validateContext,
                        eventAdapterService,
                        statementName,
                        statementId,
                        annotations, null,
                        scriptingService,
                        false, false, true, false, null, false);
                    var validatedExprNode = ExprNodeUtility.GetValidatedSubtree(
                        ExprNodeOrigin.CONTAINEDEVENT, atom.SplitterExpression, validationContext);
                    var evaluator = validatedExprNode.ExprEvaluator;

                    // determine result type
                    if (atom.OptionalResultEventType == null)
                    {
                        throw new ExprValidationException(
                                  "Missing @type(name) declaration providing the event type name of the return type for expression '" +
                                  ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(atom.SplitterExpression) + "'");
                    }
                    streamEventType = eventAdapterService.GetEventTypeByName(atom.OptionalResultEventType);
                    if (streamEventType == null)
                    {
                        throw new ExprValidationException(
                                  "Event type by name '" + atom.OptionalResultEventType + "' could not be found");
                    }

                    var returnType = evaluator.ReturnType;

                    // when the expression returns an array, allow array values to become the column of the single-column event type
                    if (returnType.IsArray &&
                        streamEventType.PropertyNames.Length == 1 &&
                        TypeHelper.IsSubclassOrImplementsInterface(
                            TypeHelper.GetBoxedType(returnType.GetElementType()),
                            TypeHelper.GetBoxedType(streamEventType.GetPropertyType(streamEventType.PropertyNames[0]))))
                    {
                        var writables = eventAdapterService.GetWriteableProperties(streamEventType, false);
                        if (!writables.IsEmpty())
                        {
                            try
                            {
                                EventBeanManufacturer manufacturer = EventAdapterServiceHelper.GetManufacturer(
                                    eventAdapterService, streamEventType,
                                    new WriteablePropertyDescriptor[] { writables.First() },
                                    engineImportService, false,
                                    eventAdapterService.EventAdapterAvroHandler);
                                containedEventEval = new ContainedEventEvalArrayToEvent(evaluator, manufacturer);
                            }
                            catch (EventBeanManufactureException e)
                            {
                                throw new ExprValidationException(
                                          "Event type '" + streamEventType.Name + "' cannot be populated: " + e.Message, e);
                            }
                        }
                        else
                        {
                            throw new ExprValidationException("Event type '" + streamEventType.Name + "' cannot be written to");
                        }
                    }
                    else if (returnType.IsArray() && returnType.GetElementType() == typeof(EventBean))
                    {
                        containedEventEval = new ContainedEventEvalEventBeanArray(evaluator);
                    }
                    else
                    {
                        EventBeanFactory eventBeanFactory = EventAdapterServiceHelper.GetFactoryForType(
                            streamEventType, eventAdapterService);
                        // check expression result type against eventtype expected underlying type
                        if (returnType.IsArray())
                        {
                            if (!TypeHelper.IsSubclassOrImplementsInterface(returnType.GetElementType(), streamEventType.UnderlyingType))
                            {
                                throw new ExprValidationException(
                                          "Event type '" + streamEventType.Name + "' underlying type " +
                                          streamEventType.UnderlyingType.GetCleanName() +
                                          " cannot be assigned a value of type " + returnType.GetCleanName());
                            }
                        }
                        else if (GenericExtensions.IsGenericEnumerable(returnType) || returnType.IsImplementsInterface <IEnumerable>())
                        {
                            // fine, assumed to return the right type
                        }
                        else
                        {
                            throw new ExprValidationException(
                                      "Return type of expression '" +
                                      ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(atom.SplitterExpression) + "' is '" +
                                      returnType.GetCleanName() + "', expected an Iterable or array result");
                        }
                        containedEventEval = new ContainedEventEvalExprNode(evaluator, eventBeanFactory);
                    }
                    expressionText    = ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(validatedExprNode);
                    fragmentEventType = new FragmentEventType(streamEventType, true, false);
                }

                // validate where clause, if any
                streamEventTypes.Add(streamEventType);
                streamNames.Add(atom.OptionalAsName);
                streamNameAndNumber.Put(atom.OptionalAsName, i + 1);
                expressionTexts.Add(expressionText);

                if (atom.OptionalWhereClause != null)
                {
                    var whereTypes       = streamEventTypes.ToArray();
                    var whereStreamNames = streamNames.ToArray();
                    var isIStreamOnly    = new bool[streamNames.Count];
                    isIStreamOnly.Fill(true);
                    StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                        whereTypes, whereStreamNames, isIStreamOnly, engineURI, false);
                    var validationContext = new ExprValidationContext(
                        container,
                        streamTypeService,
                        engineImportService,
                        statementExtensionSvcContext, null,
                        timeProvider,
                        variableService,
                        tableService,
                        validateContext,
                        eventAdapterService,
                        statementName,
                        statementId,
                        annotations, null,
                        scriptingService,
                        false, false, true, false, null, false);
                    whereClauses[i] =
                        ExprNodeUtility.GetValidatedSubtree(
                            ExprNodeOrigin.CONTAINEDEVENT, atom.OptionalWhereClause, validationContext).ExprEvaluator;
                }

                // validate select clause
                if (atom.OptionalSelectClause != null)
                {
                    var whereTypes       = streamEventTypes.ToArray();
                    var whereStreamNames = streamNames.ToArray();
                    var isIStreamOnly    = new bool[streamNames.Count];
                    isIStreamOnly.Fill(true);
                    StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                        whereTypes, whereStreamNames, isIStreamOnly, engineURI, false);
                    var validationContext = new ExprValidationContext(
                        container,
                        streamTypeService,
                        engineImportService,
                        statementExtensionSvcContext, null,
                        timeProvider,
                        variableService,
                        tableService,
                        validateContext,
                        eventAdapterService,
                        statementName,
                        statementId,
                        annotations, null,
                        scriptingService,
                        false, false, true, false, null, false);

                    foreach (var raw in atom.OptionalSelectClause.SelectExprList)
                    {
                        if (raw is SelectClauseStreamRawSpec)
                        {
                            var rawStreamSpec = (SelectClauseStreamRawSpec)raw;
                            if (!streamNames.Contains(rawStreamSpec.StreamName))
                            {
                                throw new ExprValidationException(
                                          "Property rename '" + rawStreamSpec.StreamName + "' not found in path");
                            }
                            var streamSpec = new SelectClauseStreamCompiledSpec(
                                rawStreamSpec.StreamName, rawStreamSpec.OptionalAsName);
                            int streamNumber = streamNameAndNumber.Get(rawStreamSpec.StreamName);
                            streamSpec.StreamNumber = streamNumber;
                            cumulativeSelectClause.Add(streamSpec);
                        }
                        else if (raw is SelectClauseExprRawSpec)
                        {
                            var exprSpec     = (SelectClauseExprRawSpec)raw;
                            var exprCompiled = ExprNodeUtility.GetValidatedSubtree(
                                ExprNodeOrigin.CONTAINEDEVENT, exprSpec.SelectExpression, validationContext);
                            var resultName = exprSpec.OptionalAsName;
                            if (resultName == null)
                            {
                                resultName = ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(exprCompiled);
                            }
                            cumulativeSelectClause.Add(
                                new SelectClauseExprCompiledSpec(
                                    exprCompiled, resultName, exprSpec.OptionalAsName, exprSpec.IsEvents));

                            var isMinimal = ExprNodeUtility.IsMinimalExpression(exprCompiled);
                            if (isMinimal != null)
                            {
                                throw new ExprValidationException(
                                          "Expression in a property-selection may not utilize " + isMinimal);
                            }
                        }
                        else if (raw is SelectClauseElementWildcard)
                        {
                            // wildcards are stream selects: we assign a stream name (any) and add a stream wildcard select
                            var streamNameAtom = atom.OptionalAsName;
                            if (streamNameAtom == null)
                            {
                                streamNameAtom = UuidGenerator.Generate();
                            }

                            var streamSpec   = new SelectClauseStreamCompiledSpec(streamNameAtom, atom.OptionalAsName);
                            var streamNumber = i + 1;
                            streamSpec.StreamNumber = streamNumber;
                            cumulativeSelectClause.Add(streamSpec);
                        }
                        else
                        {
                            throw new IllegalStateException("Unknown select clause item:" + raw);
                        }
                    }
                }

                currentEventType       = fragmentEventType.FragmentType;
                fragmentEventTypes[i]  = fragmentEventType;
                containedEventEvals[i] = containedEventEval;
            }

            if (cumulativeSelectClause.IsEmpty())
            {
                if (length == 1)
                {
                    return(new PropertyEvaluatorSimple(
                               containedEventEvals[0], fragmentEventTypes[0], whereClauses[0], expressionTexts[0]));
                }
                else
                {
                    return(new PropertyEvaluatorNested(containedEventEvals, fragmentEventTypes, whereClauses, expressionTexts));
                }
            }
            else
            {
                var accumulative = new PropertyEvaluatorAccumulative(
                    containedEventEvals, fragmentEventTypes, whereClauses, expressionTexts);

                var whereTypes       = streamEventTypes.ToArray();
                var whereStreamNames = streamNames.ToArray();
                var isIStreamOnly    = new bool[streamNames.Count];
                isIStreamOnly.Fill(true);
                StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                    whereTypes, whereStreamNames, isIStreamOnly, engineURI, false);

                var cumulativeSelectArr = cumulativeSelectClause.ToArray();
                var selectExpr          = SelectExprProcessorFactory.GetProcessor(
                    container,
                    assignedTypeNumberStack,
                    cumulativeSelectArr, false, null, null, null, streamTypeService,
                    eventAdapterService, null, null, null, engineImportService, validateContext, variableService,
                    scriptingService,
                    tableService, timeProvider, engineURI, statementId, statementName, annotations, null, configuration, null,
                    namedWindowMgmtService, null, null, statementExtensionSvcContext);
                return(new PropertyEvaluatorSelect(selectExpr, accumulative));
            }
        }
        /// <summary>
        /// Ctor.
        /// </summary>
        /// <param name="assignedTypeNumberStack">The assigned type number stack.</param>
        /// <param name="statementId">The statement identifier.</param>
        /// <param name="streamNames">name of each stream</param>
        /// <param name="streamTypes">type of each stream</param>
        /// <param name="eventAdapterService">service for generating events and handling event types</param>
        /// <param name="insertIntoDesc">describes the insert-into clause</param>
        /// <param name="selectExprEventTypeRegistry">registry for event type to statements</param>
        /// <param name="methodResolutionService">for resolving writable properties</param>
        /// <param name="annotations">The annotations.</param>
        /// <param name="configuration">The configuration.</param>
        /// <param name="tableService">The table service.</param>
        /// <returns></returns>
        /// <exception cref="System.ArgumentException">Stream names and types parameter length is invalid, expected use of this class is for join statements</exception>
        /// <exception cref="ExprValidationException"></exception>
        /// <throws>com.espertech.esper.epl.expression.core.ExprValidationException if the expression validation failed</throws>
        public static SelectExprProcessor Create(
            ICollection <int> assignedTypeNumberStack,
            string statementId,
            string[] streamNames,
            EventType[] streamTypes,
            EventAdapterService eventAdapterService,
            InsertIntoDesc insertIntoDesc,
            SelectExprEventTypeRegistry selectExprEventTypeRegistry,
            MethodResolutionService methodResolutionService,
            Attribute[] annotations,
            ConfigurationInformation configuration,
            TableService tableService)
        {
            if ((streamNames.Length < 2) || (streamTypes.Length < 2) || (streamNames.Length != streamTypes.Length))
            {
                throw new ArgumentException(
                          "Stream names and types parameter length is invalid, expected use of this class is for join statements");
            }

            // Create EventType of result join events
            var eventTypeMap       = new LinkedHashMap <string, object>();
            var streamTypesWTables = new EventType[streamTypes.Length];
            var hasTables          = false;

            for (var i = 0; i < streamTypes.Length; i++)
            {
                streamTypesWTables[i] = streamTypes[i];
                var tableName = TableServiceUtil.GetTableNameFromEventType(streamTypesWTables[i]);
                if (tableName != null)
                {
                    hasTables             = true;
                    streamTypesWTables[i] = tableService.GetTableMetadata(tableName).PublicEventType;
                }
                eventTypeMap.Put(streamNames[i], streamTypesWTables[i]);
            }

            // If we have a name for this type, add it
            var       useMap = EventRepresentationUtil.IsMap(annotations, configuration, AssignedType.NONE);
            EventType resultEventType;

            SelectExprProcessor processor = null;

            if (insertIntoDesc != null)
            {
                EventType existingType = eventAdapterService.GetEventTypeByName(insertIntoDesc.EventTypeName);
                if (existingType != null)
                {
                    processor = SelectExprInsertEventBeanFactory.GetInsertUnderlyingJoinWildcard(
                        eventAdapterService, existingType, streamNames, streamTypesWTables,
                        methodResolutionService.EngineImportService);
                }
            }

            if (processor == null)
            {
                if (insertIntoDesc != null)
                {
                    try
                    {
                        if (useMap)
                        {
                            resultEventType = eventAdapterService.AddNestableMapType(
                                insertIntoDesc.EventTypeName, eventTypeMap, null, false, false, false, false, true);
                        }
                        else
                        {
                            resultEventType = eventAdapterService.AddNestableObjectArrayType(
                                insertIntoDesc.EventTypeName, eventTypeMap, null, false, false, false, false, true, false, null);
                        }
                        selectExprEventTypeRegistry.Add(resultEventType);
                    }
                    catch (EventAdapterException ex)
                    {
                        throw new ExprValidationException(ex.Message);
                    }
                }
                else
                {
                    if (useMap)
                    {
                        resultEventType =
                            eventAdapterService.CreateAnonymousMapType(
                                statementId + "_join_" + CollectionUtil.ToString(assignedTypeNumberStack, "_"), eventTypeMap);
                    }
                    else
                    {
                        resultEventType =
                            eventAdapterService.CreateAnonymousObjectArrayType(
                                statementId + "_join_" + CollectionUtil.ToString(assignedTypeNumberStack, "_"), eventTypeMap);
                    }
                }
                if (resultEventType is ObjectArrayEventType)
                {
                    processor = new SelectExprJoinWildcardProcessorObjectArray(
                        streamNames, resultEventType, eventAdapterService);
                }
                else
                {
                    processor = new SelectExprJoinWildcardProcessorMap(streamNames, resultEventType, eventAdapterService);
                }
            }

            if (!hasTables)
            {
                return(processor);
            }
            return(new SelectExprJoinWildcardProcessorTableRows(streamTypes, processor, tableService));
        }
 public bool IsEventTypeExists(String eventTypeName)
 {
     return(_eventAdapterService.GetEventTypeByName(eventTypeName) != null);
 }
Ejemplo n.º 9
0
        public MapEventPropertyGetter GetGetterMap(Map optionalMapPropTypes, EventAdapterService eventAdapterService)
        {
            var getters           = new List <EventPropertyGetter>();
            var currentDictionary = optionalMapPropTypes;

            int count = 0;

            for (var it = Properties.EnumerateWithLookahead(); it.HasNext();)
            {
                count++;
                Property property = it.Next();

                // manufacture a getter for getting the item out of the map
                EventPropertyGetter getter = property.GetGetterMap(currentDictionary, eventAdapterService);
                if (getter == null)
                {
                    return(null);
                }
                getters.Add(getter);

                var @base        = (PropertyBase)property;
                var propertyName = @base.PropertyNameAtomic;

                // For the next property if there is one, check how to property type is defined
                if (!it.HasNext())
                {
                    continue;
                }

                if (currentDictionary != null)
                {
                    // check the type that this property will return
                    Object propertyReturnType = currentDictionary.Get(propertyName);

                    if (propertyReturnType == null)
                    {
                        currentDictionary = null;
                    }
                    if (propertyReturnType != null)
                    {
                        if (propertyReturnType is Map)
                        {
                            currentDictionary = (Map)propertyReturnType;
                        }
                        else if (ReferenceEquals(propertyReturnType, typeof(Map)))
                        {
                            currentDictionary = null;
                        }
                        else if (propertyReturnType is String)
                        {
                            String nestedName = propertyReturnType.ToString();
                            bool   isArray    = EventTypeUtility.IsPropertyArray(nestedName);
                            if (isArray)
                            {
                                nestedName = EventTypeUtility.GetPropertyRemoveArray(nestedName);
                            }

                            EventType innerType = eventAdapterService.GetEventTypeByName(nestedName);
                            if (innerType == null)
                            {
                                return(null);
                            }

                            String remainingProps           = ToPropertyEPL(Properties, count);
                            EventPropertyGetter getterInner = innerType.GetGetter(remainingProps);
                            if (getterInner == null)
                            {
                                return(null);
                            }

                            getters.Add(getterInner);
                            break; // the single getter handles the rest
                        }
                        else if (propertyReturnType is EventType)
                        {
                            var innerType      = (EventType)propertyReturnType;
                            var remainingProps = ToPropertyEPL(Properties, count);
                            var getterInner    = innerType.GetGetter(remainingProps);
                            if (getterInner == null)
                            {
                                return(null);
                            }

                            getters.Add(getterInner);
                            break; // the single getter handles the rest
                        }
                        else
                        {
                            // treat the return type of the map property as an object
                            var returnType = (Type)propertyReturnType;
                            if (!returnType.IsArray)
                            {
                                BeanEventType beanType =
                                    eventAdapterService.BeanEventTypeFactory.CreateBeanType(returnType.Name, returnType,
                                                                                            false, false, false);
                                String remainingProps           = ToPropertyEPL(Properties, count);
                                EventPropertyGetter getterInner = beanType.GetGetter(remainingProps);
                                if (getterInner == null)
                                {
                                    return(null);
                                }
                                getters.Add(getterInner);
                                break; // the single getter handles the rest
                            }
                            else
                            {
                                Type          componentType = returnType.GetElementType();
                                BeanEventType beanType      = eventAdapterService.BeanEventTypeFactory.CreateBeanType(
                                    componentType.Name, componentType, false, false, false);
                                String remainingProps           = ToPropertyEPL(Properties, count);
                                EventPropertyGetter getterInner = beanType.GetGetter(remainingProps);
                                if (getterInner == null)
                                {
                                    return(null);
                                }
                                getters.Add(getterInner);
                                break; // the single pono getter handles the rest
                            }
                        }
                    }
                }
            }

            var hasNonmapGetters = false;

            for (int i = 0; i < getters.Count; i++)
            {
                if (!(getters[i] is MapEventPropertyGetter))
                {
                    hasNonmapGetters = true;
                }
            }
            if (!hasNonmapGetters)
            {
                return(new MapNestedPropertyGetterMapOnly(getters, eventAdapterService));
            }
            else
            {
                return(new MapNestedPropertyGetterMixedType(getters, eventAdapterService));
            }
        }
Ejemplo n.º 10
0
        public Type GetPropertyTypeMap(Map optionalMapPropTypes, EventAdapterService eventAdapterService)
        {
            Map currentDictionary = optionalMapPropTypes;

            int count = 0;

            for (var it = Properties.EnumerateWithLookahead(); it.HasNext();)
            {
                count++;
                var property     = it.Next();
                var propertyBase = (PropertyBase)property;
                var propertyName = propertyBase.PropertyNameAtomic;

                Object nestedType = null;
                if (currentDictionary != null)
                {
                    nestedType = currentDictionary.Get(propertyName);
                }

                if (nestedType == null)
                {
                    if (property is DynamicProperty)
                    {
                        return(typeof(Object));
                    }
                    else
                    {
                        return(null);
                    }
                }

                if (!it.HasNext())
                {
                    if (nestedType is Type)
                    {
                        return(((Type)nestedType).GetBoxedType());
                    }
                    if (nestedType is Map)
                    {
                        return(typeof(Map));
                    }
                }

                if (ReferenceEquals(nestedType, typeof(Map)))
                {
                    return(typeof(Object));
                }

                if (nestedType is Type)
                {
                    Type pocoType = (Type)nestedType;
                    if (!pocoType.IsArray)
                    {
                        BeanEventType beanType       = eventAdapterService.BeanEventTypeFactory.CreateBeanType(pocoType.Name, pocoType, false, false, false);
                        String        remainingProps = ToPropertyEPL(Properties, count);
                        return(beanType.GetPropertyType(remainingProps).GetBoxedType());
                    }
                    else if (property is IndexedProperty)
                    {
                        Type          componentType  = pocoType.GetElementType();
                        BeanEventType beanType       = eventAdapterService.BeanEventTypeFactory.CreateBeanType(componentType.Name, componentType, false, false, false);
                        String        remainingProps = ToPropertyEPL(Properties, count);
                        return(beanType.GetPropertyType(remainingProps).GetBoxedType());
                    }
                }

                if (nestedType is String)       // property type is the name of a map event type
                {
                    String nestedName = nestedType.ToString();
                    bool   isArray    = EventTypeUtility.IsPropertyArray(nestedName);
                    if (isArray)
                    {
                        nestedName = EventTypeUtility.GetPropertyRemoveArray(nestedName);
                    }

                    EventType innerType = eventAdapterService.GetEventTypeByName(nestedName);
                    if (innerType == null)
                    {
                        return(null);
                    }

                    String remainingProps = ToPropertyEPL(Properties, count);
                    return(innerType.GetPropertyType(remainingProps).GetBoxedType());
                }
                else if (nestedType is EventType)       // property type is the name of a map event type
                {
                    var innerType      = (EventType)nestedType;
                    var remainingProps = ToPropertyEPL(Properties, count);
                    return(innerType.GetPropertyType(remainingProps).GetBoxedType());
                }
                else
                {
                    if (!(nestedType is Map))
                    {
                        String message = "Nestable map type configuration encountered an unexpected value type of '"
                                         + nestedType.GetType() + " for property '" + propertyName + "', expected Class, typeof(Map) or IDictionary<String, Object> as value type";
                        throw new PropertyAccessException(message);
                    }
                }

                currentDictionary = (Map)nestedType;
            }
            throw new IllegalStateException("Unexpected end of nested property");
        }
Ejemplo n.º 11
0
        public FragmentEventType GetFragmentType(String propertyName)
        {
            var item = _propertyItems.Get(propertyName);

            if (item != null) // may contain null values
            {
                return(item.FragmentEventType);
            }

            // see if this is a nested property
            var index = ASTUtil.UnescapedIndexOfDot(propertyName);

            if (index == -1)
            {
                // dynamic simple property
                if (propertyName.EndsWith("?"))
                {
                    return(null);
                }

                // parse, can be an indexed property
                var property = PropertyParser.ParseAndWalkLaxToSimple(propertyName);
                if (property is IndexedProperty)
                {
                    var indexedProp = (IndexedProperty)property;
                    var type        = NestableTypes.Get(indexedProp.PropertyNameAtomic);
                    if (type == null)
                    {
                        return(null);
                    }
                    else if (type is EventType[])
                    {
                        var eventType = ((EventType[])type)[0];
                        return(new FragmentEventType(eventType, false, false));
                    }
                    else if (type is String)
                    {
                        var propTypeName = type.ToString();
                        var isArray      = EventTypeUtility.IsPropertyArray(propTypeName);
                        if (!isArray)
                        {
                            return(null);
                        }
                        propTypeName = EventTypeUtility.GetPropertyRemoveArray(propTypeName);
                        EventType innerType = _eventAdapterService.GetEventTypeByName(propTypeName);
                        if (!(innerType is BaseNestableEventType))
                        {
                            return(null);
                        }
                        return(new FragmentEventType(innerType, false, false)); // false since an index is present
                    }
                    if (!(type is Type))
                    {
                        return(null);
                    }
                    if (!((Type)type).IsArray)
                    {
                        return(null);
                    }
                    // its an array
                    return(EventBeanUtility.CreateNativeFragmentType(((Type)type).GetElementType(), null, _eventAdapterService));
                }
                else if (property is MappedProperty)
                {
                    // No type information available for the inner event
                    return(null);
                }
                else
                {
                    return(null);
                }
            }

            // Map event types allow 2 types of properties inside:
            //   - a property that is a object is interrogated via bean property getters and BeanEventType
            //   - a property that is a Map itself is interrogated via map property getters
            // The property getters therefore act on

            // Take apart the nested property into a map key and a nested value class property name
            var propertyMap    = ASTUtil.UnescapeDot(propertyName.Substring(0, index));
            var propertyNested = propertyName.Substring(index + 1);

            // If the property is dynamic, it cannot be a fragment
            if (propertyMap.EndsWith("?"))
            {
                return(null);
            }

            var nestedType = NestableTypes.Get(propertyMap);

            if (nestedType == null)
            {
                // parse, can be an indexed property
                var property = PropertyParser.ParseAndWalkLaxToSimple(propertyMap);
                if (property is IndexedProperty)
                {
                    var indexedProp = (IndexedProperty)property;
                    var type        = NestableTypes.Get(indexedProp.PropertyNameAtomic);
                    if (type == null)
                    {
                        return(null);
                    }
                    // handle map-in-map case
                    if (type is String)
                    {
                        var propTypeName = type.ToString();
                        var isArray      = EventTypeUtility.IsPropertyArray(propTypeName);
                        if (isArray)
                        {
                            propTypeName = EventTypeUtility.GetPropertyRemoveArray(propTypeName);
                        }
                        EventType innerType = _eventAdapterService.GetEventTypeByName(propTypeName);
                        if (!(innerType is BaseNestableEventType))
                        {
                            return(null);
                        }
                        return(innerType.GetFragmentType(propertyNested));
                    }
                    // handle eventtype[] in map
                    else if (type is EventType[])
                    {
                        var innerType = ((EventType[])type)[0];
                        return(innerType.GetFragmentType(propertyNested));
                    }
                    // handle array class in map case
                    else
                    {
                        if (!(type is Type))
                        {
                            return(null);
                        }
                        if (!((Type)type).IsArray)
                        {
                            return(null);
                        }
                        var fragmentParent = EventBeanUtility.CreateNativeFragmentType(
                            (Type)type, null, _eventAdapterService);
                        if (fragmentParent == null)
                        {
                            return(null);
                        }
                        return(fragmentParent.FragmentType.GetFragmentType(propertyNested));
                    }
                }
                else if (property is MappedProperty)
                {
                    // No type information available for the property's map value
                    return(null);
                }
                else
                {
                    return(null);
                }
            }

            // If there is a map value in the map, return the Object value if this is a dynamic property
            if (ReferenceEquals(nestedType, typeof(IDictionary <string, object>)))
            {
                return(null);
            }
            else if (nestedType is IDictionary <string, object> )
            {
                return(null);
            }
            else if (nestedType is Type)
            {
                var simpleClass = (Type)nestedType;
                if (!TypeHelper.IsFragmentableType(simpleClass))
                {
                    return(null);
                }
                EventType nestedEventType =
                    _eventAdapterService.BeanEventTypeFactory.CreateBeanTypeDefaultName(simpleClass);
                return(nestedEventType.GetFragmentType(propertyNested));
            }
            else if (nestedType is EventType)
            {
                var innerType = (EventType)nestedType;
                return(innerType.GetFragmentType(propertyNested));
            }
            else if (nestedType is EventType[])
            {
                var innerType = (EventType[])nestedType;
                return(innerType[0].GetFragmentType(propertyNested));
            }
            else if (nestedType is String)
            {
                var nestedName = nestedType.ToString();
                var isArray    = EventTypeUtility.IsPropertyArray(nestedName);
                if (isArray)
                {
                    nestedName = EventTypeUtility.GetPropertyRemoveArray(nestedName);
                }
                var innerType = _eventAdapterService.GetEventTypeByName(nestedName);
                if (!(innerType is BaseNestableEventType))
                {
                    return(null);
                }
                return(innerType.GetFragmentType(propertyNested));
            }
            else
            {
                var message = "Nestable map type configuration encountered an unexpected value type of '"
                              + nestedType.GetType() + " for property '" + propertyName +
                              "', expected Class, typeof(Map) or IDictionary<String, Object> as value type";
                throw new PropertyAccessException(message);
            }
        }
Ejemplo n.º 12
0
        internal static void AssembleField(
            string propertyName,
            Object propertyType,
            JArray assembler,
            Attribute[] annotations,
            ConfigurationEngineDefaults.AvroSettings avroSettings,
            EventAdapterService eventAdapterService,
            string statementName,
            string engineURI,
            TypeRepresentationMapper optionalMapper)
        {
            if (propertyName.Contains("."))
            {
                throw new EPException(
                    "Invalid property name as Avro does not allow dot '.' in field names (property '" + propertyName +
                    "')");
            }

            Schema schema = GetAnnotationSchema(propertyName, annotations);
            if (schema != null)
            {
                assembler.Add(TypeBuilder.Field(propertyName, schema));
                // assembler.Name(propertyName).Type(schema).NoDefault();
                return;
            }

            if (optionalMapper != null && propertyType is Type)
            {
                var result = (Schema) optionalMapper.Map(
                    new TypeRepresentationMapperContext(
                        (Type) propertyType, propertyName, statementName, engineURI));
                if (result != null)
                {
                    assembler.Add(TypeBuilder.Field(propertyName, result));
                    // assembler.Name(propertyName).Type(result).NoDefault();
                    return;
                }
            }

            if (propertyType == null)
            {
                assembler.Add(TypeBuilder.Field(propertyName, TypeBuilder.NullType()));
                // assembler.Name(propertyName).Type("null");
            }
            else if (propertyType is string)
            {
                string propertyTypeName = propertyType.ToString();
                bool isArray = EventTypeUtility.IsPropertyArray(propertyTypeName);
                if (isArray)
                {
                    propertyTypeName = EventTypeUtility.GetPropertyRemoveArray(propertyTypeName);
                }

                // Add EventType itself as a property
                EventType eventType = eventAdapterService.GetEventTypeByName(propertyTypeName);
                if (!(eventType is AvroEventType))
                {
                    throw new EPException(
                        "Type definition encountered an unexpected property type name '"
                        + propertyType + "' for property '" + propertyName +
                        "', expected the name of a previously-declared Avro type");
                }
                schema = ((AvroEventType) eventType).SchemaAvro;

                if (!isArray)
                {
                    assembler.Add(TypeBuilder.Field(propertyName, schema));
                }
                else
                {
                    assembler.Add(TypeBuilder.Field(propertyName, TypeBuilder.Array(schema)));
                }
            }
            else if (propertyType is EventType)
            {
                var eventType = (EventType) propertyType;
                CheckCompatibleType(eventType);
                if (eventType is AvroEventType)
                {
                    schema = ((AvroEventType) eventType).SchemaAvro;
                    assembler.Add(TypeBuilder.Field(propertyName, schema));
                }
                else if (eventType is MapEventType)
                {
                    var mapEventType = (MapEventType) eventType;
                    var nestedSchema = AssembleNestedSchema(
                        mapEventType, avroSettings, annotations, eventAdapterService, statementName, engineURI,
                        optionalMapper);
                    assembler.Add(TypeBuilder.Field(propertyName, nestedSchema));
                }
                else
                {
                    throw new IllegalStateException("Unrecognized event type " + eventType);
                }
            }
            else if (propertyType is EventType[])
            {
                EventType eventType = ((EventType[]) propertyType)[0];
                CheckCompatibleType(eventType);
                if (eventType is AvroEventType)
                {
                    schema = ((AvroEventType) eventType).SchemaAvro;
                    assembler.Add(TypeBuilder.Field(propertyName, TypeBuilder.Array(schema)));
                }
                else if (eventType is MapEventType)
                {
                    var mapEventType = (MapEventType) eventType;
                    var nestedSchema = AssembleNestedSchema(
                        mapEventType, avroSettings, annotations, eventAdapterService, statementName, engineURI,
                        optionalMapper);

                    assembler.Add(TypeBuilder.Field(propertyName, TypeBuilder.Array(nestedSchema)));
                }
                else
                {
                    throw new IllegalStateException("Unrecognized event type " + eventType);
                }
            }
            else if (propertyType is Type)
            {
                var propertyClass = (Type) propertyType;
                var propertyClassBoxed = propertyClass.GetBoxedType();
                bool nullable = propertyClass == propertyClassBoxed;
                bool preferNonNull = avroSettings.IsEnableSchemaDefaultNonNull;
                if (propertyClassBoxed == typeof (bool?))
                {
                    AssemblePrimitive(nullable, REQ_BOOLEAN, OPT_BOOLEAN, assembler, propertyName, preferNonNull);
                }
                else if (propertyClassBoxed == typeof (int?) || propertyClassBoxed == typeof (byte?))
                {
                    AssemblePrimitive(nullable, REQ_INT, OPT_INT, assembler, propertyName, preferNonNull);
                }
                else if (propertyClassBoxed == typeof (long?))
                {
                    AssemblePrimitive(nullable, REQ_LONG, OPT_LONG, assembler, propertyName, preferNonNull);
                }
                else if (propertyClassBoxed == typeof (float?))
                {
                    AssemblePrimitive(nullable, REQ_FLOAT, OPT_FLOAT, assembler, propertyName, preferNonNull);
                }
                else if (propertyClassBoxed == typeof (double?))
                {
                    AssemblePrimitive(nullable, REQ_DOUBLE, OPT_DOUBLE, assembler, propertyName, preferNonNull);
                }
                else if (propertyClass == typeof (string))
                {
                    if (avroSettings.IsEnableNativeString)
                    {
                        if (preferNonNull)
                        {
                            assembler.Add(
                                TypeBuilder.Field(propertyName, 
                                    TypeBuilder.Primitive("string",
                                        TypeBuilder.Property(AvroConstant.PROP_STRING_KEY, AvroConstant.PROP_STRING_VALUE))));
                        }
                        else
                        {
                            assembler.Add(
                                TypeBuilder.Field(
                                    propertyName,
                                    TypeBuilder.Union(
                                        TypeBuilder.NullType(),
                                        TypeBuilder.StringType(
                                            TypeBuilder.Property(
                                                AvroConstant.PROP_STRING_KEY, AvroConstant.PROP_STRING_VALUE)))));
                        }
                    }
                    else
                    {
                        AssemblePrimitive(nullable, REQ_STRING, OPT_STRING, assembler, propertyName, preferNonNull);
                    }
                }
                else if (propertyClass == typeof (byte[]))
                {
                    if (preferNonNull)
                    {
                        assembler.Add(TypeBuilder.RequiredBytes(propertyName));
                    }
                    else
                    {
                        assembler.Add(TypeBuilder.Field(propertyName, TypeBuilder.Union(
                            TypeBuilder.NullType(), TypeBuilder.BytesType())));
                    }
                }
                else if (propertyClass.IsArray)
                {
                    var componentType = propertyClass.GetElementType();
                    var  componentTypeBoxed = componentType.GetBoxedType();
                    var nullableElements = componentType == componentTypeBoxed;

                    if (componentTypeBoxed == typeof (bool?))
                    {
                        AssembleArray(
                            nullableElements, ARRAY_OF_REQ_BOOLEAN, ARRAY_OF_OPT_BOOLEAN, assembler, propertyName, preferNonNull);
                    }
                    else if (componentTypeBoxed == typeof (int?))
                    {
                        AssembleArray(
                            nullableElements, ARRAY_OF_REQ_INT, ARRAY_OF_OPT_INT, assembler, propertyName, preferNonNull);
                    }
                    else if (componentTypeBoxed == typeof (long?))
                    {
                        AssembleArray(
                            nullableElements, ARRAY_OF_REQ_LONG, ARRAY_OF_OPT_LONG, assembler, propertyName, preferNonNull);
                    }
                    else if (componentTypeBoxed == typeof (float?))
                    {
                        AssembleArray(
                            nullableElements, ARRAY_OF_REQ_FLOAT, ARRAY_OF_OPT_FLOAT, assembler, propertyName, preferNonNull);
                    }
                    else if (componentTypeBoxed == typeof(double?))
                    {
                        AssembleArray(
                            nullableElements, ARRAY_OF_REQ_DOUBLE, ARRAY_OF_OPT_DOUBLE, assembler, propertyName, preferNonNull);
                    }
                    else if (componentTypeBoxed == typeof (byte?))
                    {
                        AssembleArray(
                            nullableElements, ARRAY_OF_REQ_INT, ARRAY_OF_OPT_INT, assembler, propertyName, preferNonNull);
                    }
                    else if (propertyClass == typeof (string[]))
                    {
                        JObject array;
                        if (avroSettings.IsEnableNativeString)
                        {
                            array = TypeBuilder.Array(TypeBuilder.StringType(TypeBuilder.Property(
                                AvroConstant.PROP_STRING_KEY, AvroConstant.PROP_STRING_VALUE)));
                        }
                        else
                        {
                            array = TypeBuilder.Array(TypeBuilder.StringType());
                        }

                        if (preferNonNull)
                        {
                            assembler.Add(TypeBuilder.Field(propertyName, array));
                        }
                        else
                        {
                            assembler.Add(TypeBuilder.Field(propertyName, TypeBuilder.Union(
                                TypeBuilder.NullType(), array)));
                        }
                    }
                    else if (propertyClass.CanUnwrap<object>())
                    {

                    }
                    else
                    {
                        throw MakeEPException(propertyName, propertyType);
                    }
                }
                else if (propertyClass.IsGenericDictionary())
                {
                    JToken value;
                    if (avroSettings.IsEnableNativeString)
                    {
                        value = TypeBuilder.StringType(
                            TypeBuilder.Property(AvroConstant.PROP_STRING_KEY, AvroConstant.PROP_STRING_VALUE));
                    }
                    else
                    {
                        value = TypeBuilder.StringType();
                    }

                    if (preferNonNull)
                    {
                        assembler.Add(TypeBuilder.Field(propertyName, TypeBuilder.Map(value)));
                    }
                    else
                    {
                        assembler.Add(TypeBuilder.Field(propertyName, TypeBuilder.Union(
                            TypeBuilder.NullType(), TypeBuilder.Map(value))));
                    }
                }
                else if (propertyClass.IsGenericCollection())
                {
                    AssembleFieldForCollection(propertyName, propertyType, assembler, avroSettings, propertyClass, preferNonNull);
                }
                else
                {
                    throw MakeEPException(propertyName, propertyType);
                }
            }
            else
            {
                throw MakeEPException(propertyName, propertyType);
            }
        }