Java Code Examples for org.springframework.expression.spel.support.standardevaluationcontext#setVariable()

The following examples show how to use org.springframework.expression.spel.support.standardevaluationcontext#setVariable() . 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: SpelReproTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void SPR10452() {
	SpelParserConfiguration configuration = new SpelParserConfiguration(false, false);
	ExpressionParser parser = new SpelExpressionParser(configuration);

	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression spel = parser.parseExpression("#enumType.values()");

	context.setVariable("enumType", ABC.class);
	Object result = spel.getValue(context);
	assertNotNull(result);
	assertTrue(result.getClass().isArray());
	assertEquals(ABC.A, Array.get(result, 0));
	assertEquals(ABC.B, Array.get(result, 1));
	assertEquals(ABC.C, Array.get(result, 2));

	context.setVariable("enumType", XYZ.class);
	result = spel.getValue(context);
	assertNotNull(result);
	assertTrue(result.getClass().isArray());
	assertEquals(XYZ.X, Array.get(result, 0));
	assertEquals(XYZ.Y, Array.get(result, 1));
	assertEquals(XYZ.Z, Array.get(result, 2));
}
 
Example 2
Source File: ScenariosForSpringSecurity.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void testScenario03_Arithmetic() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// Might be better with a as a variable although it would work as a property too...
	// Variable references using a '#'
	Expression expr = parser.parseRaw("(hasRole('SUPERVISOR') or (#a <  1.042)) and hasIpAddress('10.10.0.0/16')");

	Boolean value = null;

	ctx.setVariable("a",1.0d); // referenced as #a in the expression
	ctx.setRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it
	value = expr.getValue(ctx,Boolean.class);
	assertTrue(value);

	ctx.setRootObject(new Manager("Luke"));
	ctx.setVariable("a",1.043d);
	value = expr.getValue(ctx,Boolean.class);
	assertFalse(value);
}
 
Example 3
Source File: SpelUtil.java    From mall4j with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 支持 #p0 参数索引的表达式解析
 * @param rootObject 根对象,method 所在的对象
 * @param spel 表达式
 * @param method ,目标方法
 * @param args 方法入参
 * @return 解析后的字符串
 */
public static String parse(Object rootObject,String spel, Method method, Object[] args) {
    if (StrUtil.isBlank(spel)) {
        return StrUtil.EMPTY;
    }
    //获取被拦截方法参数名列表(使用Spring支持类库)
    LocalVariableTableParameterNameDiscoverer u =
            new LocalVariableTableParameterNameDiscoverer();
    String[] paraNameArr = u.getParameterNames(method);
    if (ArrayUtil.isEmpty(paraNameArr)) {
        return spel;
    }
    //使用SPEL进行key的解析
    ExpressionParser parser = new SpelExpressionParser();
    //SPEL上下文
    StandardEvaluationContext context = new MethodBasedEvaluationContext(rootObject,method,args,u);
    //把方法参数放入SPEL上下文中
    for (int i = 0; i < paraNameArr.length; i++) {
        context.setVariable(paraNameArr[i], args[i]);
    }
    return parser.parseExpression(spel).getValue(context, String.class);
}
 
Example 4
Source File: ScenariosForSpringSecurity.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testScenario03_Arithmetic() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// Might be better with a as a variable although it would work as a property too...
	// Variable references using a '#'
	Expression expr = parser.parseRaw("(hasRole('SUPERVISOR') or (#a <  1.042)) and hasIpAddress('10.10.0.0/16')");

	Boolean value = null;

	ctx.setVariable("a",1.0d); // referenced as #a in the expression
	ctx.setRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it
	value = expr.getValue(ctx,Boolean.class);
	assertTrue(value);

	ctx.setRootObject(new Manager("Luke"));
	ctx.setVariable("a",1.043d);
	value = expr.getValue(ctx,Boolean.class);
	assertFalse(value);
}
 
Example 5
Source File: ExpressionLanguageBasedConditionEvaluator.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@Override
public boolean evaluate(Request request, ExecutionContext executionContext) {
    if (expression != null) {
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setVariable("request", new EvaluableRequest(request));
        context.setVariable("context", new EvaluableExecutionContext(executionContext));
        return this.expression.getValue(context, Boolean.class);
    }

    return true;
}
 
