Exemple #1
0
        public void TestScenario_DefiningVariablesThatWillBeAccessibleInExpressions()
        {
            // Create a parser
            var parser = new SpelExpressionParser();

            // Use the standard evaluation context
            var ctx = new StandardEvaluationContext();

            ctx.SetVariable("favouriteColour", "blue");
            List <int> primes = new List <int> {
                2, 3, 5, 7, 11, 13, 17
            };

            ctx.SetVariable("primes", primes);

            var expr  = parser.ParseRaw("#favouriteColour");
            var value = expr.GetValue(ctx);

            Assert.Equal("blue", value);

            expr  = parser.ParseRaw("#primes[1]");
            value = expr.GetValue(ctx);
            Assert.Equal(3, value);

            // all prime numbers > 10 from the list (using selection ?{...})
            expr  = parser.ParseRaw("#primes.?[#this>10]");
            value = expr.GetValue(ctx);
            var asList = value as IList;

            Assert.Equal(3, asList.Count);
            Assert.Equal(11, asList[0]);
            Assert.Equal(13, asList[1]);
            Assert.Equal(17, asList[2]);
        }
Exemple #2
0
        public void TestServiceAccess()
        {
            var appContext = serviceProvider.GetService <IApplicationContext>();
            var context    = new StandardEvaluationContext();

            context.ServiceResolver = new ServiceFactoryResolver(appContext);

            var car  = appContext.GetService <Car>();
            var boat = appContext.GetService <Boat>();

            var expr = new SpelExpressionParser().ParseRaw("@'T(Steeltoe.Common.Expression.Internal.Contexts.ServiceFactoryAccessorTests$Car)car'.Colour");

            Assert.Equal("red", expr.GetValue <string>(context));
            expr = new SpelExpressionParser().ParseRaw("@car.Colour");
            Assert.Equal("red", expr.GetValue <string>(context));

            expr = new SpelExpressionParser().ParseRaw("@'T(Steeltoe.Common.Expression.Internal.Contexts.ServiceFactoryAccessorTests$Boat)boat'.Colour");
            Assert.Equal("blue", expr.GetValue <string>(context));
            expr = new SpelExpressionParser().ParseRaw("@boat.Colour");
            Assert.Equal("blue", expr.GetValue <string>(context));

            var noServiceExpr = new SpelExpressionParser().ParseRaw("@truck");

            Assert.Throws <SpelEvaluationException>(() => noServiceExpr.GetValue(context));
        }
        public void TestAddingSpecificPropertyAccessor()
        {
            var parser = new SpelExpressionParser();
            var ctx    = new StandardEvaluationContext();

            // Even though this property accessor is added after the reflection one, it specifically
            // names the String class as the type it is interested in so is chosen in preference to
            // any 'default' ones
            ctx.AddPropertyAccessor(new StringyPropertyAccessor());
            var expr = parser.ParseRaw("new String('hello').flibbles");
            var i    = expr.GetValue(ctx, typeof(int));

            Assert.Equal(7, (int)i);

            // The reflection one will be used for other properties...
            expr = parser.ParseRaw("new String('hello').Length");
            var o = expr.GetValue(ctx);

            Assert.NotNull(o);

            var flibbleexpr = parser.ParseRaw("new String('hello').flibbles");

            flibbleexpr.SetValue(ctx, 99);
            i = flibbleexpr.GetValue(ctx, typeof(int));
            Assert.Equal(99, (int)i);

            // Cannot set it to a string value
            Assert.Throws <SpelEvaluationException>(() => flibbleexpr.SetValue(ctx, "not allowed"));

            // message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
            // 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''
            // System.out.println(e.getMessage());
        }
        public void SpelExpressionListNullVariables()
        {
            var parser         = new SpelExpressionParser();
            var spelExpression = parser.ParseExpression("#aList.contains('one')");

            Assert.Throws <SpelEvaluationException>(() => spelExpression.GetValue());
        }
        public void TestCompositeStringExpression()
        {
            var parser = new SpelExpressionParser();
            var ex     = parser.ParseExpression("hello ${'world'}", DEFAULT_TEMPLATE_PARSER_CONTEXT);

            Assert.Equal("hello world", ex.GetValue());
            Assert.Equal("hello world", ex.GetValue(typeof(string)));
            Assert.Equal("hello world", ex.GetValue((object)null, typeof(string)));
            Assert.Equal("hello world", ex.GetValue(new Rooty()));
            Assert.Equal("hello world", ex.GetValue(new Rooty(), typeof(string)));

            var ctx = new StandardEvaluationContext();

            Assert.Equal("hello world", ex.GetValue(ctx));
            Assert.Equal("hello world", ex.GetValue(ctx, typeof(string)));
            Assert.Equal("hello world", ex.GetValue(ctx, null, typeof(string)));
            Assert.Equal("hello world", ex.GetValue(ctx, new Rooty()));
            Assert.Equal("hello world", ex.GetValue(ctx, new Rooty(), typeof(string)));
            Assert.Equal("hello world", ex.GetValue(ctx, new Rooty(), typeof(string)));
            Assert.Equal("hello ${'world'}", ex.ExpressionString);
            Assert.False(ex.IsWritable(new StandardEvaluationContext()));
            Assert.False(ex.IsWritable(new Rooty()));
            Assert.False(ex.IsWritable(new StandardEvaluationContext(), new Rooty()));

            Assert.Equal(typeof(string), ex.GetValueType());
            Assert.Equal(typeof(string), ex.GetValueType(ctx));
            Assert.Equal(typeof(string), ex.GetValueType(new Rooty()));
            Assert.Equal(typeof(string), ex.GetValueType(ctx, new Rooty()));
            Assert.Throws <EvaluationException>(() => ex.SetValue(ctx, null));
            Assert.Throws <EvaluationException>(() => ex.SetValue((object)null, null));
            Assert.Throws <EvaluationException>(() => ex.SetValue(ctx, null, null));
        }
        public void SpelExpressionListIndexAccessNullVariables()
        {
            var parser         = new SpelExpressionParser();
            var spelExpression = parser.ParseExpression("#aList[0] eq 'one'");

            Assert.Throws <SpelEvaluationException>(() => spelExpression.GetValue());
        }
