Java Code Examples for org.springframework.expression.spel.support.StandardEvaluationContext#setBeanResolver()

The following examples show how to use org.springframework.expression.spel.support.StandardEvaluationContext#setBeanResolver() . 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
static Object getValue(SpelExpressionParser parser, BeanFactory beanFactory,
		String entryValue) {
	Object value;
	String rawValue = entryValue;
	if (rawValue != null) {
		rawValue = rawValue.trim();
	}
	if (rawValue != null && rawValue.startsWith("#{") && entryValue.endsWith("}")) {
		// assume it's spel
		StandardEvaluationContext context = new StandardEvaluationContext();
		context.setBeanResolver(new BeanFactoryResolver(beanFactory));
		Expression expression = parser.parseExpression(entryValue,
				new TemplateParserContext());
		value = expression.getValue(context);
	}
	else {
		value = entryValue;
	}
	return value;
}
 
Example 2
private static Object getValue(SpelExpressionParser parser, BeanFactory beanFactory,
                               String entryValue) {
    Object value;
    String rawValue = entryValue;
    if (rawValue != null) {
        rawValue = rawValue.trim();
    }
    if (rawValue != null && rawValue.startsWith("#{") && entryValue.endsWith("}")) {
        // assume it's spel
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setBeanResolver(new BeanFactoryResolver(beanFactory));
        Expression expression = parser.parseExpression(entryValue,
                new TemplateParserContext());
        context.lookupVariable("api");
        value = expression.getValue(context);
    } else {
        value = entryValue;
    }
    return value;
}
 
Example 3
private QueryMethodEvaluationContextProvider delegateContextProvider(
		QueryMethodEvaluationContextProvider evaluationContextProvider) {
	return new QueryMethodEvaluationContextProvider() {
		@Override
		public <T extends Parameters<?, ?>> EvaluationContext getEvaluationContext(
				T parameters, Object[] parameterValues) {
			StandardEvaluationContext evaluationContext = (StandardEvaluationContext)
					evaluationContextProvider
					.getEvaluationContext(parameters, parameterValues);
			evaluationContext.setRootObject(
					DatastoreRepositoryFactory.this.applicationContext);
			evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());
			evaluationContext.setBeanResolver(new BeanFactoryResolver(
					DatastoreRepositoryFactory.this.applicationContext));
			return evaluationContext;
		}
	};
}
 
Example 4
/**
 * 创建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 5
/**
 * Creates the key filter lambda which is responsible to decide how the rate limit will be performed. The key
 * is the unique identifier like an IP address or a username.
 * 
 * @param url is used to generated a unique cache key
 * @param rateLimit the {@link RateLimit} configuration which holds the skip condition string
 * @param expressionParser is used to evaluate the expression if the filter key type is EXPRESSION.
 * @param beanFactory used to get full access to all java beans in the SpEl
 * @return should not been null. If no filter key type is matching a plain 1 is returned so that all requests uses the same key.
 */
public KeyFilter<R> getKeyFilter(String url, RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) {
	
	String expression = rateLimit.getExpression();
	if(StringUtils.isEmpty(expression)) {
		throw new MissingKeyFilterExpressionException();
	}
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new BeanFactoryResolver(beanFactory));
	return  (request) -> {
		//TODO performance problem - how can the request object reused in the expression without setting it as a rootObject
		Expression expr = expressionParser.parseExpression(rateLimit.getExpression()); 
		final String value = expr.getValue(context, request, String.class);
		return url + "-" + value;
	};

	
}
 
Example 6
public static Validator testValidator(VerifierMode verifierMode) {
    TestModel.setFit(true);

    Map<String, Object> registeredObjects = singletonMap("env", System.getProperties());

    Supplier<EvaluationContext> spelContextFactory = () -> {
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.registerFunction("fit", TestModel.getFitMethod());
        context.setBeanResolver((ctx, beanName) -> registeredObjects.get(beanName));
        return context;
    };

    return Validation.buildDefaultValidatorFactory()
            .usingContext()
            .constraintValidatorFactory(new ConstraintValidatorFactoryWrapper(verifierMode, type -> Optional.empty(), spelContextFactory))
            .messageInterpolator(new SpELMessageInterpolator(spelContextFactory))
            .getValidator();
}
 
