org.springframework.expression.spel.support.StandardEvaluationContext Java Examples
The following examples show how to use
org.springframework.expression.spel.support.StandardEvaluationContext.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExpressionLanguageScenarioTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
/** * Scenario: add a property resolver that will get called in the resolver chain, this one only supports reading. */ @Test public void testScenario_AddingYourOwnPropertyResolvers_1() throws Exception { // Create a parser SpelExpressionParser parser = new SpelExpressionParser(); // Use the standard evaluation context StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.addPropertyAccessor(new FruitColourAccessor()); Expression expr = parser.parseRaw("orange"); Object value = expr.getValue(ctx); assertEquals(Color.orange, value); try { expr.setValue(ctx, Color.blue); fail("Should not be allowed to set oranges to be blue !"); } catch (SpelEvaluationException ee) { assertEquals(ee.getMessageCode(), SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL); } }
Example #2
Source File: SpelReproTests.java From java-technology-stack with MIT License | 6 votes |
/** * Test the ability to subclass the ReflectiveMethodResolver and change how it * determines the set of methods for a type. */ @Test public void customStaticFunctions_SPR9038() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); List<MethodResolver> methodResolvers = new ArrayList<>(); methodResolvers.add(new ReflectiveMethodResolver() { @Override protected Method[] getMethods(Class<?> type) { try { return new Method[] {Integer.class.getDeclaredMethod("parseInt", String.class, Integer.TYPE)}; } catch (NoSuchMethodException ex) { return new Method[0]; } } }); context.setMethodResolvers(methodResolvers); Expression expression = parser.parseExpression("parseInt('-FF', 16)"); Integer result = expression.getValue(context, "", Integer.class); assertEquals(-255, result.intValue()); }
Example #3
Source File: ExpressionEvaluator.java From Milkomeda with MIT License | 6 votes |
/** * 根据方法创建一个 {@link EvaluationContext} * @param object 目标对象 * @param targetClass 目标类型 * @param method 方法 * @param args 参数 * @return EvaluationContext */ public StandardEvaluationContext createEvaluationContext(Object object, Class<?> targetClass, Method method, Object[] args) { Method targetMethod = getTargetMethod(targetClass, method); // 创建自定义EL Root ExpressionRootObject root = new ExpressionRootObject(object, args); // 创建基于方法的执行上下文 MethodBasedEvaluationContext evaluationContext = new MethodBasedEvaluationContext(root, targetMethod, args, this.paramNameDiscoverer); // 添加变量引用 Environment env = ApplicationContextHolder.getEnvironment(); if (env != null) { evaluationContext.setVariable("env", env.getProperties()); } evaluationContext.setVariable("target", object); ServletRequestAttributes requestAttributes = WebContext.getRequestAttributes(); if (requestAttributes != null) { evaluationContext.setVariable("request", requestAttributes.getRequest()); evaluationContext.setVariable("reqParams", requestAttributes.getRequest().getParameterMap()); } return evaluationContext; }
Example #4
Source File: SpelReproTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void mapOfMap_SPR7244() { Map<String, Object> map = new LinkedHashMap<>(); map.put("uri", "http:"); Map<String, String> nameMap = new LinkedHashMap<>(); nameMap.put("givenName", "Arthur"); map.put("value", nameMap); StandardEvaluationContext context = new StandardEvaluationContext(map); ExpressionParser parser = new SpelExpressionParser(); String el1 = "#root['value'].get('givenName')"; Expression exp = parser.parseExpression(el1); Object evaluated = exp.getValue(context); assertEquals("Arthur", evaluated); String el2 = "#root['value']['givenName']"; exp = parser.parseExpression(el2); evaluated = exp.getValue(context); assertEquals("Arthur", evaluated); }
Example #5
Source File: SpelDocumentationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testDictionaryAccess() throws Exception { StandardEvaluationContext societyContext = new StandardEvaluationContext(); societyContext.setRootObject(new IEEE()); // Officer's Dictionary Inventor pupin = parser.parseExpression("officers['president']").getValue(societyContext, Inventor.class); assertNotNull(pupin); // evaluates to "Idvor" String city = parser.parseExpression("officers['president'].PlaceOfBirth.city").getValue(societyContext, String.class); assertNotNull(city); // setting values Inventor i = parser.parseExpression("officers['advisors'][0]").getValue(societyContext,Inventor.class); assertEquals("Nikola Tesla",i.getName()); parser.parseExpression("officers['advisors'][0].PlaceOfBirth.Country").setValue(societyContext, "Croatia"); Inventor i2 = parser.parseExpression("reverse[0]['advisors'][0]").getValue(societyContext,Inventor.class); assertEquals("Nikola Tesla",i2.getName()); }
Example #6
Source File: ConstructorInvocationTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testAddingConstructorResolvers() { StandardEvaluationContext ctx = new StandardEvaluationContext(); // reflective constructor accessor is the only one by default List<ConstructorResolver> constructorResolvers = ctx.getConstructorResolvers(); assertEquals(1, constructorResolvers.size()); ConstructorResolver dummy = new DummyConstructorResolver(); ctx.addConstructorResolver(dummy); assertEquals(2, ctx.getConstructorResolvers().size()); List<ConstructorResolver> copy = new ArrayList<ConstructorResolver>(); copy.addAll(ctx.getConstructorResolvers()); assertTrue(ctx.removeConstructorResolver(dummy)); assertFalse(ctx.removeConstructorResolver(dummy)); assertEquals(1, ctx.getConstructorResolvers().size()); ctx.setConstructorResolvers(copy); assertEquals(2, ctx.getConstructorResolvers().size()); }
Example #7
Source File: EvaluationTests.java From java-technology-stack with MIT License | 6 votes |
/** * Verifies behavior requested in SPR-9621. */ @Test public void customMethodFilter() { StandardEvaluationContext context = new StandardEvaluationContext(); // Register a custom MethodResolver... List<MethodResolver> customResolvers = new ArrayList<>(); customResolvers.add(new CustomMethodResolver()); context.setMethodResolvers(customResolvers); // or simply... // context.setMethodResolvers(new ArrayList<MethodResolver>()); // Register a custom MethodFilter... MethodFilter filter = new CustomMethodFilter(); try { context.registerMethodFilter(String.class, filter); fail("should have failed"); } catch (IllegalStateException ise) { assertEquals( "Method filter cannot be set as the reflective method resolver is not in use", ise.getMessage()); } }
Example #8
Source File: ExpressionLanguageScenarioTests.java From spring-analysis-note with MIT License | 6 votes |
/** * Scenario: using your own java methods and calling them from the expression */ @Test public void testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem() throws SecurityException, NoSuchMethodException { try { // Create a parser SpelExpressionParser parser = new SpelExpressionParser(); // Use the standard evaluation context StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.registerFunction("repeat",ExpressionLanguageScenarioTests.class.getDeclaredMethod("repeat",String.class)); Expression expr = parser.parseRaw("#repeat('hello')"); Object value = expr.getValue(ctx); assertEquals("hellohello", value); } catch (EvaluationException | ParseException ex) { ex.printStackTrace(); fail("Unexpected Exception: " + ex.getMessage()); } }
Example #9
Source File: SpELTest.java From java-master with Apache License 2.0 | 6 votes |
@Test @SuppressWarnings("ALL") public void test6() { Inventor tesla = new Inventor("Nikola Tesla", new Date(), "Bei Jin"); Inventor tesla1 = new Inventor("Nikola Tesla", new Date(), "Shang Hai"); Inventor tesla2 = new Inventor("Nikola Tesla", new Date(), "New York"); Inventor tesla3 = new Inventor("Nikola Tesla", new Date(), "Serbian"); Inventor tesla4 = new Inventor("Nikola Tesla", new Date(), "Serbian"); List<Inventor> inventors = Arrays.asList(tesla, tesla1, tesla2, tesla3, tesla4); EvaluationContext context = new StandardEvaluationContext(); context.setVariable("inventors", inventors); // 对List做各类运算 List<Inventor> list = (List<Inventor>) parser.parseExpression("#inventors.?[serbian=='Serbian']").getValue(context); logger.info(list.toString()); List<Inventor> list1 = (List<Inventor>) parser.parseExpression("#inventors.![serbian]").getValue(context); logger.info(list1.toString()); List<Inventor> list2 = (List<Inventor>) parser.parseExpression("#inventors.![serbian=='Serbian']").getValue(context); logger.info(list2.toString()); List<Inventor> list3 = (List<Inventor>) parser.parseExpression("#inventors.![#this.getSerbian()]").getValue(context); logger.info(list3.toString()); }
Example #10
Source File: LiteralExpressionTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testGetValue() throws Exception { LiteralExpression lEx = new LiteralExpression("somevalue"); checkString("somevalue", lEx.getValue()); checkString("somevalue", lEx.getValue(String.class)); EvaluationContext ctx = new StandardEvaluationContext(); checkString("somevalue", lEx.getValue(ctx)); checkString("somevalue", lEx.getValue(ctx, String.class)); checkString("somevalue", lEx.getValue(new Rooty())); checkString("somevalue", lEx.getValue(new Rooty(), String.class)); checkString("somevalue", lEx.getValue(ctx, new Rooty())); checkString("somevalue", lEx.getValue(ctx, new Rooty(),String.class)); assertEquals("somevalue", lEx.getExpressionString()); assertFalse(lEx.isWritable(new StandardEvaluationContext())); assertFalse(lEx.isWritable(new Rooty())); assertFalse(lEx.isWritable(new StandardEvaluationContext(), new Rooty())); }
Example #11
Source File: PropertyAccessTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void testAddingRemovingAccessors() { StandardEvaluationContext ctx = new StandardEvaluationContext(); // reflective property accessor is the only one by default List<PropertyAccessor> propertyAccessors = ctx.getPropertyAccessors(); assertEquals(1,propertyAccessors.size()); StringyPropertyAccessor spa = new StringyPropertyAccessor(); ctx.addPropertyAccessor(spa); assertEquals(2,ctx.getPropertyAccessors().size()); List<PropertyAccessor> copy = new ArrayList<>(); copy.addAll(ctx.getPropertyAccessors()); assertTrue(ctx.removePropertyAccessor(spa)); assertFalse(ctx.removePropertyAccessor(spa)); assertEquals(1,ctx.getPropertyAccessors().size()); ctx.setPropertyAccessors(copy); assertEquals(2,ctx.getPropertyAccessors().size()); }
Example #12
Source File: AopUtil.java From phone with Apache License 2.0 | 6 votes |
/** * 通过spring spel解析参数获取redis缓存key * * @param keys * 缓存keys * @param paramNames * 参数名 * @param args * 参数列表 * @return */ public static String parseKeyByParam(String keys, String[] paramNames, Object[] args) { if (StringUtils.isBlank(keys)) { return ""; } ExpressionParser parser = getParser(); StandardEvaluationContext context = new StandardEvaluationContext(); // 把方法参数放入SPEL上下文中 for (int i = 0; i < paramNames.length; i++) { context.setVariable(paramNames[i], args[i]); } // 获取参数key StringBuffer sb = new StringBuffer(); // for (int i = 0; i < keys.length; i++) { sb.append(parser.parseExpression(keys).getValue(context, String.class)); // } return sb.toString(); }
Example #13
Source File: EvaluationTests.java From spring-analysis-note with MIT License | 6 votes |
/** * Verifies behavior requested in SPR-9621. */ @Test public void customMethodFilter() { StandardEvaluationContext context = new StandardEvaluationContext(); // Register a custom MethodResolver... List<MethodResolver> customResolvers = new ArrayList<>(); customResolvers.add(new CustomMethodResolver()); context.setMethodResolvers(customResolvers); // or simply... // context.setMethodResolvers(new ArrayList<MethodResolver>()); // Register a custom MethodFilter... MethodFilter filter = new CustomMethodFilter(); try { context.registerMethodFilter(String.class, filter); fail("should have failed"); } catch (IllegalStateException ise) { assertEquals( "Method filter cannot be set as the reflective method resolver is not in use", ise.getMessage()); } }
Example #14
Source File: LiteralExpressionTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testGetValue() throws Exception { LiteralExpression lEx = new LiteralExpression("somevalue"); checkString("somevalue", lEx.getValue()); checkString("somevalue", lEx.getValue(String.class)); EvaluationContext ctx = new StandardEvaluationContext(); checkString("somevalue", lEx.getValue(ctx)); checkString("somevalue", lEx.getValue(ctx, String.class)); checkString("somevalue", lEx.getValue(new Rooty())); checkString("somevalue", lEx.getValue(new Rooty(), String.class)); checkString("somevalue", lEx.getValue(ctx, new Rooty())); checkString("somevalue", lEx.getValue(ctx, new Rooty(),String.class)); assertEquals("somevalue", lEx.getExpressionString()); assertFalse(lEx.isWritable(new StandardEvaluationContext())); assertFalse(lEx.isWritable(new Rooty())); assertFalse(lEx.isWritable(new StandardEvaluationContext(), new Rooty())); }
Example #15
Source File: EvaluationTests.java From spring-analysis-note with MIT License | 6 votes |
@Test public void incdecTogether() { Spr9751 helper = new Spr9751(); StandardEvaluationContext ctx = new StandardEvaluationContext(helper); ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression e; // index1 is 2 at the start - the 'intArray[#root.index1++]' should not be evaluated twice! // intArray[2] is 3 e = parser.parseExpression("intArray[#root.index1++]++"); e.getValue(ctx, Integer.class); assertEquals(3, helper.index1); assertEquals(4, helper.intArray[2]); // index1 is 3 intArray[3] is 4 e = parser.parseExpression("intArray[#root.index1++]--"); assertEquals(4, e.getValue(ctx, Integer.class).intValue()); assertEquals(4, helper.index1); assertEquals(3, helper.intArray[3]); // index1 is 4, intArray[3] is 3 e = parser.parseExpression("intArray[--#root.index1]++"); assertEquals(3, e.getValue(ctx, Integer.class).intValue()); assertEquals(3, helper.index1); assertEquals(4, helper.intArray[3]); }
Example #16
Source File: VariableAndFunctionTests.java From spring4-understanding with Apache License 2.0 | 6 votes |
@Test public void testCallingIllegalFunctions() throws Exception { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext ctx = new StandardEvaluationContext(); ctx.setVariable("notStatic", this.getClass().getMethod("nonStatic")); try { @SuppressWarnings("unused") Object v = parser.parseRaw("#notStatic()").getValue(ctx); fail("Should have failed with exception - cannot call non static method that way"); } catch (SpelEvaluationException se) { if (se.getMessageCode() != SpelMessage.FUNCTION_MUST_BE_STATIC) { se.printStackTrace(); fail("Should have failed a message about the function needing to be static, not: " + se.getMessageCode()); } } }
Example #17
Source File: ProvAppExpressionHandler.java From ods-provisioning-app with Apache License 2.0 | 5 votes |
@Override public StandardEvaluationContext createEvaluationContextInternal( Authentication authentication, MethodInvocation mi) { StandardEvaluationContext ec = super.createEvaluationContextInternal(authentication, mi); ec.setVariable(PROV_APP, this); logger.debug("Registered '{}' as expression-based keyword", PROV_APP); return ec; }
Example #18
Source File: SelectionAndProjectionTests.java From spring-analysis-note with MIT License | 5 votes |
@Test @SuppressWarnings("unchecked") public void selectLastItemInMap() { EvaluationContext context = new StandardEvaluationContext(new MapTestBean()); ExpressionParser parser = new SpelExpressionParser(); Expression exp = parser.parseExpression("colors.$[key.startsWith('b')]"); Map<String, String> colorsMap = (Map<String, String>) exp.getValue(context); assertEquals(1, colorsMap.size()); assertEquals("brown", colorsMap.keySet().iterator().next()); }
Example #19
Source File: SpelReproTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void SPR10486() { SpelExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); Spr10486 rootObject = new Spr10486(); Expression classNameExpression = parser.parseExpression("class.name"); Expression nameExpression = parser.parseExpression("name"); assertThat(classNameExpression.getValue(context, rootObject), equalTo((Object) Spr10486.class.getName())); assertThat(nameExpression.getValue(context, rootObject), equalTo((Object) "name")); }
Example #20
Source File: SpelReproTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void array() { ExpressionParser parser = new SpelExpressionParser(); StandardEvaluationContext context = new StandardEvaluationContext(); Expression expression = null; Object result = null; expression = parser.parseExpression("new java.lang.Long[0].class"); result = expression.getValue(context, ""); assertEquals("Equal assertion failed: ", "class [Ljava.lang.Long;", result.toString()); expression = parser.parseExpression("T(java.lang.Long[])"); result = expression.getValue(context, ""); assertEquals("Equal assertion failed: ", "class [Ljava.lang.Long;", result.toString()); expression = parser.parseExpression("T(java.lang.String[][][])"); result = expression.getValue(context, ""); assertEquals("Equal assertion failed: ", "class [[[Ljava.lang.String;", result.toString()); assertEquals("T(java.lang.String[][][])", ((SpelExpression) expression).toStringAST()); expression = parser.parseExpression("new int[0].class"); result = expression.getValue(context, ""); assertEquals("Equal assertion failed: ", "class [I", result.toString()); expression = parser.parseExpression("T(int[][])"); result = expression.getValue(context, ""); assertEquals("class [[I", result.toString()); }
Example #21
Source File: SpelReproTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void projectionTypeDescriptors_1() { StandardEvaluationContext context = new StandardEvaluationContext(new C()); SpelExpressionParser parser = new SpelExpressionParser(); String el1 = "ls.![#this.equals('abc')]"; SpelExpression exp = parser.parseRaw(el1); List<?> value = (List<?>) exp.getValue(context); // value is list containing [true,false] assertEquals(Boolean.class, value.get(0).getClass()); TypeDescriptor evaluated = exp.getValueTypeDescriptor(context); assertEquals(null, evaluated.getElementTypeDescriptor()); }
Example #22
Source File: SetValueTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void testAssign() throws Exception { StandardEvaluationContext eContext = TestScenarioCreator.getTestEvaluationContext(); Expression e = parse("publicName='Andy'"); assertFalse(e.isWritable(eContext)); assertEquals("Andy",e.getValue(eContext)); }
Example #23
Source File: SpelReproTests.java From spring-analysis-note with MIT License | 5 votes |
/** Should be accessing Goo.setKey field because 'bar' variable evaluates to "key" */ @Test public void indexingAsAPropertyAccess_SPR6968_5() { Goo g = Goo.instance; StandardEvaluationContext context = new StandardEvaluationContext(g); Expression expr = null; expr = new SpelExpressionParser().parseRaw("instance[bar]='world'"); expr.getValue(context, String.class); assertEquals("world", g.value); expr.getValue(context, String.class); // will be using the cached accessor this time assertEquals("world", g.value); }
Example #24
Source File: SpelReproTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void SPR5804() { Map<String, String> m = new HashMap<>(); m.put("foo", "bar"); StandardEvaluationContext context = new StandardEvaluationContext(m); // root is a map instance context.addPropertyAccessor(new MapAccessor()); Expression expr = new SpelExpressionParser().parseRaw("['foo']"); assertEquals("bar", expr.getValue(context)); }
Example #25
Source File: SpelReproTests.java From java-technology-stack with MIT License | 5 votes |
@Test public void nestedProperties_SPR6923() { StandardEvaluationContext context = new StandardEvaluationContext(new Foo()); Expression expr = new SpelExpressionParser().parseRaw("resource.resource.server"); String name = expr.getValue(context, String.class); assertEquals("abc", name); }
Example #26
Source File: AbstractProcessorBuildObjectMapFromGroupedObjects.java From FortifyBugTrackerUtility with MIT License | 5 votes |
/** * Build a {@link Map} for the current group, based on the configured {@link #fields} and {@link #appendedFields}, * and then call the {@link #processMap(Context, String, List, LinkedHashMap)} method to allow the {@link Map} to be * further processed. */ @Override protected boolean processGroup(Context context, String groupName, List<Object> currentGroup) { StandardEvaluationContext sec = ContextSpringExpressionUtil.createStandardEvaluationContext(context); LinkedHashMap<String, Object> map = new MapBuilder() .addMapUpdater(new MapUpdaterPutValuesFromExpressionMap(sec, currentGroup.get(0), getFields())) .addMapUpdater(new MapUpdaterAppendValuesFromExpressionMap(sec, currentGroup, getAppendedFields())) .build(new LinkedHashMap<String, Object>()); return processMap(context, groupName, currentGroup, map); }
Example #27
Source File: ExpressionTransformTest.java From kork with Apache License 2.0 | 5 votes |
@Test void evaluateCompositeExpression() { ExpressionEvaluationSummary summary = new ExpressionEvaluationSummary(); StandardEvaluationContext evaluationContext = new ExpressionsSupport(Trigger.class) .buildEvaluationContext(new Pipeline(new Trigger(100)), true); String evaluated = new ExpressionTransform(parserContext, parser, Function.identity()) .transformString( "group:artifact:${trigger['buildNumber']}", evaluationContext, summary); assertThat(evaluated).isEqualTo("group:artifact:100"); assertThat(summary.getFailureCount()).isEqualTo(0); }
Example #28
Source File: SimpleSolrPersistentEntity.java From dubbox with Apache License 2.0 | 5 votes |
public SimpleSolrPersistentEntity(TypeInformation<T> typeInformation) { super(typeInformation); this.context = new StandardEvaluationContext(); this.typeInformation = typeInformation; this.solrCoreName = derivateSolrCoreName(); this.boost = derivateDocumentBoost(); }
Example #29
Source File: ExpressionWithConversionTests.java From spring4-understanding with Apache License 2.0 | 5 votes |
@Test public void testSetParameterizedList() throws Exception { StandardEvaluationContext context = TestScenarioCreator.getTestEvaluationContext(); Expression e = parser.parseExpression("listOfInteger.size()"); assertEquals(0,e.getValue(context,Integer.class).intValue()); context.setTypeConverter(new TypeConvertorUsingConversionService()); // Assign a List<String> to the List<Integer> field - the component elements should be converted parser.parseExpression("listOfInteger").setValue(context,listOfString); assertEquals(3,e.getValue(context,Integer.class).intValue()); // size now 3 Class<?> clazz = parser.parseExpression("listOfInteger[1].getClass()").getValue(context, Class.class); // element type correctly Integer assertEquals(Integer.class,clazz); }
Example #30
Source File: EvaluationTests.java From spring-analysis-note with MIT License | 5 votes |
@Test public void increment01root() { Integer i = 42; StandardEvaluationContext ctx = new StandardEvaluationContext(i); ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true)); Expression e = parser.parseExpression("#this++"); assertEquals(42,i.intValue()); try { e.getValue(ctx, Integer.class); fail(); } catch (SpelEvaluationException see) { assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode()); } }