Exemple #7
0
        public void TestScenario_UsingStandardInfrastructure()
        {
            try
            {
                // Create a parser
                var parser = new SpelExpressionParser();

                // Parse an expression
                var expr = parser.ParseRaw("new String('hello world')");

                // Evaluate it using a 'standard' context
                var value = expr.GetValue();

                // They are reusable
                value = expr.GetValue();

                Assert.Equal("hello world", value);
                Assert.IsType <string>(value);
            }
            catch (SpelEvaluationException ex)
            {
                throw new SystemException(ex.Message, ex);
            }
            catch (ParseException ex)
            {
                throw new SystemException(ex.Message, ex);
            }
        }
        public void TestNestedExpressions()
        {
            var parser = new SpelExpressionParser();

            // treat the nested ${..} as a part of the expression
            var ex = parser.ParseExpression("hello ${ListOfNumbersUpToTen.$[#this<5]} world", DEFAULT_TEMPLATE_PARSER_CONTEXT);
            var s  = ex.GetValue(TestScenarioCreator.GetTestEvaluationContext(), typeof(string));

            Assert.Equal("hello 4 world", s);

            // not a useful expression but Tests nested expression syntax that clashes with template prefix/suffix
            ex = parser.ParseExpression("hello ${ListOfNumbersUpToTen.$[#root.ListOfNumbersUpToTen.$[#this%2==1]==3]} world", DEFAULT_TEMPLATE_PARSER_CONTEXT);
            Assert.IsType <CompositeStringExpression>(ex);
            var cse   = (CompositeStringExpression)ex;
            var exprs = cse.Expressions;

            Assert.Equal(3, exprs.Count);
            Assert.Equal("ListOfNumbersUpToTen.$[#root.ListOfNumbersUpToTen.$[#this%2==1]==3]", exprs[1].ExpressionString);
            s = ex.GetValue(TestScenarioCreator.GetTestEvaluationContext(), typeof(string));
            Assert.Equal("hello  world", s);

            ex = parser.ParseExpression("hello ${ListOfNumbersUpToTen.$[#this<5]} ${ListOfNumbersUpToTen.$[#this>5]} world", DEFAULT_TEMPLATE_PARSER_CONTEXT);
            s  = ex.GetValue(TestScenarioCreator.GetTestEvaluationContext(), typeof(string));
            Assert.Equal("hello 4 10 world", s);

            var pex = Assert.Throws <ParseException>(() => parser.ParseExpression("hello ${ListOfNumbersUpToTen.$[#this<5]} ${ListOfNumbersUpToTen.$[#this>5] world", DEFAULT_TEMPLATE_PARSER_CONTEXT));

            Assert.Equal("No ending suffix '}' for expression starting at character 41: ${ListOfNumbersUpToTen.$[#this>5] world", pex.SimpleMessage);

            pex = Assert.Throws <ParseException>(() => parser.ParseExpression("hello ${ListOfNumbersUpToTen.$[#root.ListOfNumbersUpToTen.$[#this%2==1==3]} world", DEFAULT_TEMPLATE_PARSER_CONTEXT));
            Assert.Equal("Found closing '}' at position 74 but most recent opening is '[' at position 30", pex.SimpleMessage);
        }
