Java Code Examples for org.springframework.expression.Expression

The following examples show how to use org.springframework.expression.Expression. 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
Source Project: spring4-understanding   Source File: IndexingTests.java    License: 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 2
Source Project: spring4-understanding   Source File: SetValueTests.java    License: 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 3
Source Project: oneops   Source File: OfferingsMatcher.java    License: 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
/**
 * 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 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
@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 7
Source Project: java-technology-stack   Source File: MapAccessTests.java    License: 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 Project: spring-analysis-note   Source File: PropertyAccessTests.java    License: 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 9
Source Project: java-technology-stack   Source File: MethodInvocationTests.java    License: 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 10
Source Project: spring4-understanding   Source File: SpelReproTests.java    License: 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 11
/**
 * 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 12
Source Project: n2o-framework   Source File: DataSetMapper.java    License: 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 13
Source Project: spring-analysis-note   Source File: AbstractExpressionTests.java    License: 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 14
Source Project: docx-stamper   Source File: ProxyMethodHandlerTest.java    License: 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 15
/**
 * 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 16
/**
 * 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 17
Source Project: spring4-understanding   Source File: SpelReproTests.java    License: 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 18
@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 19
Source Project: java-technology-stack   Source File: SpelDocumentationTests.java    License: 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
@Test
public void mapWithNonStringValue() {
	Map<String, Object> map = new HashMap<String, Object>();
	map.put("x", "1");
	map.put("y", 2);
	map.put("z", "3");
	map.put("a", new UUID(1, 1));
	Expression expression = parser.parseExpression("foo(#props)");
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.setVariable("props", map);
	String result = expression.getValue(context, new TestBean(), String.class);
	assertEquals("1null3", result);
}
 
Example 21
Source Project: spring4-understanding   Source File: IndexingTests.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void resolveCollectionElementType() {
	listNotGeneric = new ArrayList(2);
	listNotGeneric.add(5);
	listNotGeneric.add(6);
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression("listNotGeneric");
	assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList<?>", expression.getValueTypeDescriptor(this).toString());
	assertEquals("5,6", expression.getValue(this, String.class));
}
 
Example 22
Source Project: spring-sync   Source File: PathToSpelTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void listIndex() {
	Expression expr = PathToSpEL.pathToExpression("/1/description");
	List<Todo> todos = new ArrayList<Todo>();
	todos.add(new Todo(1L, "A", false));
	todos.add(new Todo(2L, "B", false));
	todos.add(new Todo(3L, "C", false));
	assertEquals("B", (String) expr.getValue(todos));		
}
 
Example 23
Source Project: spring-analysis-note   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR12035() {
	ExpressionParser parser = new SpelExpressionParser();

	Expression expression1 = parser.parseExpression("list.?[ value>2 ].size()!=0");
	assertTrue(expression1.getValue(new BeanClass(new ListOf(1.1), new ListOf(2.2)), Boolean.class));

	Expression expression2 = parser.parseExpression("list.?[ T(java.lang.Math).abs(value) > 2 ].size()!=0");
	assertTrue(expression2.getValue(new BeanClass(new ListOf(1.1), new ListOf(-2.2)), Boolean.class));
}
 
Example 24
Source Project: spring-analysis-note   Source File: SpelReproTests.java    License: MIT License 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 25
Source Project: java-technology-stack   Source File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR9486_floatGreaterThanDouble() {
	Boolean expectedResult = -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(expectedResult, result);
}
 
Example 26
Source Project: spring4-understanding   Source File: SpelReproTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void SPR12502() {
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression("#root.getClass().getName()");
	assertEquals(UnnamedUser.class.getName(), expression.getValue(new UnnamedUser()));
	assertEquals(NamedUser.class.getName(), expression.getValue(new NamedUser()));
}
 
Example 27
Source Project: spring-analysis-note   Source File: CompositeStringExpression.java    License: MIT License 5 votes vote down vote up
@Override
public String getValue(EvaluationContext context, Object rootObject) throws EvaluationException {
	StringBuilder sb = new StringBuilder();
	for (Expression expression : this.expressions) {
		String value = expression.getValue(context, rootObject, String.class);
		if (value != null) {
			sb.append(value);
		}
	}
	return sb.toString();
}
 
Example 28
Source Project: spring4-understanding   Source File: PropertyAccessTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
// Adding a new property accessor just for a particular type
public void testAddingSpecificPropertyAccessor() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// Even though this property accessor is added after the reflection one, it specifically
	// names the String class as the type it is interested in so is chosen in preference to
	// any 'default' ones
	ctx.addPropertyAccessor(new StringyPropertyAccessor());
	Expression expr = parser.parseRaw("new String('hello').flibbles");
	Integer i = expr.getValue(ctx, Integer.class);
	assertEquals((int) i, 7);

	// The reflection one will be used for other properties...
	expr = parser.parseRaw("new String('hello').CASE_INSENSITIVE_ORDER");
	Object o = expr.getValue(ctx);
	assertNotNull(o);

	expr = parser.parseRaw("new String('hello').flibbles");
	expr.setValue(ctx, 99);
	i = expr.getValue(ctx, Integer.class);
	assertEquals((int) i, 99);

	// Cannot set it to a string value
	try {
		expr.setValue(ctx, "not allowed");
		fail("Should not have been allowed");
	} catch (EvaluationException e) {
		// success - message will be: EL1063E:(pos 20): A problem occurred whilst attempting to set the property
		// 'flibbles': 'Cannot set flibbles to an object of type 'class java.lang.String''
		// System.out.println(e.getMessage());
	}
}
 
Example 29
@Test
@SuppressWarnings("unchecked")
public void selectFirstItemInMap() {
	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("beige", colorsMap.keySet().iterator().next());
}
 
Example 30
@Test
public void selectLastItemInArray() 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(4, value);
}