Java Code Examples for org.springframework.expression.ExpressionParser

The following examples show how to use org.springframework.expression.ExpressionParser. These examples are extracted from open source projects. 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 Project: java-technology-stack   Source File: SpelExceptionTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void spelExpressionMapWithVariables() {
	ExpressionParser parser = new SpelExpressionParser();
	Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1");
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariables(new HashMap<String, Object>() {
		{
			put("aMap", new HashMap<String, Integer>() {
				{
					put("one", 1);
					put("two", 2);
					put("three", 3);
				}
			});

		}
	});
	boolean result = spelExpression.getValue(ctx, Boolean.class);
	assertTrue(result);

}
 
Example 2
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: 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 3
Source Project: spring-analysis-note   Source File: SpelDocumentationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testRootObject() throws Exception {
	GregorianCalendar c = new GregorianCalendar();
	c.set(1856, 7, 9);

	//  The constructor arguments are name, birthday, and nationaltiy.
	Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");

	ExpressionParser parser = new SpelExpressionParser();
	Expression exp = parser.parseExpression("name");

	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setRootObject(tesla);

	String name = (String) exp.getValue(context);
	assertEquals("Nikola Tesla",name);
}
 
Example 4
Source Project: java-technology-stack   Source File: SpelDocumentationTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testRootObject() throws Exception {
	GregorianCalendar c = new GregorianCalendar();
	c.set(1856, 7, 9);

	//  The constructor arguments are name, birthday, and nationaltiy.
	Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");

	ExpressionParser parser = new SpelExpressionParser();
	Expression exp = parser.parseExpression("name");

	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setRootObject(tesla);

	String name = (String) exp.getValue(context);
	assertEquals("Nikola Tesla",name);
}
 
Example 5
Source Project: java-technology-stack   Source File: MapAccessTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetValuePerformance() throws Exception {
	Assume.group(TestGroup.PERFORMANCE);
	Map<String, String> map = new HashMap<>();
	map.put("key", "value");
	EvaluationContext context = new StandardEvaluationContext(map);

	ExpressionParser spelExpressionParser = new SpelExpressionParser();
	Expression expr = spelExpressionParser.parseExpression("#root['key']");

	StopWatch s = new StopWatch();
	s.start();
	for (int i = 0; i < 10000; i++) {
		expr.getValue(context);
	}
	s.stop();
	assertThat(s.getTotalTimeMillis(), lessThan(200L));
}
 
Example 6
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 6 votes vote down vote up
@Test
public void SPR9735() {
	Item item = new Item();
	item.setName("parent");

	Item item1 = new Item();
	item1.setName("child1");

	Item item2 = new Item();
	item2.setName("child2");

	item.add(item1);
	item.add(item2);

	ExpressionParser parser = new SpelExpressionParser();
	EvaluationContext context = new StandardEvaluationContext();
	Expression exp = parser.parseExpression("#item[0].name");
	context.setVariable("item", item);

	assertEquals("child1", exp.getValue(context));
}
 
Example 7
Source Project: spring-analysis-note   Source File: EvaluationTests.java    License: MIT License 6 votes vote down vote up
@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 8
Source Project: spring-analysis-note   Source File: MapAccessTests.java    License: MIT License 6 votes vote down vote up
@Test
public void testGetValuePerformance() throws Exception {
	Assume.group(TestGroup.PERFORMANCE);
	Map<String, String> map = new HashMap<>();
	map.put("key", "value");
	EvaluationContext context = new StandardEvaluationContext(map);

	ExpressionParser spelExpressionParser = new SpelExpressionParser();
	Expression expr = spelExpressionParser.parseExpression("#root['key']");

	StopWatch s = new StopWatch();
	s.start();
	for (int i = 0; i < 10000; i++) {
		expr.getValue(context);
	}
	s.stop();
	assertThat(s.getTotalTimeMillis(), lessThan(200L));
}
 
Example 9
Source Project: spring-analysis-note   Source File: SpelExceptionTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void spelExpressionMapWithVariables() {
	ExpressionParser parser = new SpelExpressionParser();
	Expression spelExpression = parser.parseExpression("#aMap['one'] eq 1");
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariables(new HashMap<String, Object>() {
		{
			put("aMap", new HashMap<String, Integer>() {
				{
					put("one", 1);
					put("two", 2);
					put("three", 3);
				}
			});

		}
	});
	boolean result = spelExpression.getValue(ctx, Boolean.class);
	assertTrue(result);

}
 
Example 10
Source Project: spring-analysis-note   Source File: SpelExceptionTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void spelExpressionListIndexAccessWithVariables() {
	ExpressionParser parser = new SpelExpressionParser();
	Expression spelExpression = parser.parseExpression("#aList[0] eq 'one'");
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariables(new HashMap<String, Object>() {
		{
			put("aList", new ArrayList<String>() {
				{
					add("one");
					add("two");
					add("three");
				}
			});

		}
	});
	boolean result = spelExpression.getValue(ctx, Boolean.class);
	assertTrue(result);
}
 
