Java Code Examples for org.springframework.expression.EvaluationContext

The following examples show how to use org.springframework.expression.EvaluationContext. 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
@Override
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
	MessageHeaders headers = (MessageHeaders) target;
	SimpMessageHeaderAccessor accessor =
			MessageHeaderAccessor.getAccessor(headers, SimpMessageHeaderAccessor.class);
	Object value;
	if ("destination".equalsIgnoreCase(name)) {
		value = accessor.getDestination();
	}
	else {
		value = accessor.getFirstNativeHeader(name);
		if (value == null) {
			value = headers.get(name);
		}
	}
	return new TypedValue(value);
}
 
Example 2
@Override
public TypedValue execute(EvaluationContext context, Object target, Object... arguments) throws AccessException {
	try {
		if (arguments != null) {
			this.argumentConversionOccurred = ReflectionHelper.convertArguments(
					context.getTypeConverter(), arguments, this.method, this.varargsPosition);
			if (this.method.isVarArgs()) {
				arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(
						this.method.getParameterTypes(), arguments);
			}
		}
		ReflectionUtils.makeAccessible(this.method);
		Object value = this.method.invoke(target, arguments);
		return new TypedValue(value, new TypeDescriptor(new MethodParameter(this.method, -1)).narrow(value));
	}
	catch (Exception ex) {
		throw new AccessException("Problem invoking method: " + this.method, ex);
	}
}
 
Example 3
Source Project: java-technology-stack   Source File: ReflectivePropertyAccessor.java    License: MIT License 6 votes vote down vote up
@Nullable
private TypeDescriptor getTypeDescriptor(EvaluationContext context, Object target, String name) {
	Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());

	if (type.isArray() && name.equals("length")) {
		return TypeDescriptor.valueOf(Integer.TYPE);
	}
	PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class);
	TypeDescriptor typeDescriptor = this.typeDescriptorCache.get(cacheKey);
	if (typeDescriptor == null) {
		// Attempt to populate the cache entry
		try {
			if (canRead(context, target, name) || canWrite(context, target, name)) {
				typeDescriptor = this.typeDescriptorCache.get(cacheKey);
			}
		}
		catch (AccessException ex) {
			// Continue with null type descriptor
		}
	}
	return typeDescriptor;
}
 
Example 4
@Override
public TypedValue execute(EvaluationContext context, Object... arguments) throws AccessException {
	try {
		ReflectionHelper.convertArguments(
				context.getTypeConverter(), arguments, this.ctor, this.varargsPosition);
		if (this.ctor.isVarArgs()) {
			arguments = ReflectionHelper.setupArgumentsForVarargsInvocation(
					this.ctor.getParameterTypes(), arguments);
		}
		ReflectionUtils.makeAccessible(this.ctor);
		return new TypedValue(this.ctor.newInstance(arguments));
	}
	catch (Exception ex) {
		throw new AccessException("Problem invoking constructor: " + this.ctor, ex);
	}
}
 
Example 5
Source Project: spring-analysis-note   Source File: PropertyAccessTests.java    License: MIT License 6 votes vote down vote up
@Test
public void propertyReadWriteWithRootObject() {
	Person target = new Person("p1");
	EvaluationContext context = SimpleEvaluationContext.forReadWriteDataBinding().withRootObject(target).build();
	assertSame(target, context.getRootObject().getValue());

	Expression expr = parser.parseExpression("name");
	assertEquals("p1", expr.getValue(context, target));
	target.setName("p2");
	assertEquals("p2", expr.getValue(context, target));

	parser.parseExpression("name='p3'").getValue(context, target);
	assertEquals("p3", target.getName());
	assertEquals("p3", expr.getValue(context, target));

	expr.setValue(context, target, "p4");
	assertEquals("p4", target.getName());
	assertEquals("p4", expr.getValue(context, target));
}
 
Example 6
@Test
public void selectionWithPrimitiveArray() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("ints.?[#this<5]");
	EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean());
	Object value = expression.getValue(context);
	assertTrue(value.getClass().isArray());
	TypedValue typedValue = new TypedValue(value);
	assertEquals(Integer.class, typedValue.getTypeDescriptor().getElementTypeDescriptor().getType());
	Integer[] array = (Integer[]) value;
	assertEquals(5, array.length);
	assertEquals(new Integer(0), array[0]);
	assertEquals(new Integer(1), array[1]);
	assertEquals(new Integer(2), array[2]);
	assertEquals(new Integer(3), array[3]);
	assertEquals(new Integer(4), array[4]);
}
 