Example 6
Source File: AuthAspect.java    From blade-tool with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取方法上的参数
 *
 * @param method 方法
 * @param args   变量
 * @return {SimpleEvaluationContext}
 */
private StandardEvaluationContext getEvaluationContext(Method method, Object[] args) {
	// 初始化Sp el表达式上下文,并设置 AuthFun
	StandardEvaluationContext context = new StandardEvaluationContext(new AuthFun());
	// 设置表达式支持spring bean
	context.setBeanResolver(new BeanFactoryResolver(applicationContext));
	for (int i = 0; i < args.length; i++) {
		// 读取方法参数
		MethodParameter methodParam = ClassUtil.getMethodParameter(method, i);
		// 设置方法 参数名和值 为sp el变量
		context.setVariable(methodParam.getParameterName(), args[i]);
	}
	return context;
}
 
Example 7
Source File: PropertiesConversionSpelTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void mapWithAllStringValues() {
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("x", "1");
	map.put("y", "2");
	map.put("z", "3");
	Expression expression = parser.parseExpression("foo(#props)");
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setVariable("props", map);
	String result = expression.getValue(context, new TestBean(), String.class);
	assertEquals("123", result);
}
 
Example 8
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void dollars2() {
	StandardEvaluationContext eContext = new StandardEvaluationContext(new XX());
	Expression expr = null;
	expr = new SpelExpressionParser().parseRaw("m[$foo]");
	eContext.setVariable("file_name", "$foo");
	assertEquals("wibble", expr.getValue(eContext, String.class));
}
 
Example 9
Source File: SpelReproTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void dollars() {
	StandardEvaluationContext context = new StandardEvaluationContext(new XX());
	Expression expr = null;
	expr = new SpelExpressionParser().parseRaw("m['$foo']");
	context.setVariable("file_name", "$foo");
	assertEquals("wibble", expr.getValue(context, String.class));
}
 
Example 10
Source File: PropertiesConversionSpelTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void mapWithNonStringValue() {
	Map<String, Object> map = new HashMap<>();
	map.put("x", "1");
	map.put("y", 2);
	map.put("z", "3");
	map.put("a", new UUID(1, 1));
	Expression expression = parser.parseExpression("foo(#props)");
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setVariable("props", map);
	String result = expression.getValue(context, new TestBean(), String.class);
	assertEquals("1null3", result);
}
 
Example 11
Source File: SpelReproTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
/** Should be accessing Goo.wibble field because 'bar' variable evaluates to "wibble" */
@Test
public void indexingAsAPropertyAccess_SPR6968_3() {
	StandardEvaluationContext context = new StandardEvaluationContext(new Goo());
	context.setVariable("bar", "wibble");
	String name = null;
	Expression expr = null;
	expr = new SpelExpressionParser().parseRaw("instance[#bar]");
	// will access the field 'wibble' and not use a getter
	name = expr.getValue(context, String.class);
	assertEquals("wobble", name);
	name = expr.getValue(context, String.class); // will be using the cached accessor this time
	assertEquals("wobble", name);
}
 
Example 12
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void SPR10210() throws Exception {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setVariable("bridgeExample", new org.springframework.expression.spel.spr10210.D());
	Expression parseExpression = parser.parseExpression("#bridgeExample.bridgeMethod()");
	parseExpression.getValue(context);
}
 
Example 13
Source File: RateCheckInterceptor.java    From redislimiter-spring-boot with Apache License 2.0 5 votes vote down vote up
private void mountHeaders(HttpServletRequest request, StandardEvaluationContext context) {
    HashMap<String, String> headerMap = new HashMap();
    Enumeration<String> headerNames = request.getHeaderNames();
    if (headerNames != null) {
        while (headerNames.hasMoreElements()) {
            String headerName = headerNames.nextElement();
            headerMap.put(headerName, request.getHeader(headerName));
        }
    }
    context.setVariable("Headers", headerMap);
}
 
