private LinkedHashMap getListViewExamples(){

			LinkedHashMap examples = new LinkedHashMap();

			ArrayList examplesSet = new ArrayList();

			examplesSet.Add (new ListViewGettingStartedFragment());
			examplesSet.Add (new ListViewLayoutsFragment());
			examplesSet.Add (new ListViewDeckOfCardsFragment());
			examplesSet.Add (new ListViewSlideFragment());
			examplesSet.Add (new ListViewWrapFragment());
			examplesSet.Add (new ListViewItemAnimationFragment());
			examplesSet.Add (new ListViewDataOperationsFragment());

			examples.Put("Features", examplesSet);

			examplesSet = new ArrayList();

			examplesSet.Add (new ListViewReorderFragment());
			examplesSet.Add (new ListViewSwipeToExecuteFragment());
			examplesSet.Add (new ListViewSwipeToRefreshFragment());
			examplesSet.Add (new ListViewManualLoadOnDemandFragment());
			examplesSet.Add (new ListViewDataAutomaticLoadOnDemandFragment());
			examplesSet.Add (new ListViewSelectionFragment());
			examplesSet.Add (new ListViewStickyHeadersFragment ());
			examplesSet.Add (new ListViewCollapsibleFragment ());

			examples.Put("Behaviors", examplesSet);

			return examples;
		
		}
Esempio n. 2
0
		private LinkedHashMap getChartExamples(){
			LinkedHashMap chartExamples = new LinkedHashMap();

			ArrayList result = new ArrayList();

			result.Add(new AreaSeriesFragment());
			result.Add(new LineSeriesFragment());
			result.Add(new CandleStickSeriesFragment());
			result.Add(new DoughnutSeriesFragment());
			result.Add(new HorizontalBarSeriesFragment());
			result.Add(new IndicatorSeriesFragment());
			result.Add(new OhlcSeriesFragment());
			result.Add(new PieSeriesFragment());
			result.Add(new ScatterBubbleSeriesFragment());
			result.Add(new ScatterPointSeriesFragment());
			result.Add(new SplineAreaSeriesFragment());
			result.Add(new SplineSeriesFragment());
			result.Add(new StackAreaSeriesFragment());
			result.Add(new StackBarSeriesFragment());
			result.Add(new StackSplineAreaSeriesFragment());
			result.Add(new VerticalBarSeriesFragment());

			chartExamples.Put("Series", result);

			result = new ArrayList();

			result.Add(new ChartLegendFragment());
			result.Add(new GridFeatureFragment());
			result.Add(new PalettesFragment());

			chartExamples.Put("Features", result);

			result = new ArrayList();

			result.Add(new PanAndZoomFragment());
			result.Add(new SelectionBehaviorFragment());
			result.Add(new TooltipBehaviorFragment());
			result.Add(new TrackballBehaviorFragment());

			chartExamples.Put("Behaviors", result);

			result = new ArrayList();

			result.Add(new DateTimeContinuousAxisFragment());
			result.Add(new MultipleAxesFragment());

			chartExamples.Put("Axes", result);

			result = new ArrayList();

			result.Add(new GridLineAnnotationFragment());
			result.Add(new PlotBandAnnotationFragment());

			chartExamples.Put("Annotations", result);

			return chartExamples;
		}
		private LinkedHashMap getSideDrawerExamples(){
			LinkedHashMap sideDrawerExamples = new LinkedHashMap();
			ArrayList result = new ArrayList();

			result.Add (new DrawerInitialSetupFragment());

			sideDrawerExamples.Put ("Init", result);

			return sideDrawerExamples;
		}
		private LinkedHashMap getDataFormExamples(){
			LinkedHashMap dataFormExamples = new LinkedHashMap();
			ArrayList result = new ArrayList();

			result.Add (new DataFormGettingStartedFragment());
			result.Add (new DataFormFeaturesFragment ());
			result.Add (new DataFormEditorsFragment ());
			result.Add (new DataFormValidationFragment ());
			result.Add (new DataFormGroupLayoutFragment ());
			result.Add (new DataFormPlaceholderLayoutFragment ());
			result.Add (new DataFormValidationBehaviorFragment ());
			result.Add (new DataFormValidationModeFragment ());
			result.Add (new DataFormJsonEditFragment ());
			result.Add (new DataFormSchemaSetupFragment ());

			dataFormExamples.Put ("Features", result);

			return dataFormExamples;
		}
Esempio n. 5
0
        private static MatchEventSpec AnalyzeMatchEvent(EvalForgeNode relativeNode)
        {
            var taggedEventTypes = new LinkedHashMap<string, Pair<EventType, string>>();
            var arrayEventTypes = new LinkedHashMap<string, Pair<EventType, string>>();

            // Determine all the filter nodes used in the pattern
            var evalNodeAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(relativeNode);

            // collect all filters underneath
            foreach (var filterNode in evalNodeAnalysisResult.FilterNodes) {
                var optionalTag = filterNode.EventAsName;
                if (optionalTag != null) {
                    taggedEventTypes.Put(
                        optionalTag,
                        new Pair<EventType, string>(
                            filterNode.FilterSpecCompiled.FilterForEventType,
                            filterNode.FilterSpecCompiled.FilterForEventTypeName));
                }
            }

            // collect those filters under a repeat since they are arrays
            ISet<string> arrayTags = new HashSet<string>();
            foreach (var matchUntilNode in evalNodeAnalysisResult.RepeatNodes) {
                var matchUntilAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(matchUntilNode.ChildNodes[0]);
                foreach (var filterNode in matchUntilAnalysisResult.FilterNodes) {
                    var optionalTag = filterNode.EventAsName;
                    if (optionalTag != null) {
                        arrayTags.Add(optionalTag);
                    }
                }
            }

            // for each array tag change collection
            foreach (var arrayTag in arrayTags) {
                if (taggedEventTypes.Get(arrayTag) != null) {
                    arrayEventTypes.Put(arrayTag, taggedEventTypes.Get(arrayTag));
                    taggedEventTypes.Remove(arrayTag);
                }
            }

            return new MatchEventSpec(taggedEventTypes, arrayEventTypes);
        }
Esempio n. 6
0
        public Object EvaluateEnumMethod(EventBean[] eventsLambda, ICollection <object> target, bool isNewData, ExprEvaluatorContext context)
        {
            var result = new LinkedHashMap <Object, ICollection <object> >();

            foreach (EventBean next in target)
            {
                eventsLambda[StreamNumLambda] = next;

                var key   = InnerExpression.Evaluate(new EvaluateParams(eventsLambda, isNewData, context));
                var value = result.Get(key);
                if (value == null)
                {
                    value = new List <object>();
                    result.Put(key, value);
                }
                value.Add(next.Underlying);
            }

            return(result);
        }
Esempio n. 7
0
        public object EvaluateEnumMethod(EventBean[] eventsLambda, ICollection <object> target, bool isNewData, ExprEvaluatorContext context)
        {
            IDictionary <Object, int?> items = new LinkedHashMap <Object, int?>();

            foreach (Object next in target)
            {
                int?existing = items.Get(next);
                if (existing == null)
                {
                    existing = 1;
                }
                else
                {
                    existing++;
                }
                items.Put(next, existing);
            }

            return(EnumEvalMostLeastFrequentEvent.GetResult(items, _isMostFrequent));
        }
Esempio n. 8
0
        /// <summary>
        ///     Removed duplicate properties using the property name to find unique properties.
        /// </summary>
        /// <param name="properties">is a list of property descriptors</param>
        public static void RemoveDuplicateProperties(IList<PropertyStem> properties)
        {
            var set = new LinkedHashMap<string, PropertyStem>();
            var toRemove = new List<PropertyStem>();

            // add duplicates to separate list
            foreach (var desc in properties) {
                if (set.ContainsKey(desc.PropertyName)) {
                    toRemove.Add(desc);
                    continue;
                }

                set.Put(desc.PropertyName, desc);
            }

            // remove duplicates
            foreach (var desc in toRemove) {
                properties.Remove(desc);
            }
        }
Esempio n. 9
0
        public void TestEquals()
        {
            var metadata = new EventTypeMetadata(
                "MyType",
                null,
                EventTypeTypeClass.STREAM,
                EventTypeApplicationType.MAP,
                NameAccessModifier.INTERNAL,
                EventTypeBusModifier.NONBUS,
                false,
                EventTypeIdPair.Unassigned());

            IDictionary <string, object> mapTwo = new LinkedHashMap <string, object>();

            mapTwo.Put("MyInt", typeof(int));
            mapTwo.Put("MySupportBean", typeof(SupportBean));
            mapTwo.Put("MyNullableSupportBean", typeof(SupportBean));
            mapTwo.Put("MyComplexBean", typeof(SupportBeanComplexProps));
            Assert.IsFalse(
                new MapEventType(metadata, mapTwo, null, null, null, null, supportEventTypeFactory.BEAN_EVENT_TYPE_FACTORY).Equals(eventType));
            mapTwo.Put("MyString", typeof(string));
            mapTwo.Put("MyNullableString", typeof(string));
            mapTwo.Put("MyNullType", null);

            // compare, should equal
            Assert.IsNull(
                new MapEventType(metadata, mapTwo, null, null, null, null, supportEventTypeFactory.BEAN_EVENT_TYPE_FACTORY).EqualsCompareType(
                    eventType));
            Assert.AreEqual(
                null,
                new MapEventType(metadata, mapTwo, null, null, null, null, supportEventTypeFactory.BEAN_EVENT_TYPE_FACTORY).EqualsCompareType(
                    eventType));

            // Test boxed and primitive compatible
            IDictionary <string, object> mapOne = new LinkedHashMap <string, object>();

            mapOne.Put("MyInt", typeof(int));
            mapTwo = new LinkedHashMap <string, object>();
            mapTwo.Put("MyInt", typeof(int?));
            Assert.IsNull(
                new MapEventType(metadata, mapOne, null, null, null, null, supportEventTypeFactory.BEAN_EVENT_TYPE_FACTORY).EqualsCompareType(
                    new MapEventType(metadata, mapTwo, null, null, null, null,
                                     supportEventTypeFactory.BEAN_EVENT_TYPE_FACTORY)));
        }
Esempio n. 10
0
 public void AddNamedBean(String beanName, Object bean)
 {
     CheckNotDisposed();
     CheckNotRunning();
     ParamChecker.AssertParamNotNull(beanName, "beanName");
     ParamChecker.AssertParamNotNull(bean, "bean");
     if (nameToServiceDict == null)
     {
         nameToServiceDict = new LinkedHashMap <String, Object>();
     }
     if (nameToServiceDict.ContainsKey(beanName))
     {
         throw CreateDuplicateBeanNameException(beanName, bean, nameToServiceDict.Get(beanName));
     }
     if (beanName.Contains("&") || beanName.Contains("*") || beanName.Contains(" ") || beanName.Contains("\t"))
     {
         throw new ArgumentException("Bean name '" + beanName + "'  must not contain any of the following characters: '&', '*' or any whitespace");
     }
     nameToServiceDict.Put(beanName, bean);
 }
Esempio n. 11
0
        private LinkedHashMap getDataFormExamples()
        {
            LinkedHashMap dataFormExamples = new LinkedHashMap();
            ArrayList     result           = new ArrayList();

            result.Add(new DataFormGettingStartedFragment());
            result.Add(new DataFormFeaturesFragment());
            result.Add(new DataFormEditorsFragment());
            result.Add(new DataFormValidationFragment());
            result.Add(new DataFormGroupLayoutFragment());
            result.Add(new DataFormPlaceholderLayoutFragment());
            result.Add(new DataFormValidationBehaviorFragment());
            result.Add(new DataFormValidationModeFragment());
            result.Add(new DataFormJsonEditFragment());
            result.Add(new DataFormSchemaSetupFragment());

            dataFormExamples.Put("Features", result);

            return(dataFormExamples);
        }
        public void SetUp()
        {
            _container = SupportContainer.Reset();

            // Prepare regular test service
            var eventTypes = new EventType[]
            {
                SupportEventTypeFactory.CreateBeanType(typeof(SupportBean)),
                SupportEventTypeFactory.CreateBeanType(typeof(SupportBean)),
                SupportEventTypeFactory.CreateBeanType(typeof(SupportBean_A)),
                SupportEventTypeFactory.CreateBeanType(typeof(SupportMarketDataBean), "SupportMarketDataBean")
            };
            var eventTypeName = new string[]
            {
                "SupportBean", "SupportBean", "SupportBean_A",
                "SupportMarketDataBean"
            };
            var streamNames = new string[]
            {
                "s1", null, "s3", "s4"
            };

            _serviceRegular = new StreamTypeServiceImpl(eventTypes, streamNames,
                                                        new bool[10], "default", false);

            // Prepare with stream-zero being unambigous
            var streamTypes = new LinkedHashMap <string, Pair <EventType, string> >();

            for (int i = 0; i < streamNames.Length; i++)
            {
                streamTypes.Put(streamNames[i],
                                new Pair <EventType, string>(eventTypes[i], eventTypeName[i]));
            }
            _serviceStreamZeroUnambigous = new StreamTypeServiceImpl(streamTypes,
                                                                     "default", true, false);

            // Prepare requiring stream names for non-zero streams
            _serviceRequireStreamName = new StreamTypeServiceImpl(streamTypes,
                                                                  "default", true, true);
        }
Esempio n. 13
0
        public static IDictionary<string, Type> ResolveBeanEventTypes(
            IDictionary<string, string> typeToClassName,
            ImportService importService)
        {
            if (typeToClassName.IsEmpty()) {
                return Collections.GetEmptyMap<string, Type>();
            }

            IDictionary<string, Type> resolved = new LinkedHashMap<string, Type>();
            foreach (var entry in typeToClassName) {
                Type clazz;
                try {
                    clazz = importService.ResolveClassForBeanEventType(entry.Value);
                }
                catch (ImportException ex) {
                    throw new ConfigurationException("Class named '" + entry.Value + "' was not found", ex);
                }

                resolved.Put(entry.Key, clazz);
            }

            return resolved;
        }