Example 7
Source Project: java-technology-stack   Source File: SpelExpression.java    License: MIT License 6 votes vote down vote up
@Override
@Nullable
public Object getValue() throws EvaluationException {
	if (this.compiledAst != null) {
		try {
			EvaluationContext context = getEvaluationContext();
			return this.compiledAst.getValue(context.getRootObject().getValue(), context);
		}
		catch (Throwable ex) {
			// If running in mixed mode, revert to interpreted
			if (this.configuration.getCompilerMode() == SpelCompilerMode.MIXED) {
				this.interpretedCount = 0;
				this.compiledAst = null;
			}
			else {
				// Running in SpelCompilerMode.immediate mode - propagate exception to caller
				throw new SpelEvaluationException(ex, SpelMessage.EXCEPTION_RUNNING_COMPILED_EXPRESSION);
			}
		}
	}

	ExpressionState expressionState = new ExpressionState(getEvaluationContext(), this.configuration);
	Object result = this.ast.getValue(expressionState);
	checkCompile(expressionState);
	return result;
}
 
Example 8
/**
 * 创建SpEL执行上下文
 *
 * @param rootObject
 *            SpEL表达式根对象
 * @param context
 *            Beetl上下文对象
 * @return SpEL表达式执行上下文
 */
private EvaluationContext createEvaluationContext(Object rootObject, Context beetlContext) {
	StandardEvaluationContext context = new StandardEvaluationContext(rootObject);

	// 允许使用#context访问Beetl上下文
	context.setVariable("context", beetlContext);
	// 允许使用#global访问Beetl上下文的全局变量
	context.setVariable("global", beetlContext.globalVar);
	// 注册WebRender定义的全局变量
	context.setVariable("ctxPath", beetlContext.getGlobal("ctxPath"));
	context.setVariable("servlet", beetlContext.getGlobal("servlet"));
	context.setVariable("parameter", beetlContext.getGlobal("parameter"));
	context.setVariable("request", beetlContext.getGlobal("request"));
	context.setVariable("session", beetlContext.getGlobal("session"));
	// 允许使用属性格式访问Map
	context.addPropertyAccessor(new MapAccessor());
	// 允许访问Spring容器Bean
	context.setBeanResolver(new BeanFactoryResolver(applicationContext));

	return context;
}
 
Example 9
Source Project: java-technology-stack   Source File: MethodReference.java    License: MIT License 6 votes vote down vote up
@Nullable
private MethodExecutor getCachedExecutor(EvaluationContext evaluationContext, Object value,
		@Nullable TypeDescriptor target, List<TypeDescriptor> argumentTypes) {

	List<MethodResolver> methodResolvers = evaluationContext.getMethodResolvers();
	if (methodResolvers.size() != 1 || !(methodResolvers.get(0) instanceof ReflectiveMethodResolver)) {
		// Not a default ReflectiveMethodResolver - don't know whether caching is valid
		return null;
	}

	CachedMethodExecutor executorToCheck = this.cachedExecutor;
	if (executorToCheck != null && executorToCheck.isSuitable(value, target, argumentTypes)) {
		return executorToCheck.get();
	}
	this.cachedExecutor = null;
	return null;
}
 
Example 10
/**
 * Create an {@link EvaluationContext}.
 * @param caches the current caches
 * @param method the method
 * @param args the method arguments
 * @param target the target object
 * @param targetClass the target class
 * @param result the return value (can be {@code null}) or
 * {@link #NO_RESULT} if there is no return at this time
 * @return the evaluation context
 */
public EvaluationContext createEvaluationContext(Collection<? extends Cache> caches,
		Method method, Object[] args, Object target, Class<?> targetClass, Method targetMethod,
		@Nullable Object result, @Nullable BeanFactory beanFactory) {

	CacheExpressionRootObject rootObject = new CacheExpressionRootObject(
			caches, method, args, target, targetClass);
	CacheEvaluationContext evaluationContext = new CacheEvaluationContext(
			rootObject, targetMethod, args, getParameterNameDiscoverer());
	if (result == RESULT_UNAVAILABLE) {
		evaluationContext.addUnavailableVariable(RESULT_VARIABLE);
	}
	else if (result != NO_RESULT) {
		evaluationContext.setVariable(RESULT_VARIABLE, result);
	}
	if (beanFactory != null) {
		evaluationContext.setBeanResolver(new BeanFactoryResolver(beanFactory));
	}
	return evaluationContext;
}
 
