org.springframework.expression.Expression Java Examples

The following examples show how to use org.springframework.expression.Expression. 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: 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 #2
Source File: ProxyMethodHandlerTest.java    From docx-stamper with MIT License 6 votes vote down vote up
@Test
public void proxyDelegatesToRegisteredCommentProcessors() throws Exception {

	CommentProcessorRegistry processorRegistry = new CommentProcessorRegistry(placeholderReplacer);
	processorRegistry.registerCommentProcessor(ITestInterface.class, new TestImpl());

	NameContext contextRoot = new NameContext();
	contextRoot.setName("Tom");
	NameContext context = new ProxyBuilder<NameContext>()
			.withRoot(contextRoot)
			.withInterface(ITestInterface.class, new TestImpl())
			.build();

	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext evaluationContext = new StandardEvaluationContext(context);

	Expression nameExpression = parser.parseExpression("name");
	String name = (String) nameExpression.getValue(evaluationContext);

	Expression methodExpression = parser.parseExpression("returnString(name)");
	String returnStringResult = (String) methodExpression.getValue(evaluationContext);

	Assert.assertEquals("Tom", returnStringResult);
	Assert.assertEquals("Tom", name);
}
 
Example #3
Source File: ExpressionLanguageScenarioTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Scenario: add a property resolver that will get called in the resolver chain, this one only supports reading.
 */
@Test
public void testScenario_AddingYourOwnPropertyResolvers_1() throws Exception {
	// Create a parser
	SpelExpressionParser parser = new SpelExpressionParser();
	// Use the standard evaluation context
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	ctx.addPropertyAccessor(new FruitColourAccessor());
	Expression expr = parser.parseRaw("orange");
	Object value = expr.getValue(ctx);
	assertEquals(Color.orange, value);

	try {
		expr.setValue(ctx, Color.blue);
		fail("Should not be allowed to set oranges to be blue !");
	}
	catch (SpelEvaluationException ee) {
		assertEquals(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, ee.getMessageCode());
	}
}
 
Example #4
Source File: SpelExpressionConverterConfigurationTests.java    From spring-cloud-stream with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void converterCorrectlyInstalled() {
	Expression expression = this.pojo.getExpression();
	assertThat(expression.getValue("{\"a\": {\"b\": 5}}").toString()).isEqualTo("5");

	List<PropertyAccessor> propertyAccessors = TestUtils.getPropertyValue(
			this.evaluationContext, "propertyAccessors", List.class);

	assertThat(propertyAccessors)
			.hasAtLeastOneElementOfType(JsonPropertyAccessor.class);

	propertyAccessors = TestUtils.getPropertyValue(this.config.evaluationContext,
			"propertyAccessors", List.class);

	assertThat(propertyAccessors)
			.hasAtLeastOneElementOfType(JsonPropertyAccessor.class);
}
 
Example #5
Source File: PropertyAccessTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void propertyReadOnly() {
	EvaluationContext context = SimpleEvaluationContext.forReadOnlyDataBinding().build();

	Expression expr = parser.parseExpression("name");
	Person target = new Person("p1");
	assertEquals("p1", expr.getValue(context, target));
	target.setName("p2");
	assertEquals("p2", expr.getValue(context, target));

	try {
		parser.parseExpression("name='p3'").getValue(context, target);
		fail("Should have thrown SpelEvaluationException");
	}
	catch (SpelEvaluationException ex) {
		// expected
	}
}
 
Example #6
Source File: AbstractExpressionTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
public void evaluateAndAskForReturnType(String expression, Object expectedValue, Class<?> expectedResultType) {
	Expression expr = parser.parseExpression(expression);
	if (expr == null) {
		fail("Parser returned null for expression");
	}
	if (DEBUG) {
		SpelUtilities.printAbstractSyntaxTree(System.out, expr);
	}

	Object value = expr.getValue(context, expectedResultType);
	if (value == null) {
		if (expectedValue == null) {
			return;  // no point doing other checks
		}
		assertNull("Expression returned null value, but expected '" + expectedValue + "'", expectedValue);
	}

	Class<?> resultType = value.getClass();
	assertEquals("Type of the actual result was not as expected.  Expected '" + expectedResultType +
			"' but result was of type '" + resultType + "'", expectedResultType, resultType);
	assertEquals("Did not get expected value for expression '" + expression + "'.", expectedValue, value);
}
 
