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() . 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: TestScenarioCreator.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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
Source File: DefaultExpressionEvaluator.java    From rice with Educational Community License v2.0 6 votes vote down vote up
/**
 * 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 3
Source File: ExpressionsSupport.java    From kork with 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 4
Source File: AssertionEvaluation.java    From gravitee-gateway with Apache License 2.0 6 votes vote down vote up
@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 5
Source File: ExpressionEvaluationServiceImpl.java    From konker-platform with Apache License 2.0 6 votes vote down vote up
@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 6
Source File: ExpressionLanguageScenarioTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * 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 7
Source File: TestScenarioCreator.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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
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 9
Source File: ExpressionLanguageScenarioTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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 10
Source File: TestScenarioCreator.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * 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 11
Source File: SpELTest.java    From java-master with 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 12
Source File: ExpressionLanguageScenarioTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * 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 13
Source File: SpelDocumentationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 14
Source File: SpelDocumentationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@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
Source File: SpelCompilationCoverageTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@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 16
Source File: SpringELParser.java    From AutoLoadCache with 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);
}
 
Example 17
Source File: SpelDocumentationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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);
}