Example 11
Source Project: spring-data-keyvalue   Source File: SpelCriteria.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates new {@link SpelCriteria}.
 *
 * @param expression must not be {@literal null}.
 * @param context must not be {@literal null}.
 */
public SpelCriteria(SpelExpression expression, EvaluationContext context) {

	Assert.notNull(expression, "SpEL expression must not be null!");
	Assert.notNull(context, "EvaluationContext must not be null!");

	this.expression = expression;
	this.context = context;
}
 
Example 12
Source Project: piper   Source File: Sort.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public TypedValue execute(EvaluationContext aContext, Object aTarget, Object... aArguments) throws AccessException {
  Collection<?> list = (Collection<?>) aArguments[0];
  List<?> sorted = list.stream()
                       .sorted()
                       .collect(Collectors.toList());
  return new TypedValue(sorted);
}
 
Example 13
Source Project: spring-analysis-note   Source File: SelectionAndProjectionTests.java    License: MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void selectFirstItemInMap() {
	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("beige", colorsMap.keySet().iterator().next());
}
 
Example 14
@Test
public void projectionWithSet() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("#testList.![wrapper.value]");
	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("testList", IntegerTestBean.createSet());
	Object value = expression.getValue(context);
	assertTrue(value instanceof List);
	List<?> list = (List<?>) value;
	assertEquals(3, list.size());
	assertEquals(5, list.get(0));
	assertEquals(6, list.get(1));
	assertEquals(7, list.get(2));
}
 
Example 15
@Override
public String getValue(EvaluationContext context) throws EvaluationException {
	StringBuilder sb = new StringBuilder();
	for (Expression expression : this.expressions) {
		String value = expression.getValue(context, String.class);
		if (value != null) {
			sb.append(value);
		}
	}
	return sb.toString();
}
 
Example 16
Source Project: spring-analysis-note   Source File: EvaluationTests.java    License: MIT License 5 votes vote down vote up
@Override
public Object resolve(EvaluationContext context, String beanName) throws AccessException {
	if (beanName.equals("foo") || beanName.equals("bar")) {
		return new Spr9751_2();
	}
	throw new AccessException("not heard of " + beanName);
}
 
Example 17
Source Project: java-technology-stack   Source File: ExpressionStateTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testRootObjectConstructor() {
	EvaluationContext ctx = getContext();
	// TypedValue root = ctx.getRootObject();
	// supplied should override root on context
	ExpressionState state = new ExpressionState(ctx,new TypedValue("i am a string"));
	TypedValue stateRoot = state.getRootContextObject();
	assertEquals(String.class, stateRoot.getTypeDescriptor().getType());
	assertEquals("i am a string", stateRoot.getValue());
}
 
Example 18
private TypeDescriptor getTypeDescriptor(EvaluationContext context, Object target, String name) {
	if (target == null) {
		return null;
	}
	Class<?> type = (target instanceof Class ? (Class<?>) target : target.getClass());

	if (type.isArray() && name.equals("length")) {
		return TypeDescriptor.valueOf(Integer.TYPE);
	}
	PropertyCacheKey cacheKey = new PropertyCacheKey(type, name, target instanceof Class);
	TypeDescriptor typeDescriptor = this.typeDescriptorCache.get(cacheKey);
	if (typeDescriptor == null) {
		// attempt to populate the cache entry
		try {
			if (canRead(context, target, name)) {
				typeDescriptor = this.typeDescriptorCache.get(cacheKey);
			}
			else if (canWrite(context, target, name)) {
				typeDescriptor = this.typeDescriptorCache.get(cacheKey);
			}
		}
		catch (AccessException ex) {
			// continue with null type descriptor
		}
	}
	return typeDescriptor;
}
 
Example 19
Source Project: spring-analysis-note   Source File: MapAccessor.java    License: MIT License 5 votes vote down vote up
@Override
public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
	Assert.state(target instanceof Map, "Target must be of type Map");
	Map<?, ?> map = (Map<?, ?>) target;
	Object value = map.get(name);
	if (value == null && !map.containsKey(name)) {
		throw new MapAccessException(name);
	}
	return new TypedValue(value);
}
 
Example 20
Source Project: spring-analysis-note   Source File: MapAccessor.java    License: MIT License 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue)
		throws AccessException {

	Assert.state(target instanceof Map, "Target must be a Map");
	Map<Object, Object> map = (Map<Object, Object>) target;
	map.put(name, newValue);
}
 