Example #7
Source File: MapAccessTests.java    From java-technology-stack 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 #8
Source File: DataSetMapper.java    From n2o-framework with Apache License 2.0 6 votes vote down vote up
public static Map<String, Object> mapToMap(DataSet dataSet, Map<String, String> mapping,
                                           Map<String, String> argumentClasses) {
    validateMapping(mapping);
    Map<String, Object> instances = instantiateArguments(argumentClasses);
    Map<String, Object> result;
    if (instances == null || instances.isEmpty()) {
        result = new DataSet();
    } else {
        result = instances;
    }

    for (Map.Entry<String, String> map : mapping.entrySet()) {
        Expression expression = writeParser.parseExpression(map.getValue() != null ? map.getValue()
                : "['" + map.getKey() + "']");
        expression.setValue(result, dataSet.get(map.getKey()));
    }
    return result;
}
 
Example #9
Source File: SelectionAndProjectionTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void selectionWithPrimitiveArray() throws Exception {
	Expression expression = new SpelExpressionParser().parseRaw("ints.?[#this<5]");
	EvaluationContext context = new StandardEvaluationContext(new ArrayTestBean());
	Object value = expression.getValue(context);
	assertTrue(value.getClass().isArray());
	TypedValue typedValue = new TypedValue(value);
	assertEquals(Integer.class, typedValue.getTypeDescriptor().getElementTypeDescriptor().getType());
	Integer[] array = (Integer[]) value;
	assertEquals(5, array.length);
	assertEquals(new Integer(0), array[0]);
	assertEquals(new Integer(1), array[1]);
	assertEquals(new Integer(2), array[2]);
	assertEquals(new Integer(3), array[3]);
	assertEquals(new Integer(4), array[4]);
}
 
Example #10
Source File: ExpressionLanguageScenarioTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Scenario: using the standard context but adding your own variables
 */
@Test
public void testScenario_DefiningVariablesThatWillBeAccessibleInExpressions() throws Exception {
	// Create a parser
	SpelExpressionParser parser = new SpelExpressionParser();
	// Use the standard evaluation context
	StandardEvaluationContext ctx = new StandardEvaluationContext();
	ctx.setVariable("favouriteColour","blue");
	List<Integer> primes = new ArrayList<>();
	primes.addAll(Arrays.asList(2,3,5,7,11,13,17));
	ctx.setVariable("primes",primes);

	Expression expr = parser.parseRaw("#favouriteColour");
	Object value = expr.getValue(ctx);
	assertEquals("blue", value);

	expr = parser.parseRaw("#primes.get(1)");
	value = expr.getValue(ctx);
	assertEquals(3, value);

	// all prime numbers > 10 from the list (using selection ?{...})
	expr = parser.parseRaw("#primes.?[#this>10]");
	value = expr.getValue(ctx);
	assertEquals("[11, 13, 17]", value.toString());
}
 
Example #11
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 #12
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void SPR9735() {
	Item item = new Item();
	item.setName("parent");

	Item item1 = new Item();
	item1.setName("child1");

	Item item2 = new Item();
	item2.setName("child2");

	item.add(item1);
	item.add(item2);

	ExpressionParser parser = new SpelExpressionParser();
	EvaluationContext context = new StandardEvaluationContext();
	Expression exp = parser.parseExpression("#item[0].name");
	context.setVariable("item", item);

	assertEquals("child1", exp.getValue(context));
}
 
Example #13
Source File: ExpressionLanguageScenarioTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * Scenario: add a property resolver that will get called in the resolver chain, this one only supports reading.
 */
