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

The following examples show how to use org.springframework.expression.spel.support.StandardEvaluationContext#setVariables() . 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
@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
@Test
@SuppressWarnings("serial")
public void spelExpressionListWithVariables() {
	ExpressionParser parser = new SpelExpressionParser();
	Expression spelExpression = parser.parseExpression("#aList.contains('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 3
@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 4
@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 5
@Test
@SuppressWarnings("serial")
public void spelExpressionListWithVariables() {
	ExpressionParser parser = new SpelExpressionParser();
	Expression spelExpression = parser.parseExpression("#aList.contains('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 6
@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 7
@Override
public String evaluateTemplate(String expressionTemplate, Map<String, Object> evaluationContext) {
    Optional.ofNullable(expressionTemplate)
        .filter(template -> !template.isEmpty())
        .orElseThrow(() -> new IllegalArgumentException("Expression template cannot be null or empty"));

    Optional.ofNullable(evaluationContext)
        .orElseThrow(() -> new IllegalArgumentException("Evaluation context cannot be null"));

    Expression expression = new SpelExpressionParser().parseExpression(expressionTemplate
            ,new TemplateParserContext("@{","}"));

    StandardEvaluationContext standardEvaluationContext = new StandardEvaluationContext();
    try {
        standardEvaluationContext.registerFunction("urlEncode",
                Functions.class.getDeclaredMethod("urlEncode", new Class[] {String.class}));
    } catch (NoSuchMethodException e) {
        throw new EvaluationException("Fail to register function to evaluation context", e);
    }
    standardEvaluationContext.addPropertyAccessor(new MapAccessor());
    standardEvaluationContext.setVariables(evaluationContext);

    return expression.getValue(standardEvaluationContext,String.class);
}
 
Example 8
@Override
public boolean evaluateConditional(String conditionalExpression, Map<String, Object> evaluationContext) {
    Optional.ofNullable(conditionalExpression)
            .filter(template -> !template.isEmpty())
            .orElseThrow(() -> new IllegalArgumentException("Conditional expression cannot be null or empty"));

    Optional.ofNullable(evaluationContext)
            .orElseThrow(() -> new IllegalArgumentException("Evaluation context cannot be null"));

    Expression expression = new SpelExpressionParser().parseExpression(conditionalExpression);

    StandardEvaluationContext standardEvaluationContext = new StandardEvaluationContext();
    standardEvaluationContext.addPropertyAccessor(new MapAccessor());
    standardEvaluationContext.setVariables(evaluationContext);

    return expression.getValue(standardEvaluationContext,Boolean.class);
}
 
Example 9
@Override
public boolean validate() throws EvaluationException {
    try {
        final ExpressionParser parser = new SpelExpressionParser();
        final Expression expr = parser.parseExpression(assertion);

        final StandardEvaluationContext context = new StandardEvaluationContext();
        context.registerFunction("jsonPath",
                BeanUtils.resolveSignature("evaluate", JsonPathFunction.class));
        context.setVariables(variables);

        return expr.getValue(context, boolean.class);
    } catch (SpelEvaluationException spelex) {
        throw new EvaluationException("Assertion can not be verified : " + assertion, spelex);
    }
}
 
Example 10
Source Project: onetwo   File: SpelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
	public void test(){
		StandardEvaluationContext elcontext = new StandardEvaluationContext();
		TestBean tb = new TestBean();
		tb.aaa = "cccc";
		Map map = LangUtils.asMap("ccc", "dddd");
//		map.put("tb", tb);
		map.put("map", LangUtils.asMap("ccc", "dddd", "tb", tb));
		elcontext.setVariables(map);
		elcontext.setRootObject(tb);
		Expression exp = parser.parseExpression("'bb{ccc}'");
		Object val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("bb{ccc}", val);
		
		exp = parser.parseExpression("#ccc");
		val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("dddd", val);
		
		exp = parser.parseExpression("#map['tb'].aaa");
		val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("cccc", val);
	}
 
Example 11
Source Project: onetwo   File: SpelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
	public void test(){
		StandardEvaluationContext elcontext = new StandardEvaluationContext();
		TestBean tb = new TestBean();
		tb.aaa = "cccc";
		Map map = LangUtils.asMap("ccc", "dddd");
//		map.put("tb", tb);
		map.put("map", LangUtils.asMap("ccc", "dddd", "tb", tb));
		elcontext.setVariables(map);
		elcontext.setRootObject(tb);
		Expression exp = parser.parseExpression("'bb{ccc}'");
		Object val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("bb{ccc}", val);
		
		exp = parser.parseExpression("#ccc");
		val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("dddd", val);
		
		exp = parser.parseExpression("#map['tb'].aaa");
		val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("cccc", val);
	}
 
Example 12
Source Project: onetwo   File: SpelTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
	public void test2(){
		StandardEvaluationContext elcontext = new StandardEvaluationContext();
		TestBean tb = new TestBean();
		tb.aaa = "cccc";
		Map map = LangUtils.asMap("ccc", "dddd", "userName", "testUser");
//		map.put("tb", tb);
		map.put("map", LangUtils.asMap("ccc", "dddd", "tb", tb));
		elcontext.setRootObject(map);
		Expression exp = parser.parseExpression("['ccc']");
		Object val = (String)exp.getValue(elcontext, String.class);
		System.out.println("val: " + val);
		Assert.assertEquals("dddd", val);

		elcontext.setVariables(map);
		elcontext.setRootObject(null);
		exp = parser.parseExpression("I am ${#userName}", PARSER_CONTEXT);
		val = (String)exp.getValue(elcontext, String.class);
		System.out.println("val: " + val);
		Assert.assertEquals("I am testUser", val);
	}
 
Example 13
@Test
@SuppressWarnings("serial")
public void spelExpressionArrayWithVariables() {
	ExpressionParser parser = new SpelExpressionParser();
	Expression spelExpression = parser.parseExpression("#anArray[0] eq 1");
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariables(new HashMap<String, Object>() {
		{
			put("anArray", new int[] {1,2,3});
		}
	});
	boolean result = spelExpression.getValue(ctx, Boolean.class);
	assertTrue(result);
}
 
Example 14
@Test
@SuppressWarnings("serial")
public void spelExpressionArrayWithVariables() {
	ExpressionParser parser = new SpelExpressionParser();
	Expression spelExpression = parser.parseExpression("#anArray[0] eq 1");
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariables(new HashMap<String, Object>() {
		{
			put("anArray", new int[] {1,2,3});
		}
	});
	boolean result = spelExpression.getValue(ctx, Boolean.class);
	assertTrue(result);
}
 
Example 15
Source Project: herd   File: SpelExpressionHelper.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Evaluates the given expression using the given variables as context variables.
 * 
 * @param <T> The desired type
 * @param expression The expression to evaluate
 * @param desiredResultType The desired type of the result. Spring will make best attempt at converting result to this type.
 * @param variables The variables to put into context
 * @return The result of the evaluation
 */
public <T> T evaluate(Expression expression, Class<T> desiredResultType, Map<String, Object> variables)
{
    StandardEvaluationContext context = new StandardEvaluationContext();

    if (variables != null)
    {
        context.setVariables(variables);
    }

    return expression.getValue(context, desiredResultType);
}
 
Example 16
public static SequenceFormatter createFormatter(final String formatExpression) {
    return new SequenceFormatter() {
        @Override
        public String format(Map<String, Object> variables) {
            StandardEvaluationContext simpleContext = new StandardEvaluationContext();
            simpleContext.setVariables(variables);
            return expressionCache.getUnchecked(formatExpression).getValue(simpleContext, String.class);
        }
    };
}
 
Example 17
Source Project: nifi   File: ExpressionHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void executeSPEL(String command, Map<String, Object> facts) {
    final ExpressionParser parser = new SpelExpressionParser();
    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setRootObject(facts);
    context.setVariables(facts);
    Expression expression = parser.parseExpression(command);
    Object value = expression.getValue(context);
    if(getLogger().isDebugEnabled()) {
        getLogger().debug("Expression was executed successfully with result: {}. {}: {}", new Object[]{value, type, command});
    }
}
 
Example 18
Source Project: nifi   File: RulesSPELCondition.java    License: Apache License 2.0 5 votes vote down vote up
public boolean evaluate(Facts facts) {
    try {
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setRootObject(facts.asMap());
        context.setVariables(facts.asMap());
        return this.compiledExpression.getValue(context, Boolean.class);
    } catch (Exception ex) {
        if(ignoreConditionErrors) {
            LOGGER.debug("Unable to evaluate expression: '" + this.expression + "' on facts: " + facts, ex);
            return false;
        } else{
            throw ex;
        }
    }
}
 
Example 19
@Override
public String locate(Map<String, Object> locateParam) {

    ExpressionParser parser = new SpelExpressionParser();

    Expression expression = parser.parseExpression(this.rule);

    StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariables(locateParam);

    return expression.getValue(context, String.class);

}