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]); }
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 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 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 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); }
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 TestDictionaryAccess() { var societyContext = new StandardEvaluationContext(); societyContext.SetRootObject(new IEEE()); // Officer's Dictionary var pupin = parser.ParseExpression("Officers['president']").GetValue <Inventor>(societyContext); Assert.NotNull(pupin); // Evaluates to "Idvor" var city = parser.ParseExpression("Officers['president'].PlaceOfBirth.City").GetValue <string>(societyContext); Assert.NotNull(city); // setting values var i = parser.ParseExpression("Officers['advisors'][0]").GetValue <Inventor>(societyContext); Assert.Equal("Nikola Tesla", i.Name); parser.ParseExpression("Officers['advisors'][0].PlaceOfBirth.Country").SetValue(societyContext, "Croatia"); var i2 = parser.ParseExpression("Reverse[0]['advisors'][0]").GetValue <Inventor>(societyContext); Assert.Equal("Nikola Tesla", i2.Name); }
public static StandardEvaluationContext GetTestEvaluationContext() { var testContext = new StandardEvaluationContext(); SetupRootContextObject(testContext); PopulateVariables(testContext); PopulateFunctions(testContext); return(testContext); }
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); }
public void TestSelection() { var societyContext = new StandardEvaluationContext(); societyContext.SetRootObject(new IEEE()); var list = (List <object>)parser.ParseExpression("Members2.?[Nationality == 'Serbian']").GetValue(societyContext); Assert.Single(list); Assert.Equal("Nikola Tesla", ((Inventor)list[0]).Name); }
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); }
public void InvokeMethodWithoutConversion() { var bytes = new byte[100]; var context = new StandardEvaluationContext(bytes); context.ServiceResolver = new TestServiceResolver(); var expression = parser.ParseExpression("@service.HandleBytes(#root)"); var outBytes = expression.GetValue <byte[]>(context); Assert.Same(bytes, outBytes); }
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")); }
public void TestAccessingOnNullObject() { var expr = (SpelExpression)parser.ParseExpression("madeup"); var context = new StandardEvaluationContext(null); var ex = Assert.Throws <SpelEvaluationException>(() => expr.GetValue(context)); Assert.Equal(SpelMessage.PROPERTY_OR_FIELD_NOT_READABLE_ON_NULL, ex.MessageCode); Assert.False(expr.IsWritable(context)); ex = Assert.Throws <SpelEvaluationException>(() => expr.SetValue(context, "abc")); Assert.Equal(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, ex.MessageCode); }
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); }
public void TestConstructors() { var societyContext = new StandardEvaluationContext(); societyContext.SetRootObject(new IEEE()); var einstein = parser.ParseExpression("new Steeltoe.Common.Expression.Internal.Spring.TestResources.Inventor('Albert Einstein',new DateTime(1879, 3, 14), 'German')").GetValue <Inventor>(); Assert.Equal("Albert Einstein", einstein.Name); // create new inventor instance within add method of List parser.ParseExpression("Members2.Add(new Steeltoe.Common.Expression.Internal.Spring.TestResources.Inventor('Albert Einstein', 'German'))").GetValue(societyContext); }
public void TestVariables() { var tesla = new Inventor("Nikola Tesla", "Serbian"); var context = new StandardEvaluationContext(); context.SetVariable("newName", "Mike Tesla"); context.SetRootObject(tesla); parser.ParseExpression("Foo = #newName").GetValue(context); Assert.Equal("Mike Tesla", tesla.Foo); }
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")); }
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); }
private static void SetupRootContextObject(StandardEvaluationContext testContext) { var c = new GregorianCalendar(); var tesla = new Inventor("Nikola Tesla", c.ToDateTime(1856, 7, 9, 0, 0, 0, GregorianCalendar.CurrentEra), "Serbian"); tesla.PlaceOfBirth = new PlaceOfBirth("SmilJan"); tesla.Inventions = new string[] { "Telephone repeater", "Rotating magnetic field principle", "Polyphase alternating-current system", "Induction motor", "Alternating-current power transmission", "Tesla coil transformer", "Wireless communication", "Radio", "Fluorescent lights" }; testContext.SetRootObject(tesla); }
public void TestBraceAccess() { var rootObject = new ServiceExpressionContext(serviceProvider.GetService <IApplicationContext>()); var context = new StandardEvaluationContext(rootObject); context.AddPropertyAccessor(new ServiceExpressionContextAccessor()); context.AddPropertyAccessor(new ConfigurationAccessor()); var sep = new SpelExpressionParser(); // basic var ex = sep.ParseExpression("configuration['my.name']"); Assert.Equal("myservice", ex.GetValue <string>(context)); }
public void TestScenario01_Roles() { var parser = new SpelExpressionParser(); var ctx = new StandardEvaluationContext(); var expr = parser.ParseRaw("HasAnyRole('MANAGER','TELLER')"); ctx.SetRootObject(new Person("Ben")); var value = expr.GetValue(ctx, typeof(bool)); Assert.False((bool)value); ctx.SetRootObject(new Manager("Luke")); value = expr.GetValue(ctx, typeof(bool)); Assert.True((bool)value); }
private static void PopulateFunctions(StandardEvaluationContext testContext) { try { testContext.RegisterFunction("IsEven", typeof(TestScenarioCreator).GetMethod("IsEven", new Type[] { typeof(int) })); testContext.RegisterFunction("ReverseInt", typeof(TestScenarioCreator).GetMethod("ReverseInt", new Type[] { typeof(int), typeof(int), typeof(int) })); testContext.RegisterFunction("ReverseString", typeof(TestScenarioCreator).GetMethod("ReverseString", new Type[] { typeof(string) })); testContext.RegisterFunction("VarargsFunctionReverseStringsAndMerge", typeof(TestScenarioCreator).GetMethod("VarargsFunctionReverseStringsAndMerge", new Type[] { typeof(string[]) })); testContext.RegisterFunction("VarargsFunctionReverseStringsAndMerge2", typeof(TestScenarioCreator).GetMethod("VarargsFunctionReverseStringsAndMerge2", new Type[] { typeof(int), typeof(string[]) })); } catch (Exception ex) { throw new InvalidOperationException("Populate failed", ex); } }
public void CustomMapWithNonStringValue() { CustomMap map = new CustomMap(); map.Add("x", "1"); map.Add("y", 2); map.Add("z", "3"); var expression = _parser.ParseExpression("Foo(#props)"); var context = new StandardEvaluationContext(); context.SetVariable("props", map); var result = expression.GetValue <string>(context, new TestBean()); Assert.Equal("123", result); }
public void MapWithAllStringValues() { var map = new Dictionary <string, object>(); map.Add("x", "1"); map.Add("y", "2"); map.Add("z", "3"); var expression = _parser.ParseExpression("Foo(#props)"); var context = new StandardEvaluationContext(); context.SetVariable("props", map); var result = expression.GetValue <string>(context, new TestBean()); Assert.Equal("123", result); }
public void Props() { var props = new Dictionary <string, string>(); props.Add("x", "1"); props.Add("y", "2"); props.Add("z", "3"); var expression = _parser.ParseExpression("Foo(#props)"); var context = new StandardEvaluationContext(); context.SetVariable("props", props); var result = expression.GetValue <string>(context, new TestBean()); Assert.Equal("123", result); }
public void TestMethodInvocation2() { // string literal, Evaluates to "bc" var c = parser.ParseExpression("'abc'.Substring(1, 2)").GetValue <string>(); Assert.Equal("bc", c); var societyContext = new StandardEvaluationContext(); societyContext.SetRootObject(new IEEE()); // Evaluates to true var isMember = parser.ParseExpression("IsMember('Mihajlo Pupin')").GetValue <bool>(societyContext); Assert.True(isMember); }
public void TestRootObject() { // The constructor arguments are name, birthday, and nationaltiy. var tesla = new Inventor("Nikola Tesla", new DateTime(1856, 7, 9), "Serbian"); var parser = new SpelExpressionParser(); var exp = parser.ParseExpression("Name"); var context = new StandardEvaluationContext(); context.SetRootObject(tesla); var name = (string)exp.GetValue(context); Assert.Equal("Nikola Tesla", name); }
public void SpelExpressionArrayWithVariables() { var parser = new SpelExpressionParser(); var spelExpression = parser.ParseExpression("#anArray[0] eq 1"); var ctx = new StandardEvaluationContext(); var hmap = new Dictionary <string, object>() { { "anArray", new int[] { 1, 2, 3 } } }; ctx.SetVariables(hmap); var result = spelExpression.GetValue <bool>(ctx); Assert.True(result); }