@Test
public void testScenario_AddingYourOwnPropertyResolvers_1() throws Exception {
	// Create a parser
	SpelExpressionParser parser = new SpelExpressionParser();
	// Use the standard evaluation context
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	ctx.addPropertyAccessor(new FruitColourAccessor());
	Expression expr = parser.parseRaw("orange");
	Object value = expr.getValue(ctx);
	assertEquals(Color.orange, value);

	try {
		expr.setValue(ctx, Color.blue);
		fail("Should not be allowed to set oranges to be blue !");
	}
	catch (SpelEvaluationException ee) {
		assertEquals(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, ee.getMessageCode());
	}
}
 
Example #14
Source File: MethodInvocationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
/**
 * Check on first usage (when the cachedExecutor in MethodReference is null) that the exception is not wrapped.
 */
@Test
public void testMethodThrowingException_SPR6941() {
	// Test method on inventor: throwException()
	// On 1 it will throw an IllegalArgumentException
	// On 2 it will throw a RuntimeException
	// On 3 it will exit normally
	// In each case it increments the Inventor field 'counter' when invoked

	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expr = parser.parseExpression("throwException(#bar)");

	context.setVariable("bar", 2);
	try {
		expr.getValue(context);
		fail();
	}
	catch (Exception ex) {
		if (ex instanceof SpelEvaluationException) {
			fail("Should not be a SpelEvaluationException: " + ex);
		}
		// normal
	}
}
 
Example #15
Source File: IndexingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
public void indexIntoGenericPropertyContainingGrowingList2() {
	List<String> property2 = new ArrayList<String>();
	this.property2 = property2;
	SpelParserConfiguration configuration = new SpelParserConfiguration(true, true);
	SpelExpressionParser parser = new SpelExpressionParser(configuration);
	Expression expression = parser.parseExpression("property2");
	assertEquals("java.util.ArrayList<?>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property2, expression.getValue(this));
	expression = parser.parseExpression("property2[0]");
	try {
		assertEquals("bar", expression.getValue(this));
	} catch (EvaluationException e) {
		assertTrue(e.getMessage().startsWith("EL1053E"));
	}
}
 
Example #16
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 #17
Source File: SetValueTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
/**
 * Call setValue() but expect it to fail.
 */
protected void setValueExpectError(String expression, Object value) {
	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();
		e.setValue(lContext, value);
		fail("expected an error");
	} catch (ParseException pe) {
		pe.printStackTrace();
		fail("Unexpected Exception: " + pe.getMessage());
	} catch (EvaluationException ee) {
		// success!
	}
}
 
Example #18
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings({ "unchecked", "rawtypes" })
public void SPR10417_maps() {
	Map map1 = new HashMap();
	map1.put("A", 65);
	map1.put("B", 66);
	map1.put("X", 66);
	Map map2 = new HashMap();
	map2.put("X", 66);

	EvaluationContext context = new StandardEvaluationContext();
	context.setVariable("map1", map1);
	context.setVariable("map2", map2);

	// #this should be the element from list1
	Expression ex = parser.parseExpression("#map1.?[#map2.containsKey(#this.getKey())]");
	Object result = ex.getValue(context);
	assertEquals("{X=66}", result.toString());

	ex = parser.parseExpression("#map1.?[#map2.containsKey(key)]");
	result = ex.getValue(context);
	assertEquals("{X=66}", result.toString());
}
 
Example #19
Source File: SpelDocumentationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testRootObject() throws Exception {
	GregorianCalendar c = new GregorianCalendar();
	c.set(1856, 7, 9);

	//  The constructor arguments are name, birthday, and nationaltiy.
	Inventor tesla = new Inventor("Nikola Tesla", c.getTime(), "Serbian");

	ExpressionParser parser = new SpelExpressionParser();
	Expression exp = parser.parseExpression("name");

	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setRootObject(tesla);

	String name = (String) exp.getValue(context);
	assertEquals("Nikola Tesla",name);
}
 
