org.springframework.expression.EvaluationContext Java Examples

The following examples show how to use org.springframework.expression.EvaluationContext. 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: SpELFunction.java    From beetl2.0 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * 创建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 #2
Source File: MethodReference.java    From java-technology-stack with 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 #3
Source File: PropertyAccessTests.java    From spring-analysis-note with 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 #4
Source File: ReflectiveConstructorExecutor.java    From java-technology-stack with MIT License 6 votes vote down vote up
@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 File: SelectionAndProjectionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #6
Source File: CacheOperationExpressionEvaluator.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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 #7
Source File: ReflectivePropertyAccessor.java    From java-technology-stack with 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 #8
Source File: ReflectiveMethodExecutor.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@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 #9
Source File: SpelExpression.java    From java-technology-stack with 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 #10
Source File: DefaultSubscriptionRegistry.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 #11
Source File: MapAccessor.java    From spring-analysis-note with 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 #12
Source File: EvalTag.java    From java-technology-stack with 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 #13
Source File: EvaluationTests.java    From spring4-understanding with 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 #14
Source File: MapAccessor.java    From spring-analysis-note with 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 #15
Source File: CacheAspectSupport.java    From spring-analysis-note with 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 #16
Source File: MethodReference.java    From java-technology-stack with MIT License 5 votes vote down vote up
private MethodExecutor findAccessorForMethod(List<TypeDescriptor> argumentTypes, Object targetObject,
		EvaluationContext evaluationContext) throws SpelEvaluationException {

	AccessException accessException = null;
	List<MethodResolver> methodResolvers = evaluationContext.getMethodResolvers();
	for (MethodResolver methodResolver : methodResolvers) {
		try {
			MethodExecutor methodExecutor = methodResolver.resolve(
					evaluationContext, targetObject, this.name, argumentTypes);
			if (methodExecutor != null) {
				return methodExecutor;
			}
		}
		catch (AccessException ex) {
			accessException = ex;
			break;
		}
	}

	String method = FormatHelper.formatMethodForMessage(this.name, argumentTypes);
	String className = FormatHelper.formatClassNameForMessage(
			targetObject instanceof Class ? ((Class<?>) targetObject) : targetObject.getClass());
	if (accessException != null) {
		throw new SpelEvaluationException(
				getStartPosition(), accessException, SpelMessage.PROBLEM_LOCATING_METHOD, method, className);
	}
	else {
		throw new SpelEvaluationException(getStartPosition(), SpelMessage.METHOD_NOT_FOUND, method, className);
	}
}
 
Example #17
Source File: SelectionAndProjectionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void projectionWithIterable() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("#testList.![wrapper.value]");
	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("testList", IntegerTestBean.createIterable());
	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 #18
Source File: CompositeStringExpression.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 #19
Source File: Range.java    From piper with Apache License 2.0 5 votes vote down vote up
@Override
public TypedValue execute(EvaluationContext aContext, Object aTarget, Object... aArguments) throws AccessException {
  List<Integer> value = IntStream.rangeClosed((int)aArguments[0], (int)aArguments[1])
      .boxed()
      .collect(Collectors.toList());
  return new TypedValue(value);
}
 
Example #20
Source File: SelectionAndProjectionTests.java    From spring-analysis-note with 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 #21
Source File: SpelDocumentationTests.java    From java-technology-stack with 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 #22
Source File: SpelReproTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void SPR13918() {
	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("encoding", "UTF-8");

	Expression ex = parser.parseExpression("T(java.nio.charset.Charset).forName(#encoding)");
	Object result = ex.getValue(context);
	assertEquals(StandardCharsets.UTF_8, result);
}
 
Example #23
Source File: SelectionAndProjectionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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 #24
Source File: SpELTest.java    From java-master with 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 #25
Source File: SelectionAndProjectionTests.java    From spring-analysis-note with 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 #26
Source File: SpelEvaluator.java    From ignite with 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 #27
Source File: EvalTag.java    From spring-analysis-note with 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 #28
Source File: CompositeStringExpression.java    From spring-analysis-note with 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();
}
 
Example #29
Source File: SpelCompilationCoverageTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
public TypedValue read(EvaluationContext context, Object target, String name) throws AccessException {
	Map<?,?> map = (Map<?,?>) target;
	Object value = map.get(name);
	if (value == null && !map.containsKey(name)) {
		throw new MapAccessException(name);
	}
	return new TypedValue(value);
}
 
Example #30
Source File: KafkaExpressionEvaluatingInterceptor.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 5 votes vote down vote up
/**
 * Construct an instance with the provided expressions and evaluation context. At
 * least one expression muse be non-null.
 * @param messageKeyExpression the routing key expression.
 * @param evaluationContext the evaluation context.
 */
public KafkaExpressionEvaluatingInterceptor(Expression messageKeyExpression, EvaluationContext evaluationContext) {
	Assert.notNull(messageKeyExpression != null, "A message key expression is required");
	Assert.notNull(evaluationContext, "the 'evaluationContext' cannot be null");
	this.messageKeyExpression = messageKeyExpression;
	this.evaluationContext = evaluationContext;
}