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

The following examples show how to use org.springframework.expression.spel.support.StandardEvaluationContext#registerFunction() . 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
/**
 * Register some Java reflect methods as well known functions that can be called from an expression.
 * @param testContext the test evaluation context
 */
private static void populateFunctions(StandardEvaluationContext testContext) {
	try {
		testContext.registerFunction("isEven",
				TestScenarioCreator.class.getDeclaredMethod("isEven", Integer.TYPE));
		testContext.registerFunction("reverseInt",
				TestScenarioCreator.class.getDeclaredMethod("reverseInt", Integer.TYPE, Integer.TYPE, Integer.TYPE));
		testContext.registerFunction("reverseString",
				TestScenarioCreator.class.getDeclaredMethod("reverseString", String.class));
		testContext.registerFunction("varargsFunctionReverseStringsAndMerge",
				TestScenarioCreator.class.getDeclaredMethod("varargsFunctionReverseStringsAndMerge", String[].class));
		testContext.registerFunction("varargsFunctionReverseStringsAndMerge2",
				TestScenarioCreator.class.getDeclaredMethod("varargsFunctionReverseStringsAndMerge2", Integer.TYPE, String[].class));
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 2
/**
 * Scenario: using your own java methods and calling them from the expression
 */
@Test
public void testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem() throws SecurityException, NoSuchMethodException {
	try {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Use the standard evaluation context
		StandardEvaluationContext ctx = new StandardEvaluationContext();
		ctx.registerFunction("repeat",ExpressionLanguageScenarioTests.class.getDeclaredMethod("repeat",String.class));

		Expression expr = parser.parseRaw("#repeat('hello')");
		Object value = expr.getValue(ctx);
		assertEquals("hellohello", value);

	}
	catch (EvaluationException | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
Example 3
Source Project: java-master   File: SpELTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("ALL")
public void test4() throws Exception {
    List<Integer> primes = new ArrayList<>(Arrays.asList(2, 3, 5, 7, 11, 13, 17));

    StandardEvaluationContext context = new StandardEvaluationContext();
    // 注册一个对象变量,以便能在spEL中引用
    context.setVariable("primes", primes);

    // 过滤List并做投影运算
    List<Integer> primesGreaterThanTen = (List<Integer>) parser.parseExpression("#primes.?[#this>10]").getValue(context);
    logger.info(primesGreaterThanTen.toString());

    // 注册一个方法,以便能在spEL中调用
    context.registerFunction("reverseString", SpELTest.class.getDeclaredMethod("reverseString", String.class));
    logger.info(parser.parseExpression("#reverseString('hello')").getValue(context, String.class));
}
 
Example 4
/**
 * Register some Java reflect methods as well known functions that can be called from an expression.
 * @param testContext the test evaluation context
 */
private static void populateFunctions(StandardEvaluationContext testContext) {
	try {
		testContext.registerFunction("isEven",
				TestScenarioCreator.class.getDeclaredMethod("isEven", Integer.TYPE));
		testContext.registerFunction("reverseInt",
				TestScenarioCreator.class.getDeclaredMethod("reverseInt", Integer.TYPE, Integer.TYPE, Integer.TYPE));
		testContext.registerFunction("reverseString",
				TestScenarioCreator.class.getDeclaredMethod("reverseString", String.class));
		testContext.registerFunction("varargsFunctionReverseStringsAndMerge",
				TestScenarioCreator.class.getDeclaredMethod("varargsFunctionReverseStringsAndMerge", String[].class));
		testContext.registerFunction("varargsFunctionReverseStringsAndMerge2",
				TestScenarioCreator.class.getDeclaredMethod("varargsFunctionReverseStringsAndMerge2", Integer.TYPE, String[].class));
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 5
/**
 * Scenario: using your own java methods and calling them from the expression
 */
@Test
public void testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem() throws SecurityException, NoSuchMethodException {
	try {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Use the standard evaluation context
		StandardEvaluationContext ctx = new StandardEvaluationContext();
		ctx.registerFunction("repeat",ExpressionLanguageScenarioTests.class.getDeclaredMethod("repeat",String.class));

		Expression expr = parser.parseRaw("#repeat('hello')");
		Object value = expr.getValue(ctx);
		assertEquals("hellohello", value);

	}
	catch (EvaluationException | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
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
/**
 * Register some Java reflect methods as well known functions that can be called from an expression.
 * @param testContext the test evaluation context
 */
private static void populateFunctions(StandardEvaluationContext testContext) {
	try {
		testContext.registerFunction("isEven",
				TestScenarioCreator.class.getDeclaredMethod("isEven", Integer.TYPE));
		testContext.registerFunction("reverseInt",
				TestScenarioCreator.class.getDeclaredMethod("reverseInt", Integer.TYPE, Integer.TYPE, Integer.TYPE));
		testContext.registerFunction("reverseString",
				TestScenarioCreator.class.getDeclaredMethod("reverseString", String.class));
		testContext.registerFunction("varargsFunctionReverseStringsAndMerge",
				TestScenarioCreator.class.getDeclaredMethod("varargsFunctionReverseStringsAndMerge", String[].class));
		testContext.registerFunction("varargsFunctionReverseStringsAndMerge2",
				TestScenarioCreator.class.getDeclaredMethod("varargsFunctionReverseStringsAndMerge2", Integer.TYPE, String[].class));
	}
	catch (Exception ex) {
		throw new IllegalStateException(ex);
	}
}
 
Example 8
/**
 * Scenario: using your own java methods and calling them from the expression
 */
@Test
public void testScenario_RegisteringJavaMethodsAsFunctionsAndCallingThem() throws SecurityException, NoSuchMethodException {
	try {
		// Create a parser
		SpelExpressionParser parser = new SpelExpressionParser();
		// Use the standard evaluation context
		StandardEvaluationContext ctx = new StandardEvaluationContext();
		ctx.registerFunction("repeat",ExpressionLanguageScenarioTests.class.getDeclaredMethod("repeat",String.class));

		Expression expr = parser.parseRaw("#repeat('hello')");
		Object value = expr.getValue(ctx);
		assertEquals("hellohello", value);

	} catch (EvaluationException ee) {
		ee.printStackTrace();
		fail("Unexpected Exception: " + ee.getMessage());
	} catch (ParseException pe) {
		pe.printStackTrace();
		fail("Unexpected Exception: " + pe.getMessage());
	}
}
 
Example 9
@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 10
@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 11
Source Project: kork   File: ExpressionsSupport.java    License: Apache License 2.0 6 votes vote down vote up
private static void registerFunction(
    StandardEvaluationContext context,
    String registrationName,
    Class<?> cls,
    String methodName,
    Class<?>... types) {
  try {
    context.registerFunction(registrationName, cls.getDeclaredMethod(methodName, types));
  } catch (NoSuchMethodException e) {
    LOGGER.error("Failed to register helper function", e);
    throw new RuntimeException(
        "Failed to register helper function '"
            + registrationName
            + "' from '"
            + cls.getName()
            + "#"
            + methodName
            + "'",
        e);
  }
}
 
Example 12
/**
 * Registers custom functions for el expressions with the given context
 *
 * @param context - context instance to register functions to
 */
protected void addCustomFunctions(StandardEvaluationContext context) {
    context.registerFunction("isAssignableFrom", isAssignableFrom);
    context.registerFunction("empty", empty);
    context.registerFunction("emptyList", emptyList);
    context.registerFunction("getService", getService);
    context.registerFunction("listContains", listContains);
    context.registerFunction("getName", getName);
    context.registerFunction("getParam", getParam);
    context.registerFunction("getParamAsBoolean", getParamAsBoolean);
    context.registerFunction("getParamAsInteger", getParamAsInteger);
    context.registerFunction("getParamAsDouble", getParamAsDouble);
    context.registerFunction("hasPerm", hasPerm);
    context.registerFunction("hasPermDtls", hasPermDtls);
    context.registerFunction("hasPermTmpl", hasPermTmpl);
    context.registerFunction("sequence", sequence);
    context.registerFunction("getDataObjectKey", getDataObjectKey);
    context.registerFunction("isProductionEnvironment", isProductionEnvironment);
}
 
Example 13
@Test
public void testFunctions() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.registerFunction("reverseString", StringUtils.class.getDeclaredMethod("reverseString", String.class));

	String helloWorldReversed = parser.parseExpression("#reverseString('hello world')").getValue(context, String.class);
	assertEquals("dlrow olleh",helloWorldReversed);
}
 
Example 14
@Test
public void testFunctions() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.registerFunction("reverseString", StringUtils.class.getDeclaredMethod("reverseString", String.class));

	String helloWorldReversed = parser.parseExpression("#reverseString('hello world')").getValue(context, String.class);
	assertEquals("dlrow olleh",helloWorldReversed);
}
 
Example 15
@Test
public void testFunctions() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();

	context.registerFunction("reverseString", StringUtils.class.getDeclaredMethod(
			"reverseString", new Class[] { String.class }));

	String helloWorldReversed = parser.parseExpression("#reverseString('hello world')").getValue(context, String.class);
	assertEquals("dlrow olleh",helloWorldReversed);
}
 
Example 16
@Test
public void functionReferenceNonCompilableArguments_SPR12359() throws Exception {
	StandardEvaluationContext context = new StandardEvaluationContext(new  Object[] { "1" });
	context.registerFunction("negate", SomeCompareMethod2.class.getDeclaredMethod(
			"negate", Integer.TYPE));
	context.setVariable("arg", "2");
	int[] ints = new int[]{1,2,3};
	context.setVariable("ints",ints);

	expression = parser.parseExpression("#negate(#ints.?[#this<2][0])");
	assertEquals("-1",expression.getValue(context, Integer.class).toString());
	// Selection isn't compilable.
	assertFalse(((SpelNodeImpl)((SpelExpression)expression).getAST()).isCompilable());
}
 
Example 17
Source Project: AutoLoadCache   File: SpringELParser.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <T> T getElValue(String keySpEL, Object target, Object[] arguments, Object retVal, boolean hasRetVal,
                        Class<T> valueType) throws Exception {
    if (valueType.equals(String.class)) {
        // 如果不是表达式,直接返回字符串
        if (keySpEL.indexOf(POUND) == -1 && keySpEL.indexOf("'") == -1) {
            return (T) keySpEL;
        }
    }
    StandardEvaluationContext context = new StandardEvaluationContext();

    context.registerFunction(HASH, hash);
    context.registerFunction(EMPTY, empty);
    Iterator<Map.Entry<String, Method>> it = funcs.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<String, Method> entry = it.next();
        context.registerFunction(entry.getKey(), entry.getValue());
    }
    context.setVariable(TARGET, target);
    context.setVariable(ARGS, arguments);
    if (hasRetVal) {
        context.setVariable(RET_VAL, retVal);
    }
    Expression expression = expCache.get(keySpEL);
    if (null == expression) {
        expression = parser.parseExpression(keySpEL);
        expCache.put(keySpEL, expression);
    }
    return expression.getValue(context, valueType);
}