Java Code Examples for org.springframework.expression.Expression#getValue()

The following examples show how to use org.springframework.expression.Expression#getValue() . 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: MapAccessTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testGetValuePerformance() throws Exception {
	Assume.group(TestGroup.PERFORMANCE);
	Map<String, String> map = new HashMap<>();
	map.put("key", "value");
	EvaluationContext context = new StandardEvaluationContext(map);

	ExpressionParser spelExpressionParser = new SpelExpressionParser();
	Expression expr = spelExpressionParser.parseExpression("#root['key']");

	StopWatch s = new StopWatch();
	s.start();
	for (int i = 0; i < 10000; i++) {
		expr.getValue(context);
	}
	s.stop();
	assertThat(s.getTotalTimeMillis(), lessThan(200L));
}
 
Example 2
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 3
Source File: OfferingsMatcher.java    From oneops with Apache License 2.0 6 votes vote down vote up
List<CmsCI> getEligbleOfferings(CmsRfcCISimple cmsRfcCISimple, String offeringNS) {
    List<CmsCI> offerings = new ArrayList<>(); 
    List<CmsCI> list = cmsCmProcessor.getCiBy3(offeringNS, "cloud.Offering", null);
    for (CmsCI ci: list){
        CmsCIAttribute criteriaAttribute = ci.getAttribute("criteria");
        String criteria = criteriaAttribute.getDfValue();
        if (isLikelyElasticExpression(criteria)){
            logger.warn("cloud.Offering CI ID:"+ci.getCiId()+" likely still has elastic search criteria. Evaluation may not be successful!");
            logger.info("ES criteria:"+criteria);
            criteria = convert(criteria);
            logger.info("Converted SPEL criteria:"+criteria);
        }
        Expression expression = exprParser.parseExpression(criteria);
        StandardEvaluationContext context = new StandardEvaluationContext();
        context.setRootObject(cmsRfcCISimple);
        boolean match = (boolean) expression.getValue(context, Boolean.class);
        if (match){
            offerings.add(ci);
        }
    }
    return offerings;
}
 
Example 4
Source File: SelectionAndProjectionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void selectionWithSet() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("integers.?[#this<5]");
	EvaluationContext context = new StandardEvaluationContext(new SetTestBean());
	Object value = expression.getValue(context);
	assertTrue(value instanceof List);
	List<?> list = (List<?>) value;
	assertEquals(5, list.size());
	assertEquals(0, list.get(0));
	assertEquals(1, list.get(1));
	assertEquals(2, list.get(2));
	assertEquals(3, list.get(3));
	assertEquals(4, list.get(4));
}
 
Example 5
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void SPR9486_floatLessThanFloat() {
	Boolean expectedNumber = -10.21f < -10.2f;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("-10.21f < -10.2f");
	Boolean result = expression.getValue(context, null, Boolean.class);
	assertEquals(expectedNumber, result);
}
 
Example 6
Source File: SelectionAndProjectionTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void selectLastItemInPrimitiveArray() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("ints.$[#this<5]");
	EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean());
	Object value = expression.getValue(context);
	assertTrue(value instanceof Integer);
	assertEquals(4, value);
}
 
Example 7
Source File: SetValueTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
	 * For use when coercion is happening during a setValue().  The expectedValue should be
	 * the coerced form of the value.
	 */
	protected void setValue(String expression, Object value, Object expectedValue) {
		try {
			Expression e = parser.parseExpression(expression);
			if (e == null) {
				fail("Parser returned null for expression");
			}
			if (DEBUG) {
				SpelUtilities.printAbstractSyntaxTree(System.out, e);
			}
			StandardEvaluationContext lContext = TestScenarioCreator.getTestEvaluationContext();
			assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
			e.setValue(lContext, value);
			Object a = expectedValue;
			Object b = e.getValue(lContext);
			if (!a.equals(b)) {
				fail("Not the same: ["+a+"] type="+a.getClass()+"  ["+b+"] type="+b.getClass());
//				assertEquals("Retrieved value was not equal to set value", expectedValue, e.getValue(lContext));
			}
		} catch (EvaluationException ee) {
			ee.printStackTrace();
			fail("Unexpected Exception: " + ee.getMessage());
		} catch (ParseException pe) {
			pe.printStackTrace();
			fail("Unexpected Exception: " + pe.getMessage());
		}
	}
 
Example 8
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void SPR9486_subtractFloatWithDouble() {
	Number expectedNumber = 10.21f - 10.2;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("10.21f - 10.2");
	Number result = expression.getValue(context, null, Number.class);
	assertEquals(expectedNumber, result);
}
 
Example 9
Source File: ExpressionBasedStringQuery.java    From spring-data-ebean with Apache License 2.0 5 votes vote down vote up
/**
 * @param query,   the query expression potentially containing a SpEL expression. Must not be {@literal null}.}
 * @param metadata the {@link EntityMetadata} for the given entity. Must not be {@literal null}.
 * @param parser   Must not be {@literal null}.
 * @return
 */
private static String renderQueryIfExpressionOrReturnQuery(String query, EntityMetadata<?> metadata,
                                                           SpelExpressionParser parser) {

    Assert.notNull(query, "query must not be null!");
    Assert.notNull(metadata, "metadata must not be null!");
    Assert.notNull(parser, "parser must not be null!");

    if (!containsExpression(query)) {
        return query;
    }

    StandardEvaluationContext evalContext = new StandardEvaluationContext();
    evalContext.setVariable(ENTITY_NAME, metadata.getJavaType().getName());

    query = potentiallyQuoteExpressionsParameter(query);

    Expression expr = parser.parseExpression(query, ParserContext.TEMPLATE_EXPRESSION);

    String result = expr.getValue(evalContext, String.class);

    if (result == null) {
        return query;
    }

    return potentiallyUnquoteParameterExpressions(result);
}
 