Example #20
Source File: SpelReproTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void SPR9486_subtractFloatWithFloat() {
	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 #21
Source File: CachedExpressionEvaluator.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Return the {@link Expression} for the specified SpEL value
 * <p>Parse the expression if it hasn't been already.
 * @param cache the cache to use
 * @param elementKey the element on which the expression is defined
 * @param expression the expression to parse
 */
protected Expression getExpression(Map<ExpressionKey, Expression> cache,
		AnnotatedElementKey elementKey, String expression) {

	ExpressionKey expressionKey = createKey(elementKey, expression);
	Expression expr = cache.get(expressionKey);
	if (expr == null) {
		expr = getParser().parseExpression(expression);
		cache.put(expressionKey, expr);
	}
	return expr;
}
 
Example #22
Source File: IndexingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void indexIntoGenericPropertyContainingNullList() {
	SpelParserConfiguration configuration = new SpelParserConfiguration(true, true);
	SpelExpressionParser parser = new SpelExpressionParser(configuration);
	Expression expression = parser.parseExpression("property");
	assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.lang.Object", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property, expression.getValue(this));
	expression = parser.parseExpression("property[0]");
	try {
		assertEquals("bar", expression.getValue(this));
	}
	catch (EvaluationException ex) {
		assertTrue(ex.getMessage().startsWith("EL1027E"));
	}
}
 
Example #23
Source File: CompositeStringExpression.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
@Override
public String getValue(Object rootObject) throws EvaluationException {
	StringBuilder sb = new StringBuilder();
	for (Expression expression : this.expressions) {
		String value = expression.getValue(rootObject, String.class);
		if (value != null) {
			sb.append(value);
		}
	}
	return sb.toString();
}
 
Example #24
Source File: DecryptPassword.java    From jwala with Apache License 2.0 5 votes vote down vote up
public String decrypt(String encryptedValue) {
    if (encryptedValue==null) {
        return null;
    }
    
    final ExpressionParser expressionParser = new SpelExpressionParser();
    final Expression decryptExpression = expressionParser.parseExpression(decryptorImpl);

    final StandardEvaluationContext context = new StandardEvaluationContext();
    context.setVariable("stringToDecrypt", encryptedValue);
    return decryptExpression.getValue(context, String.class);
}
 
Example #25
Source File: IndexingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testListsOfMap() {
	listOfMapsNotGeneric = new ArrayList();
	Map map = new HashMap();
	map.put("fruit", "apple");
	listOfMapsNotGeneric.add(map);
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression("listOfMapsNotGeneric[0]['fruit']");
	assertEquals("apple", expression.getValue(this, String.class));
}
 
Example #26
Source File: EvaluationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void increment01root() {
	Integer i = 42;
	StandardEvaluationContext ctx = new StandardEvaluationContext(i);
	ExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
	Expression e =  parser.parseExpression("#this++");
	assertEquals(42,i.intValue());
	try {
		e.getValue(ctx, Integer.class);
		fail();
	}
	catch (SpelEvaluationException see) {
		assertEquals(SpelMessage.NOT_ASSIGNABLE, see.getMessageCode());
	}
}
 
Example #27
Source File: CachedMethodExecutorTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testCachedExecutionForTarget() {
	Expression expression = this.parser.parseExpression("#var.echo(42)");

	assertMethodExecution(expression, new RootObject(), "int: 42");
	assertMethodExecution(expression, new RootObject(), "int: 42");
	assertMethodExecution(expression, new BaseObject(), "String: 42");
	assertMethodExecution(expression, new RootObject(), "int: 42");
}
 
Example #28
Source File: SpelReproTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void SPR11142() {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Spr11142 rootObject = new Spr11142();
	Expression expression = parser.parseExpression("something");
	thrown.expect(SpelEvaluationException.class);
	thrown.expectMessage("'something' cannot be found");
	expression.getValue(context, rootObject);
}
 
Example #29
Source File: PropertiesConversionSpelTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void mapWithAllStringValues() {
	Map<String, Object> map = new HashMap<String, Object>();
	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 #30
Source File: SpelReproTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void SPR9486_floatLessThanDouble() {
	Boolean expectedNumber = -10.21f < -10.2;
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	Expression expression = parser.parseExpression("-10.21f < -10.2");
	Boolean result = expression.getValue(context, null, Boolean.class);
	assertEquals(expectedNumber, result);
}