Example 11
Source Project: java-technology-stack   Source File: SpelExceptionTests.java    License: MIT License 6 votes vote down vote up
@Test
@SuppressWarnings("serial")
public void spelExpressionListIndexAccessWithVariables() {
	ExpressionParser parser = new SpelExpressionParser();
	Expression spelExpression = parser.parseExpression("#aList[0] eq 'one'");
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariables(new HashMap<String, Object>() {
		{
			put("aList", new ArrayList<String>() {
				{
					add("one");
					add("two");
					add("three");
				}
			});

		}
	});
	boolean result = spelExpression.getValue(ctx, Boolean.class);
	assertTrue(result);
}
 
Example 12
Source Project: spring-analysis-note   Source File: SpelReproTests.java    License: MIT License 6 votes vote down vote up
/**
 * 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 13
Source Project: gpmall   Source File: DistributedLockAspect.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * 获取缓存的key
 * key 定义在注解上,支持SPEL表达式
 */
private String parseKey(String key, Method method, Object[] args) {
    //获取被拦截方法参数名列表(使用Spring支持类库)
    LocalVariableTableParameterNameDiscoverer u =
            new LocalVariableTableParameterNameDiscoverer();
    String[] paraNameArr = u.getParameterNames(method);

    //使用SPEL进行key的解析
    ExpressionParser parser = new SpelExpressionParser();
    //SPEL上下文
    StandardEvaluationContext context = new StandardEvaluationContext();
    //把方法参数放入SPEL上下文中
    for (int i = 0; i < paraNameArr.length; i++) {
        context.setVariable(paraNameArr[i], args[i]);
    }
    return parser.parseExpression(key).getValue(context, String.class);
}
 
Example 14
Source Project: mall4j   Source File: SpelUtil.java    License: 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 15
Source Project: spring-analysis-note   Source File: SpelReproTests.java    License: MIT License 6 votes vote down vote up
@Test
public void SPR9735() {
	Item item = new Item();
	item.setName("parent");

	Item item1 = new Item();
	item1.setName("child1");

	Item item2 = new Item();
	item2.setName("child2");

	item.add(item1);
	item.add(item2);

	ExpressionParser parser = new SpelExpressionParser();
	EvaluationContext context = new StandardEvaluationContext();
	Expression exp = parser.parseExpression("#item[0].name");
	context.setVariable("item", item);

	assertEquals("child1", exp.getValue(context));
}
 
Example 16
Source Project: java-technology-stack   Source File: EvaluationTests.java    License: MIT License 5 votes vote down vote up
private void expectFail(ExpressionParser parser, EvaluationContext eContext, String expressionString, SpelMessage messageCode) {
	try {
		Expression e = parser.parseExpression(expressionString);
		SpelUtilities.printAbstractSyntaxTree(System.out, e);
		e.getValue(eContext);
		fail();
	}
	catch (SpelEvaluationException see) {
		assertEquals(messageCode, see.getMessageCode());
	}
}
 
Example 17
Source Project: java-technology-stack   Source File: EvaluationTests.java    License: MIT License 5 votes vote down vote up
/**
 * Verifies behavior requested in SPR-9613.
 */
@Test
public void caseInsensitiveNullLiterals() {
	ExpressionParser parser = new SpelExpressionParser();

	Expression e = parser.parseExpression("null");
	assertNull(e.getValue());

	e = parser.parseExpression("NULL");
	assertNull(e.getValue());

	e = parser.parseExpression("NuLl");
	assertNull(e.getValue());
}
 
Example 18
Source Project: spring-analysis-note   Source File: SpelDocumentationTests.java    License: MIT License 5 votes vote down vote up
@Test
	public void testPropertyNavigation() throws Exception {
		ExpressionParser parser = new SpelExpressionParser();

		// Inventions Array
		StandardEvaluationContext teslaContext = TestScenarioCreator.getTestEvaluationContext();
//		teslaContext.setRootObject(tesla);

		// evaluates to "Induction motor"
		String invention = parser.parseExpression("inventions[3]").getValue(teslaContext, String.class);
		assertEquals("Induction motor",invention);

		// Members List
		StandardEvaluationContext societyContext = new StandardEvaluationContext();
		IEEE ieee = new IEEE();
		ieee.Members[0]= tesla;
		societyContext.setRootObject(ieee);

		// evaluates to "Nikola Tesla"
		String name = parser.parseExpression("Members[0].Name").getValue(societyContext, String.class);
		assertEquals("Nikola Tesla",name);

		// List and Array navigation
		// evaluates to "Wireless communication"
		invention = parser.parseExpression("Members[0].Inventions[6]").getValue(societyContext, String.class);
		assertEquals("Wireless communication",invention);
	}
 