Example 10
Source File: SpelReproTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void SPR9486_floatDivideByFloat() {
	Number expectedNumber = -10.21f / -10.2f;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("-10.21f / -10.2f");
	Number result = expression.getValue(context, null, Number.class);
	assertEquals(expectedNumber, result);
}
 
Example 11
Source File: TemplateExpressionParsingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testParsingSimpleTemplateExpression03() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expr = parser.parseExpression("The quick ${'brown'} fox jumped over the ${'lazy'} dog",
			DEFAULT_TEMPLATE_PARSER_CONTEXT);
	Object o = expr.getValue();
	assertEquals("The quick brown fox jumped over the lazy dog", o.toString());
}
 
Example 12
Source File: TemplateExpressionParsingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testParsingSimpleTemplateExpression03() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expr = parser.parseExpression("The quick ${'brown'} fox jumped over the ${'lazy'} dog",
			DEFAULT_TEMPLATE_PARSER_CONTEXT);
	Object o = expr.getValue();
	assertEquals("The quick brown fox jumped over the lazy dog", o.toString());
}
 
Example 13
Source File: SelectionAndProjectionTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void projectionWithArray() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("#testArray.![wrapper.value]");
	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("testArray", IntegerTestBean.createArray());
	Object value = expression.getValue(context);
	assertTrue(value.getClass().isArray());
	TypedValue typedValue = new TypedValue(value);
	assertEquals(Number.class, typedValue.getTypeDescriptor().getElementTypeDescriptor().getType());
	Number[] array = (Number[]) value;
	assertEquals(3, array.length);
	assertEquals(new Integer(5), array[0]);
	assertEquals(5.9f, array[1]);
	assertEquals(new Integer(7), array[2]);
}
 
Example 14
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 15
Source File: PropertiesConversionSpelTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void mapWithAllStringValues() {
	Map<String, Object> map = new HashMap<>();
	map.put("x", "1");
	map.put("y", "2");
	map.put("z", "3");
	Expression expression = parser.parseExpression("foo(#props)");
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setVariable("props", map);
	String result = expression.getValue(context, new TestBean(), String.class);
	assertEquals("123", result);
}
 
Example 16
Source File: SelectionAndProjectionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void selectLastItemInMap() {
	EvaluationContext context = new StandardEvaluationContext(new MapTestBean());
	ExpressionParser parser = new SpelExpressionParser();

	Expression exp = parser.parseExpression("colors.$[key.startsWith('b')]");
	Map<String, String> colorsMap = (Map<String, String>) exp.getValue(context);
	assertEquals(1, colorsMap.size());
	assertEquals("brown", colorsMap.keySet().iterator().next());
}
 
Example 17
Source File: SelectionAndProjectionTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void selectFirstItemInArray() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("integers.^[#this<5]");
	EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean());
	Object value = expression.getValue(context);
	assertTrue(value instanceof Integer);
	assertEquals(0, value);
}
 
Example 18
Source File: SpelCompilationPerformanceTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
@Test
public void compilingPropertyReferenceNestedMixedFieldGetter() throws Exception {
	long interpretedTotal = 0, compiledTotal = 0, stime, etime;
	String interpretedResult = null, compiledResult = null;

	TestClass2 testdata = new TestClass2();
	Expression expression = parser.parseExpression("foo.baz.boo");

	// warmup
	for (int i=0;i<count;i++) {
		expression.getValue(testdata,String.class);
	}
	log("timing interpreted: ");
	for (int iter=0;iter<iterations;iter++) {
		stime = System.currentTimeMillis();
		for (int i=0;i<count;i++) {
			interpretedResult = expression.getValue(testdata,String.class);
		}
		etime = System.currentTimeMillis();
		long interpretedSpeed = (etime - stime);
		interpretedTotal+=interpretedSpeed;
		log(interpretedSpeed+"ms ");
	}
	logln();

	compile(expression);

	log("timing compiled: ");
	expression.getValue(testdata,String.class);
	for (int iter=0;iter<iterations;iter++) {
		stime = System.currentTimeMillis();
		for (int i=0;i<count;i++) {
			compiledResult = expression.getValue(testdata,String.class);
		}
		etime = System.currentTimeMillis();
		long compiledSpeed = (etime - stime);
		compiledTotal+=compiledSpeed;
		log(compiledSpeed+"ms ");
	}
	logln();

	assertEquals(interpretedResult,compiledResult);
	reportPerformance("nested property reference (mixed field/getter)",interpretedTotal, compiledTotal);
}
 
Example 19
Source File: SQLMapper.java    From syncer with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
String evalString(Expression expr, StandardEvaluationContext context) {
  return expr.getValue(context, String.class);
}
 
Example 20
Source File: FunctionArchiveDeployer.java    From spring-cloud-function with Apache License 2.0 4 votes vote down vote up
private void setBeanFactory(Object applicationContext) {
	Expression parsed = new SpelExpressionParser().parseExpression("#context.getBeanFactory()");
	Object beanFactory = parsed.getValue(this.evalContext);
	evalContext.setVariable("bf", beanFactory);
}