Exemple #9
0
        public void TestPropertyNavigation()
        {
            var parser = new SpelExpressionParser();

            // Inventions Array
            var teslaContext = TestScenarioCreator.GetTestEvaluationContext();

            // teslaContext.SetRootObject(tesla);
            // Evaluates to "Induction motor"
            var invention = parser.ParseExpression("Inventions[3]").GetValue <string>(teslaContext);

            Assert.Equal("Induction motor", invention);

            // Members List
            var societyContext = new StandardEvaluationContext();
            var ieee           = new IEEE();

            ieee.Members[0] = Tesla;
            societyContext.SetRootObject(ieee);

            // Evaluates to "Nikola Tesla"
            var name = parser.ParseExpression("Members[0].Name").GetValue <string>(societyContext);

            Assert.Equal("Nikola Tesla", name);

            // List and Array navigation
            // Evaluates to "Wireless communication"
            invention = parser.ParseExpression("Members[0].Inventions[6]").GetValue <string>(societyContext);
            Assert.Equal("Wireless communication", invention);
        }
Exemple #10
0
        public void ResolveCollectionElementTypeNull()
        {
            var parser     = new SpelExpressionParser();
            var expression = parser.ParseExpression("ListNotGeneric");

            Assert.Equal(typeof(IList), expression.GetValueType(this));
        }
        public void TestScenario04_ControllingWhichMethodsRun()
        {
            var parser = new SpelExpressionParser();
            var ctx    = new StandardEvaluationContext();

            ctx.SetRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it);

            // NEEDS TO OVERRIDE THE REFLECTION ONE - SHOW REORDERING MECHANISM
            // Might be better with a as a variable although it would work as a property too...
            // Variable references using a '#'
            // SpelExpression expr = parser.parseExpression("(hasRole('SUPERVISOR') or (#a <  1.042)) and hasIpAddress('10.10.0.0/16')");
            ctx.AddMethodResolver(new MyMethodResolver());

            var expr = parser.ParseRaw("(HasRole(3) or (#a <  1.042)) and HasIpAddress('10.10.0.0/16')");

            bool value;

            ctx.SetVariable("a", 1.0d); // referenced as #a in the expression
            value = expr.GetValue <bool>(ctx);
            Assert.True((bool)value);

            // ctx.setRootObject(new Manager("Luke"));
            // ctx.setVariable("a",1.043d);
            // value = (bool)expr.GetValue(ctx,typeof(bool));
            // assertFalse(value);
        }
        public void TestParsingSimpleTemplateExpression02()
        {
            var parser = new SpelExpressionParser();
            var expr   = parser.ParseExpression("hello ${'to'} you", DEFAULT_TEMPLATE_PARSER_CONTEXT);
            var o      = expr.GetValue();

            Assert.Equal("hello to you", o.ToString());
        }
        public void TestParsingSimpleTemplateExpression03()
        {
            var parser = new SpelExpressionParser();
            var expr   = parser.ParseExpression("The quick ${'brown'} fox jumped over the ${'lazy'} dog", DEFAULT_TEMPLATE_PARSER_CONTEXT);
            var o      = expr.GetValue();

            Assert.Equal("The quick brown fox jumped over the lazy dog", o.ToString());
        }
