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() . 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: ShortcutConfigurable.java    From spring-cloud-gateway with Apache License 2.0 6 votes vote down vote up
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
Source File: TestValidator.java    From titus-control-plane with Apache License 2.0 6 votes vote down vote up
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 3
Source File: Bucket4JBaseConfiguration.java    From bucket4j-spring-boot-starter with Apache License 2.0 6 votes vote down vote up
/**
 * 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 4
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 5
Source File: DatastoreRepositoryFactory.java    From spring-cloud-gcp with Apache License 2.0 6 votes vote down vote up
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 6
Source File: ConfigurationUtils.java    From spring-cloud-gray with Apache License 2.0 6 votes vote down vote up
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 7
Source File: SpelReproTests.java    From java-technology-stack with 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 8
Source File: EvalTag.java    From java-technology-stack with 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 9
Source File: NavigationProviderImpl.java    From AppStash with 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 10
Source File: SecureCheckUtil.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 设置 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 File: SecureCheckUtil.java    From magic-starter with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 包含方法上的参数的上下文
 *
 * @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 12
Source File: ExpressionEvaluatorTest.java    From eclair with 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 13
Source File: ELExample.java    From pragmatic-java-engineer with GNU General Public License v3.0 5 votes vote down vote up
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 14
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 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 15
Source File: Bucket4JBaseConfiguration.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 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 16
Source File: Bucket4JBaseConfiguration.java    From bucket4j-spring-boot-starter with Apache License 2.0 5 votes vote down vote up
/**
 * 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 17
Source File: EvalTag.java    From lams with 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 18
Source File: DefaultEntitySanitizer.java    From titus-control-plane with Apache License 2.0 5 votes vote down vote up
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 19
Source File: EvalTag.java    From spring-analysis-note with 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 20
Source File: EvalTag.java    From spring4-understanding with 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;
}