Example 7
Source Project: spring-analysis-note   File: EvalTag.java    License: MIT License 5 votes vote down vote up
private EvaluationContext createEvaluationContext(PageContext pageContext) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new JspPropertyAccessor(pageContext));
	context.addPropertyAccessor(new MapAccessor());
	context.addPropertyAccessor(new EnvironmentAccessor());
	context.setBeanResolver(new BeanFactoryResolver(getRequestContext().getWebApplicationContext()));
	ConversionService conversionService = getConversionService(pageContext);
	if (conversionService != null) {
		context.setTypeConverter(new StandardTypeConverter(conversionService));
	}
	return context;
}
 
Example 8
@Test
public void SPR11445_beanReference() {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new Spr11445Class());
	Expression expr = new SpelExpressionParser().parseRaw("@bean.echo(@bean.parameter())");
	assertEquals(1, expr.getValue(context));
}
 
Example 9
/**
 * 包含方法上的参数的上下文
 *
 * @param secureExpressionHandler 上下文处理器
 * @param method                  方法
 * @param args                    参数
 * @return 上下文
 */
public static StandardEvaluationContext getEvaluationContext(SecureExpressionHandler secureExpressionHandler, Method method, Object[] args) {
	// 初始化Spel表达式上下文,并设置 处理函数
	StandardEvaluationContext context = new StandardEvaluationContext(secureExpressionHandler);
	// 设置表达式支持spring bean
	context.setBeanResolver(new BeanFactoryResolver(SpringUtil.getContext()));
	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 10
/**
 * 设置 request/response 参数的上下文
 *
 * @param secureExpressionHandler 上下文处理器
 * @param request                 请求
 * @param response                响应
 * @return 上下文
 */
public static StandardEvaluationContext getEvaluationContext(SecureExpressionHandler secureExpressionHandler, HttpServletRequest request, HttpServletResponse response) {
	// 初始化Sp el表达式上下文,并设置 处理函数
	StandardEvaluationContext context = new StandardEvaluationContext(secureExpressionHandler);
	// 设置表达式支持spring bean
	context.setBeanResolver(new BeanFactoryResolver(SpringUtil.getContext()));
	context.setVariable(SecureConstants.REQUEST, request);
	context.setVariable(SecureConstants.RESPONSE, response);
	return context;
}
 
Example 11
Source Project: java-technology-stack   File: EvalTag.java    License: MIT License 5 votes vote down vote up
private EvaluationContext createEvaluationContext(PageContext pageContext) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new JspPropertyAccessor(pageContext));
	context.addPropertyAccessor(new MapAccessor());
	context.addPropertyAccessor(new EnvironmentAccessor());
	context.setBeanResolver(new BeanFactoryResolver(getRequestContext().getWebApplicationContext()));
	ConversionService conversionService = getConversionService(pageContext);
	if (conversionService != null) {
		context.setTypeConverter(new StandardTypeConverter(conversionService));
	}
	return context;
}
 
Example 12
Source Project: java-technology-stack   File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR11445_beanReference() {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new Spr11445Class());
	Expression expr = new SpelExpressionParser().parseRaw("@bean.echo(@bean.parameter())");
	assertEquals(1, expr.getValue(context));
}
 
Example 13
Source Project: AppStash   File: NavigationProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isVisible(String visible) {
    if (StringUtils.isNotEmpty(visible)) {
        ExpressionParser parser = new SpelExpressionParser();
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setBeanResolver(new ApplicationContextBeanResolver());
        return parser.parseExpression(visible).getValue(context, Boolean.class);
    }
    return true;
}
 
Example 14
Source Project: eclair   File: ExpressionEvaluatorTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void evaluateWithArgumentAndBeanReferencing() {
    // given
    StandardEvaluationContext evaluationContext = new StandardEvaluationContext();
    evaluationContext.setBeanResolver(new BeanFactoryResolver(applicationContext));
    ExpressionEvaluator expressionEvaluator = new ExpressionEvaluator(expressionParser, evaluationContext);

    String string = "@string.toString()";
    Argument argument = new Argument();
    // when
    Object result = expressionEvaluator.evaluate(string, argument);
    // then
    assertThat(result, is("bean string"));
}
 
Example 15
public static void main(String[] args) {
    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext();
    ctx.refresh();
    ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setBeanResolver(new BeanFactoryResolver(ctx));
    Properties result = parser.parseExpression("@systemProperties").getValue(context, Properties.class);
    Assert.assertEquals(System.getProperties(), result);
}
 
Example 16
/**
 * Creates the lambda for the skip condition which will be evaluated on each request
 * 
 * @param rateLimit the {@link RateLimit} configuration which holds the skip condition string
 * @param expressionParser is used to evaluate the skip expression
 * @param beanFactory used to get full access to all java beans in the SpEl
 * @return the lamdba condition which will be evaluated lazy - null if there is no condition available.
 */