Esempio n. 14
0
        public object EvaluateEnumMethod(
            EventBean[] eventsLambda,
            ICollection<object> enumcoll,
            bool isNewData,
            ExprEvaluatorContext context)
        {
            var beans = (ICollection<EventBean>) enumcoll;
            if (beans.Count <= 1) {
                return beans;
            }

            IDictionary<IComparable, EventBean> distinct = new LinkedHashMap<IComparable, EventBean>();
            foreach (var next in beans) {
                eventsLambda[_forge.StreamNumLambda] = next;

                var comparable = (IComparable) _innerExpression.Evaluate(eventsLambda, isNewData, context);
                if (!distinct.ContainsKey(comparable)) {
                    distinct.Put(comparable, next);
                }
            }

            return distinct.Values;
        }
        public Object EvaluateEnumMethod(EventBean[] eventsLambda, ICollection <object> target, bool isNewData, ExprEvaluatorContext context)
        {
            var result      = new LinkedHashMap <object, ICollection <object> >();
            var values      = (ICollection <Object>)target;
            var resultEvent = new ObjectArrayEventBean(new Object[1], _resultEventType);

            foreach (Object next in values)
            {
                resultEvent.Properties[0]     = next;
                eventsLambda[StreamNumLambda] = resultEvent;

                var key   = InnerExpression.Evaluate(new EvaluateParams(eventsLambda, isNewData, context));
                var value = result.Get(key);
                if (value == null)
                {
                    value = new List <object>();
                    result.Put(key, value);
                }
                value.Add(next);
            }

            return(result);
        }
Esempio n. 16
0
        /// <exception cref="System.Exception"></exception>
        private IDictionary <string, DirCacheCGitCompatabilityTest.CGitLsTreeRecord> ReadLsTree
            ()
        {
            LinkedHashMap <string, DirCacheCGitCompatabilityTest.CGitLsTreeRecord> r = new LinkedHashMap
                                                                                       <string, DirCacheCGitCompatabilityTest.CGitLsTreeRecord>();
            BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(
                                                                             PathOf("gitgit.lstree")), "UTF-8"));

            try
            {
                string line;
                while ((line = br.ReadLine()) != null)
                {
                    DirCacheCGitCompatabilityTest.CGitLsTreeRecord cr = new DirCacheCGitCompatabilityTest.CGitLsTreeRecord
                                                                            (line);
                    r.Put(cr.path, cr);
                }
            }
            finally
            {
                br.Close();
            }
            return(r);
        }
Esempio n. 17
0
            internal SectionNames(ConfigSnapshot cfg)
            {
                IDictionary <string, string> sec = new LinkedHashMap <string, string>();
                IDictionary <string, ICollection <string> > sub = new Dictionary <string, ICollection
                                                                                  <string> >();

                while (cfg != null)
                {
                    foreach (ConfigLine e in cfg.entryList)
                    {
                        if (e.section == null)
                        {
                            continue;
                        }
                        string l1 = StringUtils.ToLowerCase(e.section);
                        if (!sec.ContainsKey(l1))
                        {
                            sec.Put(l1, e.section);
                        }
                        if (e.subsection == null)
                        {
                            continue;
                        }
                        ICollection <string> m = sub.Get(l1);
                        if (m == null)
                        {
                            m = new LinkedHashSet <string>();
                            sub.Put(l1, m);
                        }
                        m.AddItem(e.subsection);
                    }
                    cfg = cfg.baseState;
                }
                sections    = new ConfigSnapshot.CaseFoldingSet(sec);
                subsections = sub;
            }
Esempio n. 18
0
        private static IDictionary <Type, JsonApplicationClassSerializationDesc> AssignDelegateClassNames(
            string eventTypeName,
            IDictionary <Type, IList <FieldInfo> > classesWFields)
        {
            var classes = new LinkedHashMap <Type, JsonApplicationClassSerializationDesc>();

            foreach (var classEntry in classesWFields)
            {
                var replaced = classEntry.Key.Name
                               .RegexReplaceAll("\\.", "_")
                               .RegexReplaceAll("\\$", "_");

                var serializerClassName   = eventTypeName + "_Serializer_" + replaced;
                var deserializerClassName = eventTypeName + "_Deserializer_" + replaced;
                classes.Put(
                    classEntry.Key,
                    new JsonApplicationClassSerializationDesc(
                        serializerClassName,
                        deserializerClassName,
                        classEntry.Value));
            }

            return(classes);
        }
        static ExcludePlanHintExprUtil()
        {
            var properties = new LinkedHashMap <String, Object>();

            properties.Put("from_streamnum", typeof(int));
            properties.Put("to_streamnum", typeof(int));
            properties.Put("from_streamname", typeof(String));
            properties.Put("to_streamname", typeof(String));
            properties.Put("opname", typeof(String));
            properties.Put("exprs", typeof(String[]));

            OAEXPRESSIONTYPE = new ObjectArrayEventType(
                EventTypeMetadata.CreateAnonymous(typeof(ExcludePlanHintExprUtil).Name),
                typeof(ExcludePlanHintExprUtil).Name,
                0,
                null,
                properties,
                null,
                null,
                null);
        }