Example 21
Source Project: spring4-understanding   Source File: EvaluationTests.java    License: Apache License 2.0 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) {
		see.printStackTrace();
		assertEquals(messageCode,see.getMessageCode());
	}
}
 
Example 22
Source Project: spring-analysis-note   Source File: CacheAspectSupport.java    License: MIT License 5 votes vote down vote up
/**
 * Compute the key for the given caching operation.
 */
@Nullable
protected Object generateKey(@Nullable Object result) {
	if (StringUtils.hasText(this.metadata.operation.getKey())) {
		EvaluationContext evaluationContext = createEvaluationContext(result);
		return evaluator.key(this.metadata.operation.getKey(), this.metadata.methodKey, evaluationContext);
	}
	return this.metadata.keyGenerator.generate(this.target, this.metadata.method, this.args);
}
 
Example 23
Source Project: spring-analysis-note   Source File: SelectionAndProjectionTests.java    License: MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void selectionWithMap() {
	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(3, colorsMap.size());
	assertTrue(colorsMap.containsKey("beige"));
	assertTrue(colorsMap.containsKey("blue"));
	assertTrue(colorsMap.containsKey("brown"));
}
 
Example 24
Source Project: java-technology-stack   Source File: SpelDocumentationTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testPropertyAccess() throws Exception {
	EvaluationContext context = TestScenarioCreator.getTestEvaluationContext();
	int year = (Integer) parser.parseExpression("Birthdate.Year + 1900").getValue(context); // 1856
	assertEquals(1856,year);

	String city = (String) parser.parseExpression("placeOfBirth.City").getValue(context);
	assertEquals("SmilJan",city);
}
 
Example 25
@Test
public void selectFirstItemInSet() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("integers.^[#this<5]");
	EvaluationContext context = new StandardEvaluationContext(new SetTestBean());
	Object value = expression.getValue(context);
	assertTrue(value instanceof Integer);
	assertEquals(0, value);
}
 
Example 26
Source Project: java-master   Source File: SpELTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test5() {
    Inventor tesla = new Inventor("Nikola Tesla", new Date(), "Serbian");
    EvaluationContext context = new StandardEvaluationContext(tesla);

    // null时取默认值及null时安全调用
    logger.info(parser.parseExpression("name?:'Unknown'").getValue(context, String.class));
    logger.info(parser.parseExpression("name?.length()").getValue(context, Integer.class).toString());

    tesla.setName(null);
    logger.info(parser.parseExpression("name?:'Unknown'").getValue(context, String.class));
    logger.info(String.valueOf(parser.parseExpression("name?.length()").getValue(context, Integer.class)));
}
 
Example 27
Source Project: spring-analysis-note   Source File: SelectionAndProjectionTests.java    License: MIT License 5 votes vote down vote up
@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 28
Source Project: ignite   Source File: SpelEvaluator.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Evaluate all the SpEL expressions in {@link #parameters} based on values provided as an argument.
 *
 * @param values Parameter values. Must not be {@literal null}.
 * @return a map from parameter name to evaluated value. Guaranteed to be not {@literal null}.
 */
public Map<String, Object> evaluate(Object[] values) {
    Assert.notNull(values, "Values must not be null.");

    EvaluationContext evaluationCtx = evaluationCtxProvider.getEvaluationContext(parameters, values);

    return extractor.getParameters().collect(Collectors.toMap(//
        Map.Entry::getKey, //
        it -> getSpElValue(evaluationCtx, it.getValue()) //
    ));
}
 
Example 29
Source Project: spring-analysis-note   Source File: EvalTag.java    License: MIT License 5 votes vote down vote up
@Override
public TypedValue read(EvaluationContext context, @Nullable Object target, String name) throws AccessException {
	Object implicitVar = resolveImplicitVariable(name);
	if (implicitVar != null) {
		return new TypedValue(implicitVar);
	}
	return new TypedValue(this.pageContext.findAttribute(name));
}
 
Example 30
Source Project: spring-analysis-note   Source File: CompositeStringExpression.java    License: MIT License 5 votes vote down vote up
@Override
public String getValue(EvaluationContext context, Object rootObject) throws EvaluationException {
	StringBuilder sb = new StringBuilder();
	for (Expression expression : this.expressions) {
		String value = expression.getValue(context, rootObject, String.class);
		if (value != null) {
			sb.append(value);
		}
	}
	return sb.toString();
}