Exemple #14
0
        public void EmptyList()
        {
            ListOfScalarNotGeneric = new ArrayList();
            var parser     = new SpelExpressionParser();
            var expression = parser.ParseExpression("ListOfScalarNotGeneric");

            Assert.Equal(typeof(ArrayList), expression.GetValueType(this));
            Assert.Equal(string.Empty, expression.GetValue(this, typeof(string)));
        }
Exemple #15
0
        public void TestListOfScalar()
        {
            ListOfScalarNotGeneric = new ArrayList(1);
            ListOfScalarNotGeneric.Add("5");
            var parser     = new SpelExpressionParser();
            var expression = parser.ParseExpression("ListOfScalarNotGeneric[0]");

            Assert.Equal(5, expression.GetValue(this, typeof(int)));
        }
Exemple #16
0
        public void ResolveMapKeyValueTypes()
        {
            MapNotGeneric = new Hashtable();
            MapNotGeneric.Add("baseAmount", 3.11);
            MapNotGeneric.Add("bonusAmount", 7.17);
            var parser     = new SpelExpressionParser();
            var expression = parser.ParseExpression("MapNotGeneric");

            Assert.Equal(typeof(Hashtable), expression.GetValueType(this));
        }
Exemple #17
0
        public void SelectLastItemInSet()
        {
            var expression = new SpelExpressionParser().ParseRaw("Integers.$[#this<5]");
            var context    = new StandardEvaluationContext(new SetTestBean());
            var value      = expression.GetValue(context);
            var condition  = value is int;

            Assert.True(condition);
            Assert.Equal(4, value);
        }
        public void TestCallingIllegalFunctions()
        {
            SpelExpressionParser      parser = new SpelExpressionParser();
            StandardEvaluationContext ctx    = new StandardEvaluationContext();

            ctx.SetVariable("notStatic", this.GetType().GetMethod("NonStatic"));
            var ex = Assert.Throws <SpelEvaluationException>(() => parser.ParseRaw("#notStatic()").GetValue(ctx));

            Assert.Equal(SpelMessage.FUNCTION_MUST_BE_STATIC, ex.MessageCode);
        }
Exemple #19
0
        public void SelectFirstItemInPrimitiveArray()
        {
            var expression = new SpelExpressionParser().ParseRaw("Ints.^[#this<5]");
            var context    = new StandardEvaluationContext(new ArrayTestBean());
            var value      = expression.GetValue(context);
            var condition  = value is int;

            Assert.True(condition);
            Assert.Equal(0, value);
        }
Exemple #20
0
        public void TestFunctions()
        {
            var parser  = new SpelExpressionParser();
            var context = new StandardEvaluationContext();

            context.RegisterFunction("reversestring", typeof(StringUtils).GetMethod("ReverseString", BindingFlags.Public | BindingFlags.Static));

            var helloWorldReversed = parser.ParseExpression("#reversestring('hello world')").GetValue <string>(context);

            Assert.Equal("dlrow olleh", helloWorldReversed);
        }
Exemple #21
0
        public void SelectLastItemInMap()
        {
            var context = new StandardEvaluationContext(new MapTestBean());
            var parser  = new SpelExpressionParser();

            var exp       = parser.ParseExpression("Colors.$[Key.StartsWith('b')]");
            var colorsMap = (Dictionary <object, object>)exp.GetValue(context);

            Assert.Single(colorsMap);
            Assert.True(colorsMap.ContainsKey("beige"));
        }