Esempio n. 20
0
        public DataFlowOpInitializeResult Initialize(DataFlowOpInitializateContext context)
        {
            _initialDelayMSec = (long)(initialDelay * 1000);
            _periodDelayMSec  = (long)(interval * 1000);

            if (context.OutputPorts.Count != 1)
            {
                throw new ArgumentException(
                          "BeaconSource operator requires one output stream but produces " + context.OutputPorts.Count +
                          " streams");
            }

            // Check if a type is declared
            var port = context.OutputPorts[0];
            ICollection <string> props;

            if (port.OptionalDeclaredType != null && port.OptionalDeclaredType.EventType != null)
            {
                var outputEventType = port.OptionalDeclaredType.EventType;
                _produceEventBean = port.OptionalDeclaredType != null && !port.OptionalDeclaredType.IsUnderlying;

                // compile properties to populate
                props = _allProperties.Keys;
                props.RemoveAll(PARAMETER_PROPERTIES);
                var writables = SetupProperties(props.ToArray(), outputEventType, context.StatementContext);
                _manufacturer = context.ServicesContext.EventAdapterService.GetManufacturer(
                    outputEventType, writables, context.ServicesContext.EngineImportService, false);

                var index = 0;
                _evaluators = new ExprEvaluator[writables.Length];
                TypeWidenerCustomizer typeWidenerCustomizer =
                    context.ServicesContext.EventAdapterService.GetTypeWidenerCustomizer(outputEventType);
                foreach (var writeable in writables)
                {
                    var providedProperty = _allProperties.Get(writeable.PropertyName);
                    if (providedProperty is ExprNode)
                    {
                        var exprNode  = (ExprNode)providedProperty;
                        var validated = ExprNodeUtility.ValidateSimpleGetSubtree(
                            ExprNodeOrigin.DATAFLOWBEACON, exprNode, context.StatementContext, null, false);
                        var exprEvaluator = validated.ExprEvaluator;
                        var widener       = TypeWidenerFactory.GetCheckPropertyAssignType(
                            ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(validated), exprEvaluator.ReturnType,
                            writeable.PropertyType, writeable.PropertyName, false, typeWidenerCustomizer,
                            context.StatementContext.StatementName, context.Engine.URI);
                        if (widener != null)
                        {
                            _evaluators[index] = new ProxyExprEvaluator
                            {
                                ProcEvaluate = evaluateParams =>
                                {
                                    var value = exprEvaluator.Evaluate(evaluateParams);
                                    return(widener.Invoke(value));
                                },
                                ProcReturnType = () => null
                            };
                        }
                        else
                        {
                            _evaluators[index] = exprEvaluator;
                        }
                    }
                    else if (providedProperty == null)
                    {
                        _evaluators[index] = new ProxyExprEvaluator
                        {
                            ProcEvaluate   = evaluateParams => null,
                            ProcReturnType = () => null
                        };
                    }
                    else
                    {
                        _evaluators[index] = new ProxyExprEvaluator
                        {
                            ProcEvaluate   = evaluateParams => providedProperty,
                            ProcReturnType = () => providedProperty.GetType()
                        };
                    }
                    index++;
                }

                return(null); // no changing types
            }

            // No type has been declared, we can create one
            var anonymousTypeName = context.DataflowName + "-beacon";
            var types             = new LinkedHashMap <string, Object>();

            props = _allProperties.Keys;
            props.RemoveAll(PARAMETER_PROPERTIES);

            var count = 0;

            _evaluators = new ExprEvaluator[props.Count];
            foreach (var propertyName in props)
            {
                var exprNode        = (ExprNode)_allProperties.Get(propertyName);
                var validated       = ExprNodeUtility.ValidateSimpleGetSubtree(ExprNodeOrigin.DATAFLOWBEACON, exprNode, context.StatementContext, null, false);
                var evaluateParamsX = new EvaluateParams(null, true, context.AgentInstanceContext);
                var value           = validated.ExprEvaluator.Evaluate(evaluateParamsX);
                if (value == null)
                {
                    types.Put(propertyName, null);
                }
                else
                {
                    types.Put(propertyName, value.GetType());
                }
                _evaluators[count] = new ProxyExprEvaluator()
                {
                    ProcEvaluate   = (evaluateParams) => value,
                    ProcReturnType = () => null
                };
                count++;
            }

            EventType type =
                context.ServicesContext.EventAdapterService.CreateAnonymousObjectArrayType(anonymousTypeName, types);

            return(new DataFlowOpInitializeResult(
                       new GraphTypeDesc[]
            {
                new GraphTypeDesc(false, true, type)
            }));
        }
        private LinkedHashMap GetCalendarExamples()
        {
            LinkedHashMap calendarExamples = new LinkedHashMap();
            ArrayList     result           = new ArrayList();

            result.Add(new InitCodeFragment());
            result.Add(new InitXmlFragment());

            calendarExamples.Put("Init", result);

            result = new ArrayList();

            result.Add(new DisplayDateSetFragment());
            result.Add(new DisplayDateChangeListenerFragment());
            result.Add(new DisplayDateMinMaxValuesFragment());
            //result.Add (new DisplayDateChangeEventFragment());

            calendarExamples.Put("Display Date", result);

            result = new ArrayList();

            result.Add(new DisplayModeFragment());
            result.Add(new DisplayModeChangeListenerFragment());

            calendarExamples.Put("Display Mode", result);

            result = new ArrayList();
            result.Add(new CellStylesFragment());
            result.Add(new CustomizationRuleFragment());
            result.Add(new DateToColorFragment());

            calendarExamples.Put("Customizations", result);

            result = new ArrayList();

            result.Add(new EventFragment());
            result.Add(new EventAllDayFragment());
            result.Add(new EventRenderModeFragment());
            result.Add(new ReadEventsFragment());
            //result.Add (new ReadEventsOptionsFragment());
            result.Add(new EventsInlineDisplayModeFragment());
            result.Add(new EventsPopupDisplayModeFragment());

            calendarExamples.Put("Events", result);

            result = new ArrayList();

            result.Add(new ScrollingDirectionFragment());
            result.Add(new ScrollingFlingSpeedFragment());
            result.Add(new ScrollingFrictionFragment());
            result.Add(new ScrollingModesFragment());
            result.Add(new ScrollingProgramatticallyFragment());
            result.Add(new ScrollingSnapFragment());

            calendarExamples.Put("Scrolling", result);

            result = new ArrayList();

            result.Add(new SelectionChangedListenerFragment());
            //result.Add (new SelectionChangedEventFragment());
            result.Add(new SelectionDecoratorsFragment());
            result.Add(new SelectionDisabledDatesFragment());
            result.Add(new SelectionModesFragment());
            result.Add(new SelectionSetDatesFragment());
            result.Add(new SelectionSetRangeFragment());

            calendarExamples.Put("Selection", result);

            return(calendarExamples);
        }
        private void doTest(SpatialOperation operation)
        {
            //first show that when there's no data, a query will result in no results
            {
                Query         query         = strategy.MakeQuery(new SpatialArgs(operation, randomRectangle()));
                SearchResults searchResults = executeQuery(query, 1);
                assertEquals(0, searchResults.numFound);
            }

            bool biasContains = (operation == SpatialOperation.Contains);

            //Main index loop:
            IDictionary <String, IShape> indexedShapes   = new LinkedHashMap <String, IShape>();
            IDictionary <String, IShape> indexedShapesGS = new LinkedHashMap <String, IShape>();//grid snapped
            int numIndexedShapes = randomIntBetween(1, 6);

#pragma warning disable 219
            bool indexedAtLeastOneShapePair = false;
#pragma warning restore 219
            for (int i = 0; i < numIndexedShapes; i++)
            {
                String id = "" + i;
                IShape indexedShape;
                int    R = Random.nextInt(12);
                if (R == 0)
                {//1 in 12
                    indexedShape = null;
                }
                else if (R == 1)
                {                                 //1 in 12
                    indexedShape = randomPoint(); //just one point
                }
                else if (R <= 4)
                {//3 in 12
                 //comprised of more than one shape
                    indexedShape = randomShapePairRect(biasContains);
                    indexedAtLeastOneShapePair = true;
                }
                else
                {
                    indexedShape = randomRectangle();//just one rect
                }

                indexedShapes.Put(id, indexedShape);
                indexedShapesGS.Put(id, gridSnap(indexedShape));

                adoc(id, indexedShape);

                if (Random.nextInt(10) == 0)
                {
                    Commit();//intermediate commit, produces extra segments
                }
            }
            //delete some documents randomly
            IEnumerator <String> idIter = indexedShapes.Keys.ToList().GetEnumerator();
            while (idIter.MoveNext())
            {
                String id = idIter.Current;
                if (Random.nextInt(10) == 0)
                {
                    DeleteDoc(id);
                    //idIter.Remove();
                    indexedShapes.Remove(id);
                    indexedShapesGS.Remove(id);
                }
            }

            Commit();

            //Main query loop:
            int numQueryShapes = AtLeast(20);
            for (int i = 0; i < numQueryShapes; i++)
            {
                int scanLevel = randomInt(grid.MaxLevels);
                ((RecursivePrefixTreeStrategy)strategy).PrefixGridScanLevel = (scanLevel);

                IShape queryShape;
                switch (randomInt(10))
                {
                case 0: queryShape = randomPoint(); break;

                // LUCENE-5549
                //TODO debug: -Dtests.method=testWithin -Dtests.multiplier=3 -Dtests.seed=5F5294CE2E075A3E:AAD2F0F79288CA64
                //        case 1:case 2:case 3:
                //          if (!indexedAtLeastOneShapePair) { // avoids ShapePair.relate(ShapePair), which isn't reliable
                //            queryShape = randomShapePairRect(!biasContains);//invert biasContains for query side
                //            break;
                //          }
                default: queryShape = randomRectangle(); break;
                }
                IShape queryShapeGS = gridSnap(queryShape);

                bool opIsDisjoint = operation == SpatialOperation.IsDisjointTo;

                //Generate truth via brute force:
                // We ensure true-positive matches (if the predicate on the raw shapes match
                //  then the search should find those same matches).
                // approximations, false-positive matches
                ISet <String> expectedIds  = new /* LinkedHashSet<string>*/ HashSet <string>(); //true-positives
                ISet <String> secondaryIds = new /* LinkedHashSet<string>*/ HashSet <string>(); //false-positives (unless disjoint)
                foreach (var entry in indexedShapes)
                {
                    String id = entry.Key;
                    IShape indexedShapeCompare = entry.Value;
                    if (indexedShapeCompare == null)
                    {
                        continue;
                    }
                    IShape queryShapeCompare = queryShape;

                    if (operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                    {
                        expectedIds.add(id);
                        if (opIsDisjoint)
                        {
                            //if no longer intersect after buffering them, for disjoint, remember this
                            indexedShapeCompare = indexedShapesGS[id];
                            queryShapeCompare   = queryShapeGS;
                            if (!operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                            {
                                secondaryIds.add(id);
                            }
                        }
                    }
                    else if (!opIsDisjoint)
                    {
                        //buffer either the indexed or query shape (via gridSnap) and try again
                        if (operation == SpatialOperation.Intersects)
                        {
                            indexedShapeCompare = indexedShapesGS[id];
                            queryShapeCompare   = queryShapeGS;
                            //TODO Unfortunately, grid-snapping both can result in intersections that otherwise
                            // wouldn't happen when the grids are adjacent. Not a big deal but our test is just a
                            // bit more lenient.
                        }
                        else if (operation == SpatialOperation.Contains)
                        {
                            indexedShapeCompare = indexedShapesGS[id];
                        }
                        else if (operation == SpatialOperation.IsWithin)
                        {
                            queryShapeCompare = queryShapeGS;
                        }
                        if (operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                        {
                            secondaryIds.add(id);
                        }
                    }
                }

                //Search and verify results
                SpatialArgs args = new SpatialArgs(operation, queryShape);
                if (queryShape is ShapePair)
                {
                    args.DistErrPct = (0.0);//a hack; we want to be more detailed than gridSnap(queryShape)
                }
                Query         query = strategy.MakeQuery(args);
                SearchResults got   = executeQuery(query, 100);
                ISet <String> remainingExpectedIds = new /* LinkedHashSet<string>*/ HashSet <string>(expectedIds);
                foreach (SearchResult result in got.results)
                {
                    String id      = result.GetId();
                    bool   removed = remainingExpectedIds.remove(id);
                    if (!removed && (!opIsDisjoint && !secondaryIds.contains(id)))
                    {
                        fail("Shouldn't match", id, indexedShapes, indexedShapesGS, queryShape);
                    }
                }
                if (opIsDisjoint)
                {
                    remainingExpectedIds.removeAll(secondaryIds);
                }
                if (remainingExpectedIds.Any())
                {
                    var iter = remainingExpectedIds.GetEnumerator();
                    iter.MoveNext();
                    String id = iter.Current;
                    fail("Should have matched", id, indexedShapes, indexedShapesGS, queryShape);
                }
            }
        }
Esempio n. 23
0
        private void RunAssertionMapAndNestedArray(EPServiceProvider epService)
        {
            var defOuter = new LinkedHashMap <string, Object>();

            defOuter.Put("intarr", typeof(int[]));
            defOuter.Put("innersimple", "InnerMap");
            defOuter.Put("innerarray", "InnerMap[]");
            defOuter.Put("prop0", typeof(SupportBean_A));

            var defInner = new LinkedHashMap <string, Object>();

            defInner.Put("stringarr", typeof(string[]));
            defInner.Put("prop1", typeof(string));

            epService.EPAdministrator.Configuration.AddEventType("InnerMap", defInner);
            epService.EPAdministrator.Configuration.AddEventType("OuterMap", defOuter);
            EPStatement statement = epService.EPAdministrator.CreateEPL("select * from OuterMap");

            var dataInner = new LinkedHashMap <string, Object>();

            dataInner.Put("stringarr", new string[] { "a", null });
            dataInner.Put("prop1", "");
            var dataArrayOne = new LinkedHashMap <string, Object>();

            dataArrayOne.Put("stringarr", new string[0]);
            dataArrayOne.Put("prop1", "abcdef");
            var dataArrayTwo = new LinkedHashMap <string, Object>();

            dataArrayTwo.Put("stringarr", new string[] { "R&R", "a>b" });
            dataArrayTwo.Put("prop1", "");
            var dataArrayThree = new LinkedHashMap <string, Object>();

            dataArrayOne.Put("stringarr", null);
            var dataOuter = new LinkedHashMap <string, Object>();

            dataOuter.Put("intarr", new int[] { 1, 2 });
            dataOuter.Put("innersimple", dataInner);
            dataOuter.Put("innerarray", new Map[] { dataArrayOne, dataArrayTwo, dataArrayThree });
            dataOuter.Put("prop0", new SupportBean_A("A1"));
            epService.EPRuntime.SendEvent(dataOuter, "OuterMap");

            string result = epService.EPRuntime.EventRenderer.RenderXML("outerMap", statement.First());
            // Log.Info(result);
            string expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                              "<outerMap>\n" +
                              "  <intarr>1</intarr>\n" +
                              "  <intarr>2</intarr>\n" +
                              "  <innerarray>\n" +
                              "    <prop1>abcdef</prop1>\n" +
                              "  </innerarray>\n" +
                              "  <innerarray>\n" +
                              "    <prop1></prop1>\n" +
                              "    <stringarr>R&amp;R</stringarr>\n" +
                              "    <stringarr>a&gt;b</stringarr>\n" +
                              "  </innerarray>\n" +
                              "  <innerarray>\n" +
                              "  </innerarray>\n" +
                              "  <innersimple>\n" +
                              "    <prop1></prop1>\n" +
                              "    <stringarr>a</stringarr>\n" +
                              "  </innersimple>\n" +
                              "  <prop0>\n" +
                              "    <Id>A1</Id>\n" +
                              "  </prop0>\n" +
                              "</outerMap>";

            Assert.AreEqual(RemoveNewline(expected), RemoveNewline(result));

            result = epService.EPRuntime.EventRenderer.RenderXML("outerMap xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"", statement.First(), new XMLRenderingOptions()
            {
                IsDefaultAsAttribute = true
            });
            // Log.Info(result);
            expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                       "<outerMap xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n" +
                       "  <intarr>1</intarr>\n" +
                       "  <intarr>2</intarr>\n" +
                       "  <innerarray prop1=\"abcdef\"/>\n" +
                       "  <innerarray prop1=\"\">\n" +
                       "    <stringarr>R&amp;R</stringarr>\n" +
                       "    <stringarr>a&gt;b</stringarr>\n" +
                       "  </innerarray>\n" +
                       "  <innerarray/>\n" +
                       "  <innersimple prop1=\"\">\n" +
                       "    <stringarr>a</stringarr>\n" +
                       "  </innersimple>\n" +
                       "  <prop0 Id=\"A1\"/>\n" +
                       "</outerMap>";
            Assert.AreEqual(RemoveNewline(expected), RemoveNewline(result));

            statement.Dispose();
        }
Esempio n. 24
0
        public static LinkedHashMap<string, object> ResolvePropertyTypes(
            IDictionary<string, object> propertyTypes,
            EventTypeNameResolver eventTypeNameResolver)
        {
            var verified = new LinkedHashMap<string, object>();
            foreach (var prop in propertyTypes) {
                var propertyName = prop.Key;
                var propertyType = prop.Value;

                if (propertyType is Type ||
                    propertyType is EventType ||
                    propertyType == null ||
                    propertyType is TypeBeanOrUnderlying) {
                    verified.Put(propertyName, propertyType);
                    continue;
                }

                if (propertyType is EventType[]) {
                    var types = (EventType[]) propertyType;
                    if (types.Length != 1 || types[0] == null) {
                        throw new ArgumentException("Invalid null event type array");
                    }

                    verified.Put(propertyName, propertyType);
                    continue;
                }

                if (propertyType is TypeBeanOrUnderlying[]) {
                    var types = (TypeBeanOrUnderlying[]) propertyType;
                    if (types.Length != 1 || types[0] == null) {
                        throw new ArgumentException("Invalid null event type array");
                    }

                    verified.Put(propertyName, propertyType);
                    continue;
                }

                if (propertyType is IDictionary<string, object>) {
                    IDictionary<string, object> inner = ResolvePropertyTypes(
                        (IDictionary<string, object>) propertyType,
                        eventTypeNameResolver);
                    verified.Put(propertyName, inner);
                    continue;
                }

                if (!(propertyType is string propertyTypeName)) {
                    throw MakeUnexpectedTypeException(propertyType.ToString(), propertyName);
                }

                var isArray = EventTypeUtility.IsPropertyArray(propertyTypeName);
                if (isArray) {
                    propertyTypeName = EventTypeUtility.GetPropertyRemoveArray(propertyTypeName);
                }

                var eventType = eventTypeNameResolver.GetTypeByName(propertyTypeName);
                if (!(eventType is BaseNestableEventType) && !(eventType is BeanEventType)) {
                    var clazz = TypeHelper.GetPrimitiveTypeForName(propertyTypeName);
                    if (clazz != null) {
                        verified.Put(propertyName, clazz);
                        continue;
                    }

                    throw MakeUnexpectedTypeException(propertyTypeName, propertyName);
                }

                if (eventType is BaseNestableEventType) {
                    var typeEntity = !isArray
                        ? new TypeBeanOrUnderlying(eventType)
                        : (object) new[] {new TypeBeanOrUnderlying(eventType)};
                    verified.Put(propertyName, typeEntity);
                    continue;
                }

                var beanEventType = (BeanEventType) eventType;
                object type = !isArray
                    ? beanEventType.UnderlyingType
                    : TypeHelper.GetArrayType(beanEventType.UnderlyingType);
                verified.Put(propertyName, type);
            }

            return verified;
        }
Esempio n. 25
0
		/// <exception cref="System.IO.IOException"></exception>
		private void ReadBundleV2()
		{
			byte[] hdrbuf = new byte[1024];
			LinkedHashMap<string, Ref> avail = new LinkedHashMap<string, Ref>();
			for (; ; )
			{
				string line = ReadLine(hdrbuf);
				if (line.Length == 0)
				{
					break;
				}
				if (line[0] == '-')
				{
					ObjectId id = ObjectId.FromString(Sharpen.Runtime.Substring(line, 1, 41));
					string shortDesc = null;
					if (line.Length > 42)
					{
						shortDesc = Sharpen.Runtime.Substring(line, 42);
					}
					prereqs.Put(id, shortDesc);
					continue;
				}
				string name = Sharpen.Runtime.Substring(line, 41, line.Length);
				ObjectId id_1 = ObjectId.FromString(Sharpen.Runtime.Substring(line, 0, 40));
				Ref prior = avail.Put(name, new ObjectIdRef.Unpeeled(RefStorage.NETWORK, name, id_1
					));
				if (prior != null)
				{
					throw DuplicateAdvertisement(name);
				}
			}
			Available(avail);
		}
        public void Run(RegressionEnvironment env)
        {
            // Bean
            BiConsumer <EventType, Nullable2Lvl> bean = (
                type,
                val) => {
                LocalEvent @event;
                if (val.IsNullAtRoot)
                {
                    @event = new LocalEvent(null);
                }
                else if (val.IsNullAtInner)
                {
                    @event = new LocalEvent(new LocalInnerEvent(null));
                }
                else
                {
                    @event = new LocalEvent(new LocalInnerEvent(new LocalLeafEvent(val.Id)));
                }

                env.SendEventBean(@event);
            };
            var beanepl = $"@public @buseventtype create schema LocalEvent as {typeof(LocalEvent).MaskTypeName()};\n";

            RunAssertion(env, beanepl, bean);

            // Map
            BiConsumer <EventType, Nullable2Lvl> map = (
                type,
                val) => {
                IDictionary <string, object> @event = new LinkedHashMap <string, object>();
                if (val.IsNullAtRoot)
                {
                    // no change
                }
                else if (val.IsNullAtInner)
                {
                    var inner = Collections.SingletonDataMap("Leaf", null);
                    @event.Put("Property", inner);
                }
                else
                {
                    var leaf  = Collections.SingletonDataMap("Id", val.Id);
                    var inner = Collections.SingletonDataMap("Leaf", leaf);
                    @event.Put("Property", inner);
                }

                env.SendEventMap(@event, "LocalEvent");
            };

            RunAssertion(env, GetEpl("map"), map);

            // Object-array
            BiConsumer <EventType, Nullable2Lvl> oa = (
                type,
                val) => {
                var @event = new object[1];
                if (val.IsNullAtRoot)
                {
                    // no change
                }
                else if (val.IsNullAtInner)
                {
                    var inner = new object[] { null };
                    @event[0] = inner;
                }
                else
                {
                    var leaf  = new object[] { val.Id };
                    var inner = new object[] { leaf };
                    @event[0] = inner;
                }

                env.SendEventObjectArray(@event, "LocalEvent");
            };

            RunAssertion(env, GetEpl("objectarray"), oa);

            // Json
            BiConsumer <EventType, Nullable2Lvl> json = (
                type,
                val) => {
                var @event = new JObject();
                if (val.IsNullAtRoot)
                {
                    // no change
                }
                else if (val.IsNullAtInner)
                {
                    @event.Add("Property", new JObject(new JProperty("Leaf", null)));
                }
                else
                {
                    var leaf  = new JObject(new JProperty("Id", val.Id));
                    var inner = new JObject(new JProperty("Leaf", leaf));
                    @event.Add("Property", inner);
                }

                env.SendEventJson(@event.ToString(), "LocalEvent");
            };

            RunAssertion(env, GetEpl("json"), json);

            // Json-Class-Provided
            var eplJsonProvided =
                $"@JsonSchema(ClassName='{typeof(MyLocalJsonProvided).MaskTypeName()}') " +
                "@public @buseventtype create json schema LocalEvent();\n";

            RunAssertion(env, eplJsonProvided, json);

            // Avro
            BiConsumer <EventType, Nullable2Lvl> avro = (
                type,
                val) => {
                var schema = SupportAvroUtil.GetAvroSchema(type);
                var @event = new GenericRecord(schema.AsRecordSchema());
                if (val.IsNullAtRoot)
                {
                    // no change
                }
                else if (val.IsNullAtInner)
                {
                    var inner = new GenericRecord(schema
                                                  .GetField("Property")
                                                  .Schema.AsRecordSchema());
                    @event.Put("Property", inner);
                }
                else
                {
                    var leaf = new GenericRecord(schema
                                                 .GetField("Property")
                                                 .Schema.AsRecordSchema()
                                                 .GetField("Leaf")
                                                 .Schema.AsRecordSchema());
                    leaf.Put("Id", val.Id);
                    var inner = new GenericRecord(schema.GetField("Property").Schema.AsRecordSchema());
                    inner.Put("Leaf", leaf);
                    @event.Put("Property", inner);
                }

                env.SendEventAvro(@event, "LocalEvent");
            };

            RunAssertion(env, GetEpl("avro"), avro);
        }
        public override EnumForgeDescFactory GetForgeFactory(
            DotMethodFP footprint,
            IList <ExprNode> parameters,
            EnumMethodEnum enumMethod,
            string enumMethodUsedName,
            EventType inputEventType,
            Type collectionComponentType,
            ExprValidationContext validationContext)
        {
            if (parameters.IsEmpty())
            {
                var typeX = InitAndNoParamsReturnType(inputEventType, collectionComponentType);
                return(new ThreeFormNoParamFactory(typeX, NoParamsForge(enumMethod, typeX, validationContext.StatementCompileTimeService)));
            }

            var goesNode    = (ExprLambdaGoesNode)parameters[0];
            var goesToNames = goesNode.GoesToNames;

            if (inputEventType != null)
            {
                var streamName = goesToNames[0];
                if (goesToNames.Count == 1)
                {
                    return(new ThreeFormEventPlainFactory(
                               InitAndSingleParamReturnType(inputEventType, collectionComponentType),
                               inputEventType,
                               streamName,
                               SingleParamEventPlain(enumMethod)));
                }

                IDictionary <string, object> fieldsX = new LinkedHashMap <string, object>();
                fieldsX.Put(goesToNames[1], typeof(int?));
                if (goesToNames.Count > 2)
                {
                    fieldsX.Put(goesToNames[2], typeof(int?));
                }

                var fieldType = ExprDotNodeUtility.MakeTransientOAType(
                    enumMethodUsedName,
                    fieldsX,
                    validationContext.StatementRawInfo,
                    validationContext.StatementCompileTimeService);
                return(new ThreeFormEventPlusFactory(
                           InitAndSingleParamReturnType(inputEventType, collectionComponentType),
                           inputEventType,
                           streamName,
                           fieldType,
                           goesToNames.Count,
                           SingleParamEventPlus(enumMethod)));
            }

            var fields = new LinkedHashMap <string, object>();

            fields.Put(goesToNames[0], collectionComponentType);
            if (goesToNames.Count > 1)
            {
                fields.Put(goesToNames[1], typeof(int?));
            }

            if (goesToNames.Count > 2)
            {
                fields.Put(goesToNames[2], typeof(int?));
            }

            var type = ExprDotNodeUtility.MakeTransientOAType(
                enumMethodUsedName,
                fields,
                validationContext.StatementRawInfo,
                validationContext.StatementCompileTimeService);

            return(new ThreeFormScalarFactory(
                       InitAndSingleParamReturnType(inputEventType, collectionComponentType),
                       type,
                       goesToNames.Count,
                       SingleParamScalar(enumMethod)));
        }
Esempio n. 28
0
        /**
         * /// Loads the sphinx3 density file, a set of density arrays are created and
         * /// placed in the given pool.
         * ///
         * /// @param useCDUnits
         * ///            if true, loads also the context dependent units
         * /// @param inputStream
         * ///            the open input stream to use
         * /// @param path
         * ///            the path to a density file
         * /// @throws FileNotFoundException
         * ///             if a file cannot be found
         * /// @throws IOException
         * ///             if an error occurs while loading the data
         */
        protected void LoadHMMPool(Boolean useCDUnits, Stream inputStream,
                                   string path)
        {
            var est = new ExtendedStreamTokenizer(inputStream,
                                                  '#', false);

            this.LogInfo("Loading HMM file from: " + path);

            est.ExpectString(ModelVersion);

            var numBase = est.GetInt("numBase");

            est.ExpectString("n_base");

            var numTri = est.GetInt("numTri");

            est.ExpectString("n_tri");

            var numStateMap = est.GetInt("numStateMap");

            est.ExpectString("n_state_map");

            var numTiedState = est.GetInt("numTiedState");

            est.ExpectString("n_tied_state");

            var numContextIndependentTiedState = est
                                                 .GetInt("numContextIndependentTiedState");

            est.ExpectString("n_tied_ci_state");

            var numTiedTransitionMatrices = est.GetInt("numTiedTransitionMatrices");

            est.ExpectString("n_tied_tmat");

            var numStatePerHMM = numStateMap / (numTri + numBase);

            Debug.Assert(numTiedState == MixtureWeightsPool.StatesNum);
            Debug.Assert(numTiedTransitionMatrices == MatrixPool.Size);

            // Load the base phones
            for (var i = 0; i < numBase; i++)
            {
                var name      = est.GetString();
                var left      = est.GetString();
                var right     = est.GetString();
                var position  = est.GetString();
                var attribute = est.GetString();
                var tmat      = est.GetInt("tmat");

                var stid = new int[numStatePerHMM - 1];

                for (var j = 0; j < numStatePerHMM - 1; j++)
                {
                    stid[j] = est.GetInt("j");
                    Debug.Assert(stid[j] >= 0 && stid[j] < numContextIndependentTiedState);
                }
                est.ExpectString("N");

                Debug.Assert(left.Equals("-"));
                Debug.Assert(right.Equals("-"));
                Debug.Assert(position.Equals("-"));
                Debug.Assert(tmat < numTiedTransitionMatrices);

                var unit = _unitManager.GetUnit(name, attribute.Equals(Filler));
                ContextIndependentUnits.Put(unit.Name, unit);


                //this.LogInfo("Loaded " + unit.ToString());

                // The first filler
                if (unit.IsFiller && unit.Name.Equals(SilenceCiphone))
                {
                    unit = UnitManager.Silence;
                }

                var transitionMatrix = MatrixPool.Get(tmat);
                var ss = GetSenoneSequence(stid);

                IHMM hmm = new SenoneHMM(unit, ss, transitionMatrix, GetHMMPosition(position));
                HmmManager.Put(hmm);
            }

            if (HmmManager.Get(HMMPosition.Undefined, UnitManager.Silence) == null)
            {
                throw new IOException("Could not find SIL unit in acoustic model");
            }

            // Load the context dependent phones. If the useCDUnits
            // property is false, the CD phones will not be created, but
            // the values still need to be read in from the file.

            var  lastUnitName = "";
            Unit lastUnit     = null;

            int[]          lastStid           = null;
            SenoneSequence lastSenoneSequence = null;

            for (var i = 0; i < numTri; i++)
            {
                var name      = est.GetString();
                var left      = est.GetString();
                var right     = est.GetString();
                var position  = est.GetString();
                var attribute = est.GetString();
                var tmat      = est.GetInt("tmat");

                var stid = new int[numStatePerHMM - 1];

                for (var j = 0; j < numStatePerHMM - 1; j++)
                {
                    stid[j] = est.GetInt("j");
                    Debug.Assert(stid[j] >= numContextIndependentTiedState &&
                                 stid[j] < numTiedState);
                }
                est.ExpectString("N");

                Debug.Assert(!left.Equals("-"));
                Debug.Assert(!right.Equals("-"));
                Debug.Assert(!position.Equals("-"));
                Debug.Assert(attribute.Equals("n/a"));
                Debug.Assert(tmat < numTiedTransitionMatrices);

                if (useCDUnits)
                {
                    Unit unit;
                    var  unitName = (name + ' ' + left + ' ' + right);

                    if (unitName.Equals(lastUnitName))
                    {
                        unit = lastUnit;
                    }
                    else
                    {
                        var leftContext = new Unit[1];
                        leftContext[0] = ContextIndependentUnits.Get(left);

                        var rightContext = new Unit[1];
                        rightContext[0] = ContextIndependentUnits.Get(right);

                        Context context = LeftRightContext.Get(leftContext,
                                                               rightContext);
                        unit = _unitManager.GetUnit(name, false, context);
                    }
                    lastUnitName = unitName;
                    lastUnit     = unit;


                    //this.LogInfo("Loaded " + unit.ToString());


                    var transitionMatrix = MatrixPool.Get(tmat);

                    var ss = lastSenoneSequence;
                    if (ss == null || !SameSenoneSequence(stid, lastStid))
                    {
                        ss = GetSenoneSequence(stid);
                    }
                    lastSenoneSequence = ss;
                    lastStid           = stid;

                    IHMM hmm = new SenoneHMM(unit, ss, transitionMatrix, GetHMMPosition(position));
                    HmmManager.Put(hmm);
                }
            }

            est.Close();
        }
Esempio n. 29
0
 /// <exception cref="System.IO.IOException"></exception>
 internal override void ConfigureRequest(HttpURLConnection conn)
 {
     IDictionary<string, string> r = new LinkedHashMap<string, string>();
     string realm = @params.Get("realm");
     string nonce = @params.Get("nonce");
     string cnonce = @params.Get("cnonce");
     string uri = Uri(conn.GetURL());
     string qop = @params.Get("qop");
     string method = conn.GetRequestMethod();
     string A1 = user + ":" + realm + ":" + pass;
     string A2 = method + ":" + uri;
     r.Put("username", user);
     r.Put("realm", realm);
     r.Put("nonce", nonce);
     r.Put("uri", uri);
     string response;
     string nc;
     if ("auth".Equals(qop))
     {
         nc = string.Format("%08x", ++requestCount);
         response = KD(H(A1), nonce + ":" + nc + ":" + cnonce + ":" + qop + ":" + H(A2));
     }
     else
     {
         nc = null;
         response = KD(H(A1), nonce + ":" + H(A2));
     }
     r.Put("response", response);
     if (@params.ContainsKey("algorithm"))
     {
         r.Put("algorithm", "MD5");
     }
     if (cnonce != null && qop != null)
     {
         r.Put("cnonce", cnonce);
     }
     if (@params.ContainsKey("opaque"))
     {
         r.Put("opaque", @params.Get("opaque"));
     }
     if (qop != null)
     {
         r.Put("qop", qop);
     }
     if (nc != null)
     {
         r.Put("nc", nc);
     }
     StringBuilder v = new StringBuilder();
     foreach (KeyValuePair<string, string> e in r.EntrySet())
     {
         if (v.Length > 0)
         {
             v.Append(", ");
         }
         v.Append(e.Key);
         v.Append('=');
         v.Append('"');
         v.Append(e.Value);
         v.Append('"');
     }
     conn.SetRequestProperty(HttpSupport.HDR_AUTHORIZATION, NAME + " " + v);
 }
Esempio n. 30
0
		/// <exception cref="System.IO.IOException"></exception>
		private void ReadAdvertisedRefsImpl()
		{
			LinkedHashMap<string, Ref> avail = new LinkedHashMap<string, Ref>();
			for (; ; )
			{
				string line;
				try
				{
					line = pckIn.ReadString();
				}
				catch (EOFException eof)
				{
					if (avail.IsEmpty())
					{
						throw NoRepository();
					}
					throw;
				}
				if (line == PacketLineIn.END)
				{
					break;
				}
				if (line.StartsWith("ERR "))
				{
					// This is a customized remote service error.
					// Users should be informed about it.
					throw new RemoteRepositoryException(uri, Sharpen.Runtime.Substring(line, 4));
				}
				if (avail.IsEmpty())
				{
					int nul = line.IndexOf('\0');
					if (nul >= 0)
					{
						// The first line (if any) may contain "hidden"
						// capability values after a NUL byte.
						foreach (string c in Sharpen.Runtime.Substring(line, nul + 1).Split(" "))
						{
							remoteCapablities.AddItem(c);
						}
						line = Sharpen.Runtime.Substring(line, 0, nul);
					}
				}
				string name = Sharpen.Runtime.Substring(line, 41, line.Length);
				if (avail.IsEmpty() && name.Equals("capabilities^{}"))
				{
					// special line from git-receive-pack to show
					// capabilities when there are no refs to advertise
					continue;
				}
				ObjectId id = ObjectId.FromString(Sharpen.Runtime.Substring(line, 0, 40));
				if (name.Equals(".have"))
				{
					additionalHaves.AddItem(id);
				}
				else
				{
					if (name.EndsWith("^{}"))
					{
						name = Sharpen.Runtime.Substring(name, 0, name.Length - 3);
						Ref prior = avail.Get(name);
						if (prior == null)
						{
							throw new PackProtocolException(uri, MessageFormat.Format(JGitText.Get().advertisementCameBefore
								, name, name));
						}
						if (prior.GetPeeledObjectId() != null)
						{
							throw DuplicateAdvertisement(name + "^{}");
						}
						avail.Put(name, new ObjectIdRef.PeeledTag(RefStorage.NETWORK, name, prior.GetObjectId
							(), id));
					}
					else
					{
						Ref prior = avail.Put(name, new ObjectIdRef.PeeledNonTag(RefStorage.NETWORK, name
							, id));
						if (prior != null)
						{
							throw DuplicateAdvertisement(name);
						}
					}
				}
			}
			Available(avail);
		}
Esempio n. 31
0
		private LinkedHashMap GetCalendarExamples(){
			LinkedHashMap calendarExamples = new LinkedHashMap();
			ArrayList result = new ArrayList();

			result.Add (new InitCodeFragment());
			result.Add (new InitXmlFragment());

			calendarExamples.Put ("Init", result);

			result = new ArrayList ();

			result.Add (new DisplayDateSetFragment());
			result.Add (new DisplayDateChangeListenerFragment());
			result.Add (new DisplayDateMinMaxValuesFragment());
			//result.Add (new DisplayDateChangeEventFragment());

			calendarExamples.Put ("Display Date", result);

			result = new ArrayList ();

			result.Add (new DisplayModeFragment());
			result.Add (new DisplayModeChangeListenerFragment());

			calendarExamples.Put ("Display Mode", result);

			result = new ArrayList ();

			result.Add (new EventFragment());
			result.Add (new EventAllDayFragment());
			result.Add (new EventRenderModeFragment());
			result.Add (new ReadEventsFragment());
			//result.Add (new ReadEventsOptionsFragment());
			result.Add (new EventsInlineDisplayModeFragment());
			result.Add (new EventsPopupDisplayModeFragment());

			calendarExamples.Put ("Events", result);

			result = new ArrayList ();

			result.Add (new ScrollingDirectionFragment());
			result.Add (new ScrollingFlingSpeedFragment());
			result.Add (new ScrollingFrictionFragment());
			result.Add (new ScrollingModesFragment());
			result.Add (new ScrollingProgramatticallyFragment());
			result.Add (new ScrollingSnapFragment());

			calendarExamples.Put ("Scrolling", result);

			result = new ArrayList ();

			result.Add (new SelectionChangedListenerFragment());
			//result.Add (new SelectionChangedEventFragment());
			result.Add (new SelectionDecoratorsFragment());
			result.Add (new SelectionDisabledDatesFragment());
			result.Add (new SelectionModesFragment());
			result.Add (new SelectionSetDatesFragment());
			result.Add (new SelectionSetRangeFragment());

			calendarExamples.Put ("Selection", result);

			return calendarExamples;
		}
Esempio n. 32
0
		/// <exception cref="NGit.Errors.TransportException"></exception>
		private void Sendpack(IList<RemoteRefUpdate> updates, ProgressMonitor monitor)
		{
			string pathPack = null;
			string pathIdx = null;
			PackWriter writer = new PackWriter(transport.GetPackConfig(), local.NewObjectReader
				());
			try
			{
				IList<ObjectId> need = new AList<ObjectId>();
				IList<ObjectId> have = new AList<ObjectId>();
				foreach (RemoteRefUpdate r in updates)
				{
					need.AddItem(r.GetNewObjectId());
				}
				foreach (Ref r_1 in GetRefs())
				{
					have.AddItem(r_1.GetObjectId());
					if (r_1.GetPeeledObjectId() != null)
					{
						have.AddItem(r_1.GetPeeledObjectId());
					}
				}
				writer.PreparePack(monitor, need, have);
				// We don't have to continue further if the pack will
				// be an empty pack, as the remote has all objects it
				// needs to complete this change.
				//
				if (writer.GetObjectCount() == 0)
				{
					return;
				}
				packNames = new LinkedHashMap<string, string>();
				foreach (string n in dest.GetPackNames())
				{
					packNames.Put(n, n);
				}
				string @base = "pack-" + writer.ComputeName().Name;
				string packName = @base + ".pack";
				pathPack = "pack/" + packName;
				pathIdx = "pack/" + @base + ".idx";
				if (Sharpen.Collections.Remove(packNames, packName) != null)
				{
					// The remote already contains this pack. We should
					// remove the index before overwriting to prevent bad
					// offsets from appearing to clients.
					//
					dest.WriteInfoPacks(packNames.Keys);
					dest.DeleteFile(pathIdx);
				}
				// Write the pack file, then the index, as readers look the
				// other direction (index, then pack file).
				//
				string wt = "Put " + Sharpen.Runtime.Substring(@base, 0, 12);
				OutputStream os = dest.WriteFile(pathPack, monitor, wt + "..pack");
				try
				{
					os = new BufferedOutputStream(os);
					writer.WritePack(monitor, monitor, os);
				}
				finally
				{
					os.Close();
				}
				os = dest.WriteFile(pathIdx, monitor, wt + "..idx");
				try
				{
					os = new BufferedOutputStream(os);
					writer.WriteIndex(os);
				}
				finally
				{
					os.Close();
				}
				// Record the pack at the start of the pack info list. This
				// way clients are likely to consult the newest pack first,
				// and discover the most recent objects there.
				//
				AList<string> infoPacks = new AList<string>();
				infoPacks.AddItem(packName);
				Sharpen.Collections.AddAll(infoPacks, packNames.Keys);
				dest.WriteInfoPacks(infoPacks);
			}
			catch (IOException err)
			{
				SafeDelete(pathIdx);
				SafeDelete(pathPack);
				throw new TransportException(uri, JGitText.Get().cannotStoreObjects, err);
			}
			finally
			{
				writer.Release();
			}
		}
Esempio n. 33
0
        public static SubordPropPlan GetJoinProps(
            ExprNode filterExpr,
            int outsideStreamCount,
            EventType[] allStreamTypesZeroIndexed,
            ExcludePlanHint excludePlanHint)
        {
            // No filter expression means full table scan
            if (filterExpr == null) {
                return new SubordPropPlan();
            }

            // analyze query graph
            var queryGraph = new QueryGraphForge(outsideStreamCount + 1, excludePlanHint, true);
            FilterExprAnalyzer.Analyze(filterExpr, queryGraph, false);

            // Build a list of streams and indexes
            var joinProps = new LinkedHashMap<string, SubordPropHashKeyForge>();
            var rangeProps = new LinkedHashMap<string, SubordPropRangeKeyForge>();
            IDictionary<QueryGraphValueEntryCustomKeyForge, QueryGraphValueEntryCustomOperationForge> customIndexOps =
                EmptyDictionary<QueryGraphValueEntryCustomKeyForge, QueryGraphValueEntryCustomOperationForge>.Instance;

            for (var stream = 0; stream < outsideStreamCount; stream++) {
                var lookupStream = stream + 1;

                var queryGraphValue = queryGraph.GetGraphValue(lookupStream, 0);
                var hashKeysAndIndexes = queryGraphValue.HashKeyProps;

                // determine application functions
                foreach (var item in queryGraphValue.Items) {
                    if (item.Entry is QueryGraphValueEntryCustomForge) {
                        if (customIndexOps.IsEmpty()) {
                            customIndexOps =
                                new Dictionary<QueryGraphValueEntryCustomKeyForge,
                                    QueryGraphValueEntryCustomOperationForge>();
                        }

                        var custom = (QueryGraphValueEntryCustomForge) item.Entry;
                        custom.MergeInto(customIndexOps);
                    }
                }

                // handle key-lookups
                var keyPropertiesJoin = hashKeysAndIndexes.Keys;
                var indexPropertiesJoin = hashKeysAndIndexes.Indexed;
                if (!keyPropertiesJoin.IsEmpty()) {
                    if (keyPropertiesJoin.Count != indexPropertiesJoin.Length) {
                        throw new IllegalStateException(
                            "Invalid query key and index property collection for stream " + stream);
                    }

                    for (var i = 0; i < keyPropertiesJoin.Count; i++) {
                        QueryGraphValueEntryHashKeyedForge keyDesc = keyPropertiesJoin[i];
                        var compareNode = keyDesc.KeyExpr;

                        var keyPropType = compareNode.Forge.EvaluationType.GetBoxedType();
                        var indexedPropType = allStreamTypesZeroIndexed[0]
                            .GetPropertyType(indexPropertiesJoin[i])
                            .GetBoxedType();
                        var coercionType = indexedPropType;
                        if (keyPropType != indexedPropType) {
                            coercionType = keyPropType.GetCompareToCoercionType(indexedPropType);
                        }

                        SubordPropHashKeyForge desc;
                        if (keyPropertiesJoin[i] is QueryGraphValueEntryHashKeyedForgeExpr) {
                            var keyExpr = (QueryGraphValueEntryHashKeyedForgeExpr) keyPropertiesJoin[i];
                            var keyStreamNum = keyExpr.IsRequiresKey ? (int?) stream : null;
                            desc = new SubordPropHashKeyForge(keyDesc, keyStreamNum, coercionType);
                        }
                        else {
                            var prop = (QueryGraphValueEntryHashKeyedForgeProp) keyDesc;
                            desc = new SubordPropHashKeyForge(prop, stream, coercionType);
                        }

                        joinProps.Put(indexPropertiesJoin[i], desc);
                    }
                }

                // handle range lookups
                var rangeKeysAndIndexes = queryGraphValue.RangeProps;
                var rangeIndexes = rangeKeysAndIndexes.Indexed;
                var rangeDescs = rangeKeysAndIndexes.Keys;
                if (rangeDescs.IsEmpty()) {
                    continue;
                }

                // get all ranges lookups
                var count = -1;
                foreach (var rangeDesc in rangeDescs) {
                    count++;
                    var rangeIndexProp = rangeIndexes[count];

                    var subqRangeDesc = rangeProps.Get(rangeIndexProp);

                    // other streams may specify the start or end endpoint of a range, therefore this operation can be additive
                    if (subqRangeDesc != null) {
                        if (subqRangeDesc.RangeInfo.Type.IsRange()) {
                            continue;
                        }

                        // see if we can make this additive by using a range
                        var relOpOther = (QueryGraphValueEntryRangeRelOpForge) subqRangeDesc.RangeInfo;
                        var relOpThis = (QueryGraphValueEntryRangeRelOpForge) rangeDesc;

                        var opsDesc = QueryGraphRangeUtil.GetCanConsolidate(relOpThis.Type, relOpOther.Type);
                        if (opsDesc != null) {
                            ExprNode start;
                            ExprNode end;
                            if (!opsDesc.IsReverse) {
                                start = relOpOther.Expression;
                                end = relOpThis.Expression;
                            }
                            else {
                                start = relOpThis.Expression;
                                end = relOpOther.Expression;
                            }

                            var allowRangeReversal = relOpOther.IsBetweenPart && relOpThis.IsBetweenPart;
                            var rangeIn = new QueryGraphValueEntryRangeInForge(
                                opsDesc.Type,
                                start,
                                end,
                                allowRangeReversal);

                            var indexedPropType = allStreamTypesZeroIndexed[0]
                                .GetPropertyType(rangeIndexProp)
                                .GetBoxedType();
                            var coercionType = indexedPropType;
                            var proposedType = CoercionUtil.GetCoercionTypeRangeIn(
                                indexedPropType,
                                rangeIn.ExprStart,
                                rangeIn.ExprEnd);
                            if (proposedType != null && proposedType != indexedPropType) {
                                coercionType = proposedType;
                            }

                            subqRangeDesc = new SubordPropRangeKeyForge(rangeIn, coercionType);
                            rangeProps.Put(rangeIndexProp, subqRangeDesc);
                        }

                        // ignore
                        continue;
                    }

                    // an existing entry has not been found
                    if (rangeDesc.Type.IsRange()) {
                        var rangeIn = (QueryGraphValueEntryRangeInForge) rangeDesc;
                        var indexedPropType =
                            allStreamTypesZeroIndexed[0].GetPropertyType(rangeIndexProp).GetBoxedType();
                        var coercionType = indexedPropType;
                        var proposedType = CoercionUtil.GetCoercionTypeRangeIn(
                            indexedPropType,
                            rangeIn.ExprStart,
                            rangeIn.ExprEnd);
                        if (proposedType != null && proposedType != indexedPropType) {
                            coercionType = proposedType;
                        }

                        subqRangeDesc = new SubordPropRangeKeyForge(rangeDesc, coercionType);
                    }
                    else {
                        var relOp = (QueryGraphValueEntryRangeRelOpForge) rangeDesc;
                        var keyPropType = relOp.Expression.Forge.EvaluationType;
                        var indexedPropType =
                            allStreamTypesZeroIndexed[0].GetPropertyType(rangeIndexProp).GetBoxedType();
                        var coercionType = indexedPropType;
                        if (keyPropType != indexedPropType) {
                            coercionType = keyPropType.GetCompareToCoercionType(indexedPropType);
                        }

                        subqRangeDesc = new SubordPropRangeKeyForge(rangeDesc, coercionType);
                    }

                    rangeProps.Put(rangeIndexProp, subqRangeDesc);
                }
            }

            SubordPropInKeywordSingleIndex inKeywordSingleIdxProp = null;
            SubordPropInKeywordMultiIndex inKeywordMultiIdxProp = null;
            if (joinProps.IsEmpty() && rangeProps.IsEmpty()) {
                for (var stream = 0; stream < outsideStreamCount; stream++) {
                    var lookupStream = stream + 1;
                    var queryGraphValue = queryGraph.GetGraphValue(lookupStream, 0);

                    var inkwSingles = queryGraphValue.InKeywordSingles;
                    if (inkwSingles.Indexed.Length != 0) {
                        ExprNode[] keys = inkwSingles.Key[0].KeyExprs;
                        var key = inkwSingles.Indexed[0];
                        if (inKeywordSingleIdxProp != null) {
                            continue;
                        }

                        var coercionType = keys[0].Forge.EvaluationType; // for in-comparison the same type is required
                        inKeywordSingleIdxProp = new SubordPropInKeywordSingleIndex(key, coercionType, keys);
                    }

                    var inkwMultis = queryGraphValue.InKeywordMulti;
                    if (!inkwMultis.IsEmpty()) {
                        QueryGraphValuePairInKWMultiIdx multi = inkwMultis[0];
                        inKeywordMultiIdxProp = new SubordPropInKeywordMultiIndex(
                            ExprNodeUtilityQuery.GetIdentResolvedPropertyNames(multi.Indexed),
                            multi.Indexed[0].Forge.EvaluationType,
                            multi.Key.KeyExpr);
                    }

                    if (inKeywordSingleIdxProp != null && inKeywordMultiIdxProp != null) {
                        inKeywordMultiIdxProp = null;
                    }
                }
            }

            return new SubordPropPlan(
                joinProps,
                rangeProps,
                inKeywordSingleIdxProp,
                inKeywordMultiIdxProp,
                customIndexOps);
        }
Esempio n. 34
0
        private void RunAssertionMapAndNestedArray(EPServiceProvider epService)
        {
            var defOuter = new LinkedHashMap <string, Object>();

            defOuter.Put("intarr", typeof(int[]));
            defOuter.Put("innersimple", "InnerMap");
            defOuter.Put("innerarray", "InnerMap[]");
            defOuter.Put("prop0", typeof(SupportBean_A));

            var defInner = new LinkedHashMap <string, Object>();

            defInner.Put("stringarr", typeof(string[]));
            defInner.Put("prop1", typeof(string));

            epService.EPAdministrator.Configuration.AddEventType("InnerMap", defInner);
            epService.EPAdministrator.Configuration.AddEventType("OuterMap", defOuter);
            EPStatement statement = epService.EPAdministrator.CreateEPL("select * from OuterMap");

            var dataInner = new LinkedHashMap <string, Object>();

            dataInner.Put("stringarr", new string[] { "a", "b" });
            dataInner.Put("prop1", "");
            var dataInnerTwo = new LinkedHashMap <string, Object>();

            dataInnerTwo.Put("stringarr", new string[0]);
            dataInnerTwo.Put("prop1", "abcdef");
            var dataOuter = new LinkedHashMap <string, Object>();

            dataOuter.Put("intarr", new int[] { 1, 2 });
            dataOuter.Put("innersimple", dataInner);
            dataOuter.Put("innerarray", new Map[] { dataInner, dataInnerTwo });
            dataOuter.Put("prop0", new SupportBean_A("A1"));
            epService.EPRuntime.SendEvent(dataOuter, "OuterMap");

            string result = epService.EPRuntime.EventRenderer.RenderJSON("outerMap", statement.First());

            //Log.Info(result);
            string expected = "{\n" +
                              "  \"outerMap\": {\n" +
                              "    \"innerarray\": [{\n" +
                              "        \"prop1\": \"\",\n" +
                              "        \"stringarr\": [\"a\", \"b\"]\n" +
                              "      },\n" +
                              "      {\n" +
                              "        \"prop1\": \"abcdef\",\n" +
                              "        \"stringarr\": []\n" +
                              "      }],\n" +
                              "    \"innersimple\": {\n" +
                              "      \"prop1\": \"\",\n" +
                              "      \"stringarr\": [\"a\", \"b\"]\n" +
                              "    },\n" +
                              "    \"intarr\": [1, 2],\n" +
                              "    \"prop0\": {\n" +
                              "      \"Id\": \"A1\"\n" +
                              "    }\n" +
                              "  }\n" +
                              "}";

            Assert.AreEqual(RemoveNewline(expected), RemoveNewline(result));

            statement.Dispose();
        }
		/// <exception cref="System.Exception"></exception>
		private IDictionary<string, DirCacheCGitCompatabilityTest.CGitLsTreeRecord> ReadLsTree
			()
		{
			LinkedHashMap<string, DirCacheCGitCompatabilityTest.CGitLsTreeRecord> r = new LinkedHashMap
				<string, DirCacheCGitCompatabilityTest.CGitLsTreeRecord>();
			BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(
				PathOf("gitgit.lstree")), "UTF-8"));
			try
			{
				string line;
				while ((line = br.ReadLine()) != null)
				{
					DirCacheCGitCompatabilityTest.CGitLsTreeRecord cr = new DirCacheCGitCompatabilityTest.CGitLsTreeRecord
						(line);
					r.Put(cr.path, cr);
				}
			}
			finally
			{
				br.Close();
			}
			return r;
		}
Esempio n. 36
0
        /// <exception cref="System.IO.IOException"></exception>
        private IDictionary <string, OpenSshConfig.Host> Parse(InputStream @in)
        {
            IDictionary <string, OpenSshConfig.Host> m = new LinkedHashMap <string, OpenSshConfig.Host
                                                                            >();
            BufferedReader             br      = new BufferedReader(new InputStreamReader(@in));
            IList <OpenSshConfig.Host> current = new AList <OpenSshConfig.Host>(4);
            string line;

            while ((line = br.ReadLine()) != null)
            {
                line = line.Trim();
                if (line.Length == 0 || line.StartsWith("#"))
                {
                    continue;
                }
                string[] parts    = line.Split("[ \t]*[= \t]", 2);
                string   keyword  = parts[0].Trim();
                string   argValue = parts[1].Trim();
                if (StringUtils.EqualsIgnoreCase("Host", keyword))
                {
                    current.Clear();
                    foreach (string pattern in argValue.Split("[ \t]"))
                    {
                        string             name = Dequote(pattern);
                        OpenSshConfig.Host c    = m.Get(name);
                        if (c == null)
                        {
                            c = new OpenSshConfig.Host();
                            m.Put(name, c);
                        }
                        current.AddItem(c);
                    }
                    continue;
                }
                if (current.IsEmpty())
                {
                    // We received an option outside of a Host block. We
                    // don't know who this should match against, so skip.
                    //
                    continue;
                }
                if (StringUtils.EqualsIgnoreCase("HostName", keyword))
                {
                    foreach (OpenSshConfig.Host c in current)
                    {
                        if (c.hostName == null)
                        {
                            c.hostName = Dequote(argValue);
                        }
                    }
                }
                else
                {
                    if (StringUtils.EqualsIgnoreCase("User", keyword))
                    {
                        foreach (OpenSshConfig.Host c in current)
                        {
                            if (c.user == null)
                            {
                                c.user = Dequote(argValue);
                            }
                        }
                    }
                    else
                    {
                        if (StringUtils.EqualsIgnoreCase("Port", keyword))
                        {
                            try
                            {
                                int port = System.Convert.ToInt32(Dequote(argValue));
                                foreach (OpenSshConfig.Host c in current)
                                {
                                    if (c.port == 0)
                                    {
                                        c.port = port;
                                    }
                                }
                            }
                            catch (FormatException)
                            {
                            }
                        }
                        else
                        {
                            // Bad port number. Don't set it.
                            if (StringUtils.EqualsIgnoreCase("IdentityFile", keyword))
                            {
                                foreach (OpenSshConfig.Host c in current)
                                {
                                    if (c.identityFile == null)
                                    {
                                        c.identityFile = ToFile(Dequote(argValue));
                                    }
                                }
                            }
                            else
                            {
                                if (StringUtils.EqualsIgnoreCase("PreferredAuthentications", keyword))
                                {
                                    foreach (OpenSshConfig.Host c in current)
                                    {
                                        if (c.preferredAuthentications == null)
                                        {
                                            c.preferredAuthentications = Nows(Dequote(argValue));
                                        }
                                    }
                                }
                                else
                                {
                                    if (StringUtils.EqualsIgnoreCase("BatchMode", keyword))
                                    {
                                        foreach (OpenSshConfig.Host c in current)
                                        {
                                            if (c.batchMode == null)
                                            {
                                                c.batchMode = Yesno(Dequote(argValue));
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (StringUtils.EqualsIgnoreCase("StrictHostKeyChecking", keyword))
                                        {
                                            string value = Dequote(argValue);
                                            foreach (OpenSshConfig.Host c in current)
                                            {
                                                if (c.strictHostKeyChecking == null)
                                                {
                                                    c.strictHostKeyChecking = value;
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return(m);
        }
        private void doTest(SpatialOperation operation)
        {
            //first show that when there's no data, a query will result in no results
            {
                Query query = strategy.MakeQuery(new SpatialArgs(operation, randomRectangle()));
                SearchResults searchResults = executeQuery(query, 1);
                assertEquals(0, searchResults.numFound);
            }

            bool biasContains = (operation == SpatialOperation.Contains);

            //Main index loop:
            IDictionary<String, IShape> indexedShapes = new LinkedHashMap<String, IShape>();
            IDictionary<String, IShape> indexedShapesGS = new LinkedHashMap<String, IShape>();//grid snapped
            int numIndexedShapes = randomIntBetween(1, 6);
            bool indexedAtLeastOneShapePair = false;
            for (int i = 0; i < numIndexedShapes; i++)
            {
                String id = "" + i;
                IShape indexedShape;
                int R = Random().nextInt(12);
                if (R == 0)
                {//1 in 12
                    indexedShape = null;
                }
                else if (R == 1)
                {//1 in 12
                    indexedShape = randomPoint();//just one point
                }
                else if (R <= 4)
                {//3 in 12
                 //comprised of more than one shape
                    indexedShape = randomShapePairRect(biasContains);
                    indexedAtLeastOneShapePair = true;
                }
                else
                {
                    indexedShape = randomRectangle();//just one rect
                }

                indexedShapes.Put(id, indexedShape);
                indexedShapesGS.Put(id, gridSnap(indexedShape));

                adoc(id, indexedShape);

                if (Random().nextInt(10) == 0)
                    Commit();//intermediate commit, produces extra segments

            }
            //delete some documents randomly
            IEnumerator<String> idIter = indexedShapes.Keys.ToList().GetEnumerator();
            while (idIter.MoveNext())
            {
                String id = idIter.Current;
                if (Random().nextInt(10) == 0)
                {
                    DeleteDoc(id);
                    //idIter.Remove();
                    indexedShapes.Remove(id); // LUCENENET TODO: Verify this works.
                    indexedShapesGS.Remove(id);
                }
            }

            Commit();

            //Main query loop:
            int numQueryShapes = AtLeast(20);
            for (int i = 0; i < numQueryShapes; i++)
            {
                int scanLevel = randomInt(grid.MaxLevels);
                ((RecursivePrefixTreeStrategy)strategy).PrefixGridScanLevel = (scanLevel);

                IShape queryShape;
                switch (randomInt(10))
                {
                    case 0: queryShape = randomPoint(); break;
                    // LUCENE-5549
                    //TODO debug: -Dtests.method=testWithin -Dtests.multiplier=3 -Dtests.seed=5F5294CE2E075A3E:AAD2F0F79288CA64
                    //        case 1:case 2:case 3:
                    //          if (!indexedAtLeastOneShapePair) { // avoids ShapePair.relate(ShapePair), which isn't reliable
                    //            queryShape = randomShapePairRect(!biasContains);//invert biasContains for query side
                    //            break;
                    //          }
                    default: queryShape = randomRectangle(); break;
                }
                IShape queryShapeGS = gridSnap(queryShape);

                bool opIsDisjoint = operation == SpatialOperation.IsDisjointTo;

                //Generate truth via brute force:
                // We ensure true-positive matches (if the predicate on the raw shapes match
                //  then the search should find those same matches).
                // approximations, false-positive matches
                ISet<String> expectedIds = new /* LinkedHashSet<string>*/ HashSet<string>();//true-positives
                ISet<String> secondaryIds = new /* LinkedHashSet<string>*/ HashSet<string>();//false-positives (unless disjoint)
                foreach (var entry in indexedShapes)
                {
                    String id = entry.Key;
                    IShape indexedShapeCompare = entry.Value;
                    if (indexedShapeCompare == null)
                        continue;
                    IShape queryShapeCompare = queryShape;

                    if (operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                    {
                        expectedIds.add(id);
                        if (opIsDisjoint)
                        {
                            //if no longer intersect after buffering them, for disjoint, remember this
                            indexedShapeCompare = indexedShapesGS[id];
                            queryShapeCompare = queryShapeGS;
                            if (!operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                                secondaryIds.add(id);
                        }
                    }
                    else if (!opIsDisjoint)
                    {
                        //buffer either the indexed or query shape (via gridSnap) and try again
                        if (operation == SpatialOperation.Intersects)
                        {
                            indexedShapeCompare = indexedShapesGS[id];
                            queryShapeCompare = queryShapeGS;
                            //TODO Unfortunately, grid-snapping both can result in intersections that otherwise
                            // wouldn't happen when the grids are adjacent. Not a big deal but our test is just a
                            // bit more lenient.
                        }
                        else if (operation == SpatialOperation.Contains)
                        {
                            indexedShapeCompare = indexedShapesGS[id];
                        }
                        else if (operation == SpatialOperation.IsWithin)
                        {
                            queryShapeCompare = queryShapeGS;
                        }
                        if (operation.Evaluate(indexedShapeCompare, queryShapeCompare))
                            secondaryIds.add(id);
                    }
                }

                //Search and verify results
                SpatialArgs args = new SpatialArgs(operation, queryShape);
                if (queryShape is ShapePair)
                    args.DistErrPct = (0.0);//a hack; we want to be more detailed than gridSnap(queryShape)
                Query query = strategy.MakeQuery(args);
                SearchResults got = executeQuery(query, 100);
                ISet<String> remainingExpectedIds = new /* LinkedHashSet<string>*/ HashSet<string>(expectedIds);
                foreach (SearchResult result in got.results)
                {
                    String id = result.GetId();
                    bool removed = remainingExpectedIds.remove(id);
                    if (!removed && (!opIsDisjoint && !secondaryIds.contains(id)))
                    {
                        fail("Shouldn't match", id, indexedShapes, indexedShapesGS, queryShape);
                    }
                }
                if (opIsDisjoint)
                    remainingExpectedIds.removeAll(secondaryIds);
                if (remainingExpectedIds.Any())
                {
                    var iter = remainingExpectedIds.GetEnumerator();
                    iter.MoveNext();
                    String id = iter.Current;
                    fail("Should have matched", id, indexedShapes, indexedShapesGS, queryShape);
                }
            }
        }
Esempio n. 38
0
        private static void RecursiveCompile(
            EvalFactoryNode evalNode,
            StatementContext context,
            ExprEvaluatorContext evaluatorContext,
            ICollection <string> eventTypeReferences,
            bool isInsertInto,
            MatchEventSpec tags,
            Deque <int> subexpressionIdStack,
            Stack <EvalFactoryNode> parentNodeStack,
            ICollection <string> allTagNamesOrdered)
        {
            var counter = 0;

            parentNodeStack.Push(evalNode);
            foreach (var child in evalNode.ChildNodes)
            {
                subexpressionIdStack.AddLast(counter++);
                RecursiveCompile(
                    child, context, evaluatorContext, eventTypeReferences, isInsertInto, tags, subexpressionIdStack,
                    parentNodeStack, allTagNamesOrdered);
                subexpressionIdStack.RemoveLast();
            }
            parentNodeStack.Pop();

            LinkedHashMap <string, Pair <EventType, string> > newTaggedEventTypes = null;
            LinkedHashMap <string, Pair <EventType, string> > newArrayEventTypes  = null;

            if (evalNode is EvalFilterFactoryNode)
            {
                var filterNode = (EvalFilterFactoryNode)evalNode;
                var eventName  = filterNode.RawFilterSpec.EventTypeName;
                if (context.TableService.GetTableMetadata(eventName) != null)
                {
                    throw new ExprValidationException("Tables cannot be used in pattern filter atoms");
                }

                var resolvedEventType = FilterStreamSpecRaw.ResolveType(
                    context.EngineURI, eventName, context.EventAdapterService, context.PlugInTypeResolutionURIs);
                var finalEventType       = resolvedEventType;
                var optionalTag          = filterNode.EventAsName;
                var isPropertyEvaluation = false;
                var isParentMatchUntil   = IsParentMatchUntil(evalNode, parentNodeStack);

                // obtain property event type, if final event type is properties
                if (filterNode.RawFilterSpec.OptionalPropertyEvalSpec != null)
                {
                    var optionalPropertyEvaluator =
                        PropertyEvaluatorFactory.MakeEvaluator(
                            context.Container,
                            filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                            resolvedEventType,
                            filterNode.EventAsName,
                            context.EventAdapterService,
                            context.EngineImportService,
                            context.SchedulingService,
                            context.VariableService,
                            context.ScriptingService,
                            context.TableService,
                            context.EngineURI,
                            context.StatementId,
                            context.StatementName,
                            context.Annotations,
                            subexpressionIdStack,
                            context.ConfigSnapshot,
                            context.NamedWindowMgmtService,
                            context.StatementExtensionServicesContext);
                    finalEventType       = optionalPropertyEvaluator.FragmentEventType;
                    isPropertyEvaluation = true;
                }

                if (finalEventType is EventTypeSPI)
                {
                    eventTypeReferences.Add(((EventTypeSPI)finalEventType).Metadata.PrimaryName);
                }

                // If a tag was supplied for the type, the tags must stay with this type, i.e. a=BeanA -> b=BeanA -> a=BeanB is a no
                if (optionalTag != null)
                {
                    var       pair         = tags.TaggedEventTypes.Get(optionalTag);
                    EventType existingType = null;
                    if (pair != null)
                    {
                        existingType = pair.First;
                    }
                    if (existingType == null)
                    {
                        pair = tags.ArrayEventTypes.Get(optionalTag);
                        if (pair != null)
                        {
                            throw new ExprValidationException(
                                      "Tag '" + optionalTag + "' for event '" + eventName +
                                      "' used in the repeat-until operator cannot also appear in other filter expressions");
                        }
                    }
                    if ((existingType != null) && (existingType != finalEventType))
                    {
                        throw new ExprValidationException(
                                  "Tag '" + optionalTag + "' for event '" + eventName +
                                  "' has already been declared for events of type " + existingType.UnderlyingType.FullName);
                    }
                    pair = new Pair <EventType, string>(finalEventType, eventName);

                    // add tagged type
                    if (isPropertyEvaluation || isParentMatchUntil)
                    {
                        newArrayEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newArrayEventTypes.Put(optionalTag, pair);
                    }
                    else
                    {
                        newTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                        newTaggedEventTypes.Put(optionalTag, pair);
                    }
                }

                // For this filter, filter types are all known tags at this time,
                // and additionally stream 0 (self) is our event type.
                // Stream type service allows resolution by property name event if that name appears in other tags.
                // by defaulting to stream zero.
                // Stream zero is always the current event type, all others follow the order of the map (stream 1 to N).
                var selfStreamName = optionalTag;
                if (selfStreamName == null)
                {
                    selfStreamName = "s_" + UuidGenerator.Generate();
                }
                var filterTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                var typePair    = new Pair <EventType, string>(finalEventType, eventName);
                filterTypes.Put(selfStreamName, typePair);
                filterTypes.PutAll(tags.TaggedEventTypes);

                // for the filter, specify all tags used
                var filterTaggedEventTypes = new LinkedHashMap <string, Pair <EventType, string> >(tags.TaggedEventTypes);
                filterTaggedEventTypes.Remove(optionalTag);

                // handle array tags (match-until clause)
                LinkedHashMap <string, Pair <EventType, string> > arrayCompositeEventTypes = null;
                if (tags.ArrayEventTypes != null && !tags.ArrayEventTypes.IsEmpty())
                {
                    arrayCompositeEventTypes = new LinkedHashMap <string, Pair <EventType, string> >();
                    var patternSubexEventType = GetPatternSubexEventType(
                        context.StatementId, "pattern", subexpressionIdStack);

                    foreach (var entry in tags.ArrayEventTypes)
                    {
                        var specificArrayType = new LinkedHashMap <string, Pair <EventType, string> >();
                        specificArrayType.Put(entry.Key, entry.Value);
                        var arrayTagCompositeEventType =
                            context.EventAdapterService.CreateSemiAnonymousMapType(
                                patternSubexEventType, Collections.GetEmptyMap <string, Pair <EventType, string> >(),
                                specificArrayType, isInsertInto);
                        context.StatementSemiAnonymousTypeRegistry.Register(arrayTagCompositeEventType);

                        var tag = entry.Key;
                        if (!filterTypes.ContainsKey(tag))
                        {
                            var pair = new Pair <EventType, string>(arrayTagCompositeEventType, tag);
                            filterTypes.Put(tag, pair);
                            arrayCompositeEventTypes.Put(tag, pair);
                        }
                    }
                }

                StreamTypeService streamTypeService = new StreamTypeServiceImpl(
                    filterTypes, context.EngineURI, true, false);
                var exprNodes = filterNode.RawFilterSpec.FilterExpressions;

                var spec = FilterSpecCompiler.MakeFilterSpec(
                    resolvedEventType, eventName, exprNodes,
                    filterNode.RawFilterSpec.OptionalPropertyEvalSpec,
                    filterTaggedEventTypes,
                    arrayCompositeEventTypes,
                    streamTypeService,
                    null, context, subexpressionIdStack);
                filterNode.FilterSpec = spec;
            }
            else if (evalNode is EvalObserverFactoryNode)
            {
                var observerNode = (EvalObserverFactoryNode)evalNode;
                try
                {
                    var observerFactory = context.PatternResolutionService.Create(observerNode.PatternObserverSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "observer", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNOBSERVER, observerNode.PatternObserverSpec.ObjectParameters,
                        validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    observerNode.ObserverFactory = observerFactory;
                    observerFactory.SetObserverParameters(validated, convertor, validationContext);
                }
                catch (ObserverParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " +
                              e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern observer '" + observerNode.ToPrecedenceFreeEPL() + "': " + e.Message,
                              e);
                }
            }
            else if (evalNode is EvalGuardFactoryNode)
            {
                var guardNode = (EvalGuardFactoryNode)evalNode;
                try
                {
                    var guardFactory = context.PatternResolutionService.Create(guardNode.PatternGuardSpec);

                    var streamTypeService = GetStreamTypeService(
                        context.EngineURI, context.StatementId, context.EventAdapterService, tags.TaggedEventTypes,
                        tags.ArrayEventTypes, subexpressionIdStack, "guard", context);
                    var validationContext = new ExprValidationContext(
                        context.Container,
                        streamTypeService,
                        context.EngineImportService,
                        context.StatementExtensionServicesContext, null,
                        context.SchedulingService,
                        context.VariableService,
                        context.TableService, evaluatorContext,
                        context.EventAdapterService,
                        context.StatementName,
                        context.StatementId,
                        context.Annotations,
                        context.ContextDescriptor,
                        context.ScriptingService,
                        false, false, false, false, null, false);
                    var validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNGUARD, guardNode.PatternGuardSpec.ObjectParameters, validationContext);

                    MatchedEventConvertor convertor = new MatchedEventConvertorImpl(
                        tags.TaggedEventTypes, tags.ArrayEventTypes, allTagNamesOrdered, context.EventAdapterService);

                    guardNode.GuardFactory = guardFactory;
                    guardFactory.SetGuardParameters(validated, convertor);
                }
                catch (GuardParameterException e)
                {
                    throw new ExprValidationException(
                              "Invalid parameter for pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
                catch (PatternObjectException e)
                {
                    throw new ExprValidationException(
                              "Failed to resolve pattern guard '" + guardNode.ToPrecedenceFreeEPL() + "': " + e.Message, e);
                }
            }
            else if (evalNode is EvalEveryDistinctFactoryNode)
            {
                var distinctNode             = (EvalEveryDistinctFactoryNode)evalNode;
                var matchEventFromChildNodes = AnalyzeMatchEvent(distinctNode);
                var streamTypeService        = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                    subexpressionIdStack, "every-distinct", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);
                IList <ExprNode> validated;
                try
                {
                    validated = ValidateExpressions(
                        ExprNodeOrigin.PATTERNEVERYDISTINCT, distinctNode.Expressions, validationContext);
                }
                catch (ExprValidationPropertyException ex)
                {
                    throw new ExprValidationPropertyException(
                              ex.Message +
                              ", every-distinct requires that all properties resolve from sub-expressions to the every-distinct",
                              ex.InnerException);
                }

                MatchedEventConvertor convertor =
                    new MatchedEventConvertorImpl(
                        matchEventFromChildNodes.TaggedEventTypes, matchEventFromChildNodes.ArrayEventTypes,
                        allTagNamesOrdered, context.EventAdapterService);

                distinctNode.Convertor = convertor;

                // Determine whether some expressions are constants or time period
                IList <ExprNode>             distinctExpressions  = new List <ExprNode>();
                ExprTimePeriodEvalDeltaConst timeDeltaComputation = null;
                ExprNode expiryTimeExp = null;
                var      count         = -1;
                var      last          = validated.Count - 1;
                foreach (var expr in validated)
                {
                    count++;
                    if (count == last && expr is ExprTimePeriod)
                    {
                        expiryTimeExp = expr;
                        var timePeriodExpr = (ExprTimePeriod)expiryTimeExp;
                        timeDeltaComputation =
                            timePeriodExpr.ConstEvaluator(new ExprEvaluatorContextStatement(context, false));
                    }
                    else if (expr.IsConstantResult)
                    {
                        if (count == last)
                        {
                            var evaluateParams = new EvaluateParams(null, true, evaluatorContext);
                            var value          = expr.ExprEvaluator.Evaluate(evaluateParams);
                            if (!(value.IsNumber()))
                            {
                                throw new ExprValidationException(
                                          "Invalid parameter for every-distinct, expected number of seconds constant (constant not considered for distinct)");
                            }

                            var secondsExpire = expr.ExprEvaluator.Evaluate(evaluateParams);

                            long?timeExpire;
                            if (secondsExpire == null)
                            {
                                timeExpire = null;
                            }
                            else
                            {
                                timeExpire = context.TimeAbacus.DeltaForSecondsNumber(secondsExpire);
                            }

                            if (timeExpire != null && timeExpire > 0)
                            {
                                timeDeltaComputation = new ExprTimePeriodEvalDeltaConstGivenDelta(timeExpire.Value);
                                expiryTimeExp        = expr;
                            }
                            else
                            {
                                Log.Warn("Invalid seconds-expire " + timeExpire + " for " + ExprNodeUtility.ToExpressionStringMinPrecedenceSafe(expr));
                            }
                        }
                        else
                        {
                            Log.Warn(
                                "Every-distinct node utilizes an expression returning a constant value, please check expression '{0}', not adding expression to distinct-value expression list",
                                expr.ToExpressionStringMinPrecedenceSafe());
                        }
                    }
                    else
                    {
                        distinctExpressions.Add(expr);
                    }
                }
                if (distinctExpressions.IsEmpty())
                {
                    throw new ExprValidationException(
                              "Every-distinct node requires one or more distinct-value expressions that each return non-constant result values");
                }
                distinctNode.SetDistinctExpressions(distinctExpressions, timeDeltaComputation, expiryTimeExp);
            }
            else if (evalNode is EvalMatchUntilFactoryNode)
            {
                var matchUntilNode = (EvalMatchUntilFactoryNode)evalNode;

                // compile bounds expressions, if any
                var untilMatchEventSpec = new MatchEventSpec(tags.TaggedEventTypes, tags.ArrayEventTypes);
                var streamTypeService   = GetStreamTypeService(
                    context.EngineURI, context.StatementId, context.EventAdapterService,
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, subexpressionIdStack,
                    "until", context);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService, evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                var lower = ValidateBounds(matchUntilNode.LowerBounds, validationContext);
                matchUntilNode.LowerBounds = lower;

                var upper = ValidateBounds(matchUntilNode.UpperBounds, validationContext);
                matchUntilNode.UpperBounds = upper;

                var single = ValidateBounds(matchUntilNode.SingleBound, validationContext);
                matchUntilNode.SingleBound = single;

                var convertor = new MatchedEventConvertorImpl(
                    untilMatchEventSpec.TaggedEventTypes, untilMatchEventSpec.ArrayEventTypes, allTagNamesOrdered,
                    context.EventAdapterService);
                matchUntilNode.Convertor = convertor;

                // compile new tag lists
                ISet <string> arrayTags = null;
                var           matchUntilAnalysisResult = EvalNodeUtil.RecursiveAnalyzeChildNodes(matchUntilNode.ChildNodes[0]);
                foreach (var filterNode in matchUntilAnalysisResult.FilterNodes)
                {
                    var optionalTag = filterNode.EventAsName;
                    if (optionalTag != null)
                    {
                        if (arrayTags == null)
                        {
                            arrayTags = new HashSet <string>();
                        }
                        arrayTags.Add(optionalTag);
                    }
                }

                if (arrayTags != null)
                {
                    foreach (var arrayTag in arrayTags)
                    {
                        if (!tags.ArrayEventTypes.ContainsKey(arrayTag))
                        {
                            tags.ArrayEventTypes.Put(arrayTag, tags.TaggedEventTypes.Get(arrayTag));
                            tags.TaggedEventTypes.Remove(arrayTag);
                        }
                    }
                }
                matchUntilNode.TagsArrayed = GetIndexesForTags(allTagNamesOrdered, arrayTags);
            }
            else if (evalNode is EvalFollowedByFactoryNode)
            {
                var followedByNode = (EvalFollowedByFactoryNode)evalNode;
                StreamTypeService streamTypeService = new StreamTypeServiceImpl(context.EngineURI, false);
                var validationContext = new ExprValidationContext(
                    context.Container,
                    streamTypeService,
                    context.EngineImportService,
                    context.StatementExtensionServicesContext, null,
                    context.SchedulingService,
                    context.VariableService,
                    context.TableService,
                    evaluatorContext,
                    context.EventAdapterService,
                    context.StatementName,
                    context.StatementId,
                    context.Annotations,
                    context.ContextDescriptor,
                    context.ScriptingService,
                    false, false, false, false, null, false);

                if (followedByNode.OptionalMaxExpressions != null)
                {
                    IList <ExprNode> validated = new List <ExprNode>();
                    foreach (var maxExpr in followedByNode.OptionalMaxExpressions)
                    {
                        if (maxExpr == null)
                        {
                            validated.Add(null);
                        }
                        else
                        {
                            var visitor = new ExprNodeSummaryVisitor();
                            maxExpr.Accept(visitor);
                            if (!visitor.IsPlain)
                            {
                                var errorMessage = "Invalid maximum expression in followed-by, " + visitor.GetMessage() +
                                                   " are not allowed within the expression";
                                Log.Error(errorMessage);
                                throw new ExprValidationException(errorMessage);
                            }

                            var validatedExpr = ExprNodeUtility.GetValidatedSubtree(
                                ExprNodeOrigin.FOLLOWEDBYMAX, maxExpr, validationContext);
                            validated.Add(validatedExpr);
                            if ((validatedExpr.ExprEvaluator.ReturnType == null) ||
                                (!validatedExpr.ExprEvaluator.ReturnType.IsNumeric()))
                            {
                                var message = "Invalid maximum expression in followed-by, the expression must return an integer value";
                                throw new ExprValidationException(message);
                            }
                        }
                    }
                    followedByNode.OptionalMaxExpressions = validated;
                }
            }

            if (newTaggedEventTypes != null)
            {
                tags.TaggedEventTypes.PutAll(newTaggedEventTypes);
            }
            if (newArrayEventTypes != null)
            {
                tags.ArrayEventTypes.PutAll(newArrayEventTypes);
            }
        }
        public static StreamTypeService BuildDefineStreamTypeServiceDefine(
            StatementContext statementContext,
            LinkedHashMap <String, Pair <int, bool> > variableStreams,
            MatchRecognizeDefineItem defineItem,
            IDictionary <String, ISet <String> > visibilityByIdentifier,
            EventType parentViewType)
        {
            if (!variableStreams.ContainsKey(defineItem.Identifier))
            {
                throw new ExprValidationException("Variable '" + defineItem.Identifier + "' does not occur in pattern");
            }

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

            CompatExtensions.Fill(isIStreamOnly, true);

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

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

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

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

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

            return(new StreamTypeServiceImpl(
                       typesDefine, streamNamesDefine, isIStreamOnly, statementContext.EngineURI, false));
        }
Esempio n. 40
0
        public void Run(RegressionEnvironment env)
        {
            // Bean
            BiConsumer <EventType, Nullable2Lvl> bean = (
                type,
                val) => {
                LocalEvent @event;
                if (val.IsNullAtRoot)
                {
                    @event = new LocalEvent();
                }
                else if (val.IsNullAtInner)
                {
                    @event = new LocalEventSubA(new LocalInnerEvent(null));
                }
                else
                {
                    @event = new LocalEventSubA(new LocalInnerEvent(new LocalLeafEvent(val.Id)));
                }

                env.SendEventBean(@event, "LocalEvent");
            };
            var beanepl = "@public @buseventtype create schema LocalEvent as " +
                          typeof(EventInfraGetterDynamicNested.LocalEvent).MaskTypeName() +
                          ";\n" +
                          "@public @buseventtype create schema LocalEventSubA as " +
                          typeof(EventInfraGetterDynamicNested.LocalEventSubA).MaskTypeName() +
                          ";\n";

            RunAssertion(env, beanepl, bean);

            // Map
            BiConsumer <EventType, Nullable2Lvl> map = (
                type,
                val) => {
                IDictionary <string, object> @event = new LinkedHashMap <string, object>();
                if (val.IsNullAtRoot)
                {
                    // no change
                }
                else if (val.IsNullAtInner)
                {
                    var inner = Collections.SingletonDataMap("Leaf", null);
                    @event.Put("Property", inner);
                }
                else
                {
                    var leaf  = Collections.SingletonDataMap("Id", val.Id);
                    var inner = Collections.SingletonDataMap("Leaf", leaf);
                    @event.Put("Property", inner);
                }

                env.SendEventMap(@event, "LocalEvent");
            };

            RunAssertion(env, GetEpl("map"), map);

            // Object-array
            RunAssertion(env, GetEpl("objectarray"), null);

            // Json
            BiConsumer <EventType, Nullable2Lvl> json = (
                type,
                val) => {
                var @event = new JObject();
                if (val.IsNullAtRoot)
                {
                    // no change
                }
                else if (val.IsNullAtInner)
                {
                    @event.Add("Property", new JObject(new JProperty("Leaf", null)));
                }
                else
                {
                    var leaf  = new JObject(new JProperty("Id", val.Id));
                    var inner = new JObject(new JProperty("Leaf", leaf));
                    @event.Add("Property", inner);
                }

                env.SendEventJson(@event.ToString(), "LocalEvent");
            };

            RunAssertion(env, GetEpl("json"), json);

            // Json-Class-Provided
            var eplJsonProvided = "@JsonSchema(ClassName='" +
                                  typeof(MyLocalJsonProvided).MaskTypeName() +
                                  "') @public @buseventtype create json schema LocalEvent();\n";

            RunAssertion(env, eplJsonProvided, json);

            // Avro
            BiConsumer <EventType, Nullable2Lvl> avro = (
                type,
                val) => {
                var           emptySchema = SchemaBuilder.Record("empty");
                GenericRecord @event;
                if (val.IsNullAtRoot)
                {
                    @event = new GenericRecord(emptySchema);
                }
                else if (val.IsNullAtInner)
                {
                    var inner     = new GenericRecord(emptySchema);
                    var topSchema = SchemaBuilder.Record("name", TypeBuilder.Field("Property", emptySchema));
                    @event = new GenericRecord(topSchema);
                    @event.Put("Property", inner);
                }
                else
                {
                    var leafSchema = SchemaBuilder.Record(
                        "leaf",
                        TypeBuilder.Field(
                            "Id",
                            TypeBuilder.StringType(
                                TypeBuilder.Property(
                                    AvroConstant.PROP_STRING_KEY,
                                    AvroConstant.PROP_STRING_VALUE))));

                    var innerSchema = SchemaBuilder.Record("inner", TypeBuilder.Field("Leaf", leafSchema));
                    var topSchema   = SchemaBuilder.Record("top", TypeBuilder.Field("Property", innerSchema));
                    var leaf        = new GenericRecord(leafSchema);
                    leaf.Put("Id", val.Id);
                    var inner = new GenericRecord(innerSchema);
                    inner.Put("Leaf", leaf);
                    @event = new GenericRecord(topSchema);
                    @event.Put("Property", inner);
                }

                env.SendEventAvro(@event, "LocalEvent");
            };

            RunAssertion(env, GetEpl("avro"), avro);
        }
Esempio n. 41
0
        public override void Update(EventBean[] newData, EventBean[] oldData)
        {
            using (Instrument.With(
                       i => i.QViewProcessIRStream(this, _factory.ViewName, newData, oldData),
                       i => i.AViewProcessIRStream()))
            {
                if ((newData != null) && (newData.Length > 0))
                {
                    // If we have an empty window about to be filled for the first time, add a callback
                    bool removeSchedule = false;
                    bool addSchedule    = false;
                    long timestamp      = _agentInstanceContext.StatementContext.SchedulingService.Time;

                    // if the window is already filled, then we may need to reschedule
                    if (_currentBatch.IsNotEmpty())
                    {
                        // check if we need to reschedule
                        long callbackTime = timestamp + _timeDeltaComputation.DeltaMillisecondsAdd(timestamp);
                        if (callbackTime != _callbackScheduledTime)
                        {
                            removeSchedule = true;
                            addSchedule    = true;
                        }
                    }
                    else
                    {
                        addSchedule = true;
                    }

                    if (removeSchedule)
                    {
                        _agentInstanceContext.StatementContext.SchedulingService.Remove(_handle, _scheduleSlot);
                        _callbackScheduledTime = -1;
                    }
                    if (addSchedule)
                    {
                        long msecIntervalSize = _timeDeltaComputation.DeltaMillisecondsAdd(timestamp);
                        _agentInstanceContext.StatementContext.SchedulingService.Add(
                            msecIntervalSize, _handle, _scheduleSlot);
                        _callbackScheduledTime = msecIntervalSize + timestamp;
                    }

                    // add data points to the window
                    for (int i = 0; i < newData.Length; i++)
                    {
                        _currentBatch.Put(newData[i], timestamp);
                        InternalHandleAdded(newData[i], timestamp);
                        _lastEvent = newData[i];
                    }
                }

                if ((oldData != null) && (oldData.Length > 0))
                {
                    bool removedLastEvent = false;
                    foreach (EventBean anOldData in oldData)
                    {
                        _currentBatch.Remove(anOldData);
                        InternalHandleRemoved(anOldData);
                        if (anOldData == _lastEvent)
                        {
                            removedLastEvent = true;
                        }
                    }

                    // we may need to reschedule as the newest event may have been deleted
                    if (_currentBatch.Count == 0)
                    {
                        _agentInstanceContext.StatementContext.SchedulingService.Remove(_handle, _scheduleSlot);
                        _callbackScheduledTime = -1;
                        _lastEvent             = null;
                    }
                    else
                    {
                        // reschedule if the last event was removed
                        if (removedLastEvent)
                        {
                            ICollection <EventBean> keyset = _currentBatch.Keys;
                            EventBean[]             events = keyset.ToArray();
                            _lastEvent = events[events.Length - 1];
                            long lastTimestamp = _currentBatch.Get(_lastEvent);

                            // reschedule, newest event deleted
                            long timestamp    = _agentInstanceContext.StatementContext.SchedulingService.Time;
                            long callbackTime = lastTimestamp + _timeDeltaComputation.DeltaMillisecondsAdd(lastTimestamp);
                            long deltaFromNow = callbackTime - timestamp;
                            if (callbackTime != _callbackScheduledTime)
                            {
                                _agentInstanceContext.StatementContext.SchedulingService.Remove(_handle, _scheduleSlot);
                                _agentInstanceContext.StatementContext.SchedulingService.Add(
                                    deltaFromNow, _handle, _scheduleSlot);
                                _callbackScheduledTime = callbackTime;
                            }
                        }
                    }
                }

                // Update child views
                if (HasViews)
                {
                    using (Instrument.With(
                               i => i.QViewIndicate(this, _factory.ViewName, newData, oldData),
                               i => i.AViewIndicate()))
                    {
                        UpdateChildren(newData, oldData);
                    }
                }
            }
        }