public Condition<R> skipCondition(RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new BeanFactoryResolver(beanFactory));
	
	if(rateLimit.getSkipCondition() != null) {
		return  (request) -> {
			Expression expr = expressionParser.parseExpression(rateLimit.getSkipCondition()); 
			Boolean value = expr.getValue(context, request, Boolean.class);
			return value;
		};
	}
	return null;
}
 
Example 17
/**
 * Creates the lambda for the execute condition which will be evaluated on each request.
 * 
 * @param rateLimit the {@link RateLimit} configuration which holds the execute condition string
 * @param expressionParser is used to evaluate the execution expression
 * @param beanFactory used to get full access to all java beans in the SpEl
 * @return the lamdba condition which will be evaluated lazy - null if there is no condition available.
 */
public Condition<R> executeCondition(RateLimit rateLimit, ExpressionParser expressionParser, BeanFactory beanFactory) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setBeanResolver(new BeanFactoryResolver(beanFactory));
	
	if(rateLimit.getExecuteCondition() != null) {
		return (request) -> {
			Expression expr = expressionParser.parseExpression(rateLimit.getExecuteCondition()); 
			Boolean value = expr.getValue(context, request, Boolean.class);
			return value;
		};
	}
	return null;
}
 
Example 18
Source Project: lams   File: EvalTag.java    License: GNU General Public License v2.0 5 votes vote down vote up
private EvaluationContext createEvaluationContext(PageContext pageContext) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new JspPropertyAccessor(pageContext));
	context.addPropertyAccessor(new MapAccessor());
	context.addPropertyAccessor(new EnvironmentAccessor());
	context.setBeanResolver(new BeanFactoryResolver(getRequestContext().getWebApplicationContext()));
	ConversionService conversionService = getConversionService(pageContext);
	if (conversionService != null) {
		context.setTypeConverter(new StandardTypeConverter(conversionService));
	}
	return context;
}
 
Example 19
public DefaultEntitySanitizer(VerifierMode verifierMode,
                              List<Function<Object, Optional<Object>>> sanitizers,
                              boolean annotationSanitizersEnabled,
                              boolean stdValueSanitizersEnabled,
                              Function<Class<?>, Boolean> includesPredicate,
                              Function<String, Optional<Object>> templateResolver,
                              Map<String, Method> registeredFunctions,
                              Map<String, Object> registeredBeans,
                              Function<Class<?>, Optional<ConstraintValidator<?, ?>>> applicationValidatorFactory) {

    Supplier<EvaluationContext> spelContextFactory = () -> {
        StandardEvaluationContext context = new StandardEvaluationContext();
        registeredFunctions.forEach(context::registerFunction);
        context.setBeanResolver((ctx, beanName) -> registeredBeans.get(beanName));
        context.setMethodResolvers(Collections.singletonList(new ReflectiveMethodResolver()));
        return context;
    };

    this.validator = Validation.buildDefaultValidatorFactory()
            .usingContext()
            .constraintValidatorFactory(new ConstraintValidatorFactoryWrapper(verifierMode, applicationValidatorFactory, spelContextFactory))
            .messageInterpolator(new SpELMessageInterpolator(spelContextFactory))
            .getValidator();

    List<Function<Object, Optional<Object>>> allSanitizers = new ArrayList<>();
    if (annotationSanitizersEnabled) {
        allSanitizers.add(new AnnotationBasedSanitizer(spelContextFactory.get(), includesPredicate));
    }
    if (stdValueSanitizersEnabled) {
        allSanitizers.add(new StdValueSanitizer(includesPredicate));
    }
    allSanitizers.add(new TemplateSanitizer(templateResolver, includesPredicate));
    allSanitizers.addAll(sanitizers);
    this.sanitizers = allSanitizers;
}
 
Example 20
Source Project: spring4-understanding   File: EvalTag.java    License: Apache License 2.0 5 votes vote down vote up
private EvaluationContext createEvaluationContext(PageContext pageContext) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new JspPropertyAccessor(pageContext));
	context.addPropertyAccessor(new MapAccessor());
	context.addPropertyAccessor(new EnvironmentAccessor());
	context.setBeanResolver(new BeanFactoryResolver(getRequestContext().getWebApplicationContext()));
	ConversionService conversionService = getConversionService(pageContext);
	if (conversionService != null) {
		context.setTypeConverter(new StandardTypeConverter(conversionService));
	}
	return context;
}