Exemple #22
0
        public void TestGetValueFromRootMap()
        {
            var map = new Dictionary <string, string>();

            map.Add("key", "value");

            var spelExpressionParser = new SpelExpressionParser();
            var expr = spelExpressionParser.ParseExpression("#root['key']");

            Assert.Equal("value", expr.GetValue(map));
        }
Exemple #23
0
        public void ResolveCollectionElementType()
        {
            ListNotGeneric = new ArrayList(2);
            ListNotGeneric.Add(5);
            ListNotGeneric.Add(6);
            var parser     = new SpelExpressionParser();
            var expression = parser.ParseExpression("ListNotGeneric");

            Assert.Equal(typeof(ArrayList), expression.GetValueType(this));
            Assert.Equal("5,6", expression.GetValue(this, typeof(string)));
        }
Exemple #24
0
        public void SetPropertyContainingMapAutoGrow()
        {
            var parser     = new SpelExpressionParser(new SpelParserOptions(true, false));
            var expression = parser.ParseExpression("ParameterizedMap");

            Assert.Equal(typeof(Dictionary <int, int>), expression.GetValueType(this));
            Assert.Equal(Property, expression.GetValue(this));
            expression = parser.ParseExpression("ParameterizedMap['9']");
            Assert.Null(expression.GetValue(this));
            expression.SetValue(this, "37");
            Assert.Equal(37, expression.GetValue(this));
        }
Exemple #25
0
        public void TestCustomMapAccessor()
        {
            var parser = new SpelExpressionParser();
            var ctx    = TestScenarioCreator.GetTestEvaluationContext();

            ctx.AddPropertyAccessor(new MapAccessor());

            var expr  = parser.ParseExpression("TestDictionary.monday");
            var value = expr.GetValue(ctx, typeof(string));

            Assert.Equal("montag", value);
        }
Exemple #26
0
        public void TestListsOfMap()
        {
            ListOfMapsNotGeneric = new ArrayList();
            var map = new Hashtable();

            map.Add("fruit", "apple");
            ListOfMapsNotGeneric.Add(map);
            var parser     = new SpelExpressionParser();
            var expression = parser.ParseExpression("ListOfMapsNotGeneric[0]['fruit']");

            Assert.Equal("apple", expression.GetValue(this, typeof(string)));
        }
Exemple #27
0
        public void TestVariableMapAccess()
        {
            var parser = new SpelExpressionParser();
            var ctx    = TestScenarioCreator.GetTestEvaluationContext();

            ctx.SetVariable("day", "saturday");

            var expr  = parser.ParseExpression("TestDictionary[#day]");
            var value = expr.GetValue(ctx, typeof(string));

            Assert.Equal("samstag", value);
        }
Exemple #28
0
        public void IndexIntoGenericPropertyContainingArray()
        {
            var property = new string[] { "bar" };

            Property = property;
            var parser     = new SpelExpressionParser();
            var expression = parser.ParseExpression("Property");

            Assert.Equal(typeof(string[]), expression.GetValueType(this));
            Assert.Equal(property, expression.GetValue(this));
            expression = parser.ParseExpression("Property[0]");
            Assert.Equal("bar", expression.GetValue(this));
        }
Exemple #29
0
        public void TestEqualityCheck()
        {
            var parser = new SpelExpressionParser();

            var context = new StandardEvaluationContext();

            context.SetRootObject(Tesla);

            var exp     = parser.ParseExpression("Name == 'Nikola Tesla'");
            var isEqual = exp.GetValue <bool>(context);

            Assert.True(isEqual);
        }
Exemple #30
0
        public void SelectionWithMap()
        {
            var context = new StandardEvaluationContext(new MapTestBean());
            var parser  = new SpelExpressionParser();
            var exp     = parser.ParseExpression("Colors.?[Key.StartsWith('b')]");

            var colorsMap = (Dictionary <object, object>)exp.GetValue(context);

            Assert.Equal(3, colorsMap.Count);
            Assert.True(colorsMap.ContainsKey("beige"));
            Assert.True(colorsMap.ContainsKey("blue"));
            Assert.True(colorsMap.ContainsKey("brown"));
        }