Example 14
Source File: ExpressionWithConversionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCoercionToCollectionOfPrimitive() throws Exception {

	class TestTarget {
		@SuppressWarnings("unused")
		public int sum(Collection<Integer> numbers) {
			int total = 0;
			for (int i : numbers) {
				total += i;
			}
			return total;
		}
	}

	StandardEvaluationContext evaluationContext = new StandardEvaluationContext();

	TypeDescriptor collectionType = new TypeDescriptor(new MethodParameter(TestTarget.class.getDeclaredMethod(
			"sum", Collection.class), 0));
	// The type conversion is possible
	assertTrue(evaluationContext.getTypeConverter()
			.canConvert(TypeDescriptor.valueOf(String.class), collectionType));
	// ... and it can be done successfully
	assertEquals("[1, 2, 3, 4]", evaluationContext.getTypeConverter().convertValue("1,2,3,4", TypeDescriptor.valueOf(String.class), collectionType).toString());

	evaluationContext.setVariable("target", new TestTarget());

	// OK up to here, so the evaluation should be fine...
	// ... but this fails
	int result = (Integer) parser.parseExpression("#target.sum(#root)").getValue(evaluationContext, "1,2,3,4");
	assertEquals("Wrong result: " + result, 10, result);

}
 
Example 15
Source File: HbaseApiMetaDataDaoTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void getApiMetaDataCachable() {
    // cacheable key - spring expression language
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("agentId", "foo");
    context.setVariable("time", (long) 1);
    context.setVariable("apiId", (int) 2);

    String key = (String) parser.parseExpression(HbaseApiMetaDataDao.SPEL_KEY).getValue(context);
    assertEquals("foo.1.2", key);
}
 
Example 16
Source File: PropertiesConversionSpelTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void mapWithAllStringValues() {
	Map<String, Object> map = new HashMap<>();
	map.put("x", "1");
	map.put("y", "2");
	map.put("z", "3");
	Expression expression = parser.parseExpression("foo(#props)");
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setVariable("props", map);
	String result = expression.getValue(context, new TestBean(), String.class);
	assertEquals("123", result);
}
 
Example 17
Source File: DecryptPassword.java    From jwala with Apache License 2.0 5 votes vote down vote up
public String encrypt(String unencryptedValue) {
    
    if (unencryptedValue==null) {
        return null;
    }
    
    final ExpressionParser expressionParser = new SpelExpressionParser();
    final Expression encryptExpression = expressionParser.parseExpression(encryptorImpl);

    final StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("stringToEncrypt", unencryptedValue);
    return encryptExpression.getValue(context, String.class);
}
 
Example 18
Source File: SpelCompilationCoverageTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void functionReferenceNonCompilableArguments_SPR12359() throws Exception {
	StandardEvaluationContext context = new StandardEvaluationContext(new  Object[] { "1" });
	context.registerFunction("negate", SomeCompareMethod2.class.getDeclaredMethod(
			"negate", Integer.TYPE));
	context.setVariable("arg", "2");
	int[] ints = new int[]{1,2,3};
	context.setVariable("ints",ints);

	expression = parser.parseExpression("#negate(#ints.?[#this<2][0])");
	assertEquals("-1",expression.getValue(context, Integer.class).toString());
	// Selection isn't compilable.
	assertFalse(((SpelNodeImpl)((SpelExpression)expression).getAST()).isCompilable());
}
 
Example 19
Source File: ConsumerSpEL.java    From DataflowTemplates with Apache License 2.0 4 votes vote down vote up
public void evaluateAssign(Consumer consumer, Collection<TopicPartition> topicPartitions) {
  StandardEvaluationContext mapContext = new StandardEvaluationContext();
  mapContext.setVariable("consumer", consumer);
  mapContext.setVariable("tp", topicPartitions);
  assignExpression.getValue(mapContext);
}
 
Example 20
Source File: ConsumerSpEL.java    From beam with Apache License 2.0 4 votes vote down vote up
public void evaluateSeek2End(Consumer consumer, TopicPartition topicPartition) {
  StandardEvaluationContext mapContext = new StandardEvaluationContext();
  mapContext.setVariable("consumer", consumer);
  mapContext.setVariable("tp", topicPartition);
  seek2endExpression.getValue(mapContext);
}