Example 19
Source Project: spring-analysis-note   Source File: SpelDocumentationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testFunctions() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.registerFunction("reverseString", StringUtils.class.getDeclaredMethod("reverseString", String.class));

	String helloWorldReversed = parser.parseExpression("#reverseString('hello world')").getValue(context, String.class);
	assertEquals("dlrow olleh",helloWorldReversed);
}
 
Example 20
Source Project: java-technology-stack   Source File: EvaluationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void decrement01root() {
	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());
	}
}
 
Example 21
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR9486_multiplyFloatWithFloat() {
	Number expectedNumber = 10.21f * 10.2f;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("10.21f * 10.2f");
	Number result = expression.getValue(context, null, Number.class);
	assertEquals(expectedNumber, result);
}
 
Example 22
Source Project: spring-analysis-note   Source File: EvaluationTests.java    License: MIT License 5 votes vote down vote up
@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());
	}
}
 
Example 23
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR16123() {
	ExpressionParser parser = new SpelExpressionParser();
	parser.parseExpression("simpleProperty").setValue(new BooleanHolder(), null);

	try {
		parser.parseExpression("primitiveProperty").setValue(new BooleanHolder(), null);
		fail("Should have thrown EvaluationException");
	}
	catch (EvaluationException ex) {
		// expected
	}
}
 
Example 24
Source Project: java-technology-stack   Source File: SpelDocumentationTests.java    License: MIT License 5 votes vote down vote up
@Test
	public void testPropertyNavigation() throws Exception {
		ExpressionParser parser = new SpelExpressionParser();

		// Inventions Array
		StandardEvaluationContext teslaContext = TestScenarioCreator.getTestEvaluationContext();
//		teslaContext.setRootObject(tesla);

		// evaluates to "Induction motor"
		String invention = parser.parseExpression("inventions[3]").getValue(teslaContext, String.class);
		assertEquals("Induction motor",invention);

		// Members List
		StandardEvaluationContext societyContext = new StandardEvaluationContext();
		IEEE ieee = new IEEE();
		ieee.Members[0]= tesla;
		societyContext.setRootObject(ieee);

		// evaluates to "Nikola Tesla"
		String name = parser.parseExpression("Members[0].Name").getValue(societyContext, String.class);
		assertEquals("Nikola Tesla",name);

		// List and Array navigation
		// evaluates to "Wireless communication"
		invention = parser.parseExpression("Members[0].Inventions[6]").getValue(societyContext, String.class);
		assertEquals("Wireless communication",invention);
	}
 
Example 25
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR9486_floatPowerDouble() {
	Number expectedResult = Math.pow(10.21f, 10.2);
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("10.21f ^ 10.2");
	Number result = expression.getValue(context, null, Number.class);
	assertEquals(expectedResult, result);
}
 
Example 26
Source Project: spring-analysis-note   Source File: MapAccessTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testCustomMapAccessor() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = TestScenarioCreator.getTestEvaluationContext();
	ctx.addPropertyAccessor(new MapAccessor());

	Expression expr = parser.parseExpression("testMap.monday");
	Object value = expr.getValue(ctx, String.class);
	assertEquals("montag", value);
}
 
Example 27
Source Project: spring-analysis-note   Source File: MapAccessTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testVariableMapAccess() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = TestScenarioCreator.getTestEvaluationContext();
	ctx.setVariable("day", "saturday");

	Expression expr = parser.parseExpression("testMap[#day]");
	Object value = expr.getValue(ctx, String.class);
	assertEquals("samstag", value);
}
 
Example 28
Source Project: spring-analysis-note   Source File: MapAccessTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testGetValue(){
	Map<String,String> props1 = new HashMap<>();
	props1.put("key1", "value1");
	props1.put("key2", "value2");
	props1.put("key3", "value3");

	Object bean = new TestBean("name1", new TestBean("name2", null, "Description 2", 15, props1), "description 1", 6, props1);

	ExpressionParser parser = new SpelExpressionParser();
	Expression expr = parser.parseExpression("testBean.properties['key2']");
	assertEquals("value2", expr.getValue(bean));
}
 
Example 29
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR9486_floatGreaterThanFloat() {
	Boolean expectedNumber = -10.21f > -10.2f;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("-10.21f > -10.2f");
	Boolean result = expression.getValue(context, null, Boolean.class);
	assertEquals(expectedNumber, result);
}
 
Example 30
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR9486_floatFunctionResolver() {
	Number expectedResult = Math.abs(-10.2f);
	ExpressionParser parser = new SpelExpressionParser();
	SPR9486_FunctionsClass testObject = new SPR9486_FunctionsClass();

	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("abs(-10.2f)");
	Number result = expression.getValue(context, testObject, Number.class);
	assertEquals(expectedResult, result);
}