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

The following examples show how to use org.springframework.expression.spel.support.StandardEvaluationContext#addPropertyAccessor() . 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
@Test
public void indexIntoGenericPropertyContainingMapObject() {
	Map<String, Map<String, String>> property = new HashMap<String, Map<String, String>>();
	Map<String, String> map =  new HashMap<String, String>();
	map.put("foo", "bar");
	property.put("property", map);
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new MapAccessor());
	context.setRootObject(property);
	Expression expression = parser.parseExpression("property");
	assertEquals("java.util.HashMap<?, ?>", expression.getValueTypeDescriptor(context).toString());
	assertEquals(map, expression.getValue(context));
	assertEquals(map, expression.getValue(context, Map.class));
	expression = parser.parseExpression("property['foo']");
	assertEquals("bar", expression.getValue(context));
}
 
Example 2
@Test
public void testAddingRemovingAccessors() {
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// reflective property accessor is the only one by default
	List<PropertyAccessor> propertyAccessors = ctx.getPropertyAccessors();
	assertEquals(1,propertyAccessors.size());

	StringyPropertyAccessor spa = new StringyPropertyAccessor();
	ctx.addPropertyAccessor(spa);
	assertEquals(2,ctx.getPropertyAccessors().size());

	List<PropertyAccessor> copy = new ArrayList<>();
	copy.addAll(ctx.getPropertyAccessors());
	assertTrue(ctx.removePropertyAccessor(spa));
	assertFalse(ctx.removePropertyAccessor(spa));
	assertEquals(1,ctx.getPropertyAccessors().size());

	ctx.setPropertyAccessors(copy);
	assertEquals(2,ctx.getPropertyAccessors().size());
}
 
Example 3
Source Project: java-technology-stack   File: IndexingTests.java    License: MIT License 6 votes vote down vote up
@Test
public void indexIntoGenericPropertyContainingMapObject() {
	Map<String, Map<String, String>> property = new HashMap<>();
	Map<String, String> map = new HashMap<>();
	map.put("foo", "bar");
	property.put("property", map);
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext context = new StandardEvaluationContext();
	context.addPropertyAccessor(new MapAccessor());
	context.setRootObject(property);
	Expression expression = parser.parseExpression("property");
	assertEquals("java.util.HashMap<?, ?>", expression.getValueTypeDescriptor(context).toString());
	assertEquals(map, expression.getValue(context));
	assertEquals(map, expression.getValue(context, Map.class));
	expression = parser.parseExpression("property['foo']");
	assertEquals("bar", expression.getValue(context));
}
 
Example 4
@Override
public boolean evaluateConditional(String conditionalExpression, Map<String, Object> evaluationContext) {
    Optional.ofNullable(conditionalExpression)
            .filter(template -> !template.isEmpty())
            .orElseThrow(() -> new IllegalArgumentException("Conditional expression cannot be null or empty"));

    Optional.ofNullable(evaluationContext)
            .orElseThrow(() -> new IllegalArgumentException("Evaluation context cannot be null"));

    Expression expression = new SpelExpressionParser().parseExpression(conditionalExpression);

    StandardEvaluationContext standardEvaluationContext = new StandardEvaluationContext();
    standardEvaluationContext.addPropertyAccessor(new MapAccessor());
    standardEvaluationContext.setVariables(evaluationContext);

    return expression.getValue(standardEvaluationContext,Boolean.class);
}
 
Example 5
/**
 * 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 6
private QueryMethodEvaluationContextProvider delegateContextProvider(
		QueryMethodEvaluationContextProvider evaluationContextProvider) {
	return new QueryMethodEvaluationContextProvider() {
		@Override
		public <T extends Parameters<?, ?>> EvaluationContext getEvaluationContext(
				T parameters, Object[] parameterValues) {
			StandardEvaluationContext evaluationContext = (StandardEvaluationContext) evaluationContextProvider
					.getEvaluationContext(parameters, parameterValues);
			evaluationContext
					.setRootObject(SpannerRepositoryFactory.this.applicationContext);
			evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());
			evaluationContext.setBeanResolver(new BeanFactoryResolver(
					SpannerRepositoryFactory.this.applicationContext));
			return evaluationContext;
		}
	};
}
 
Example 7
@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 8
Source Project: spring-analysis-note   File: MapAccessorTests.java    License: MIT License 5 votes vote down vote up
@Test
public void mapAccessorCompilable() {
	Map<String, Object> testMap = getSimpleTestMap();
	StandardEvaluationContext sec = new StandardEvaluationContext();
	sec.addPropertyAccessor(new MapAccessor());
	SpelExpressionParser sep = new SpelExpressionParser();

	// basic
	Expression ex = sep.parseExpression("foo");
	assertEquals("bar",ex.getValue(sec,testMap));
	assertTrue(SpelCompiler.compile(ex));
	assertEquals("bar",ex.getValue(sec,testMap));

	// compound expression
	ex = sep.parseExpression("foo.toUpperCase()");
	assertEquals("BAR",ex.getValue(sec,testMap));
	assertTrue(SpelCompiler.compile(ex));
	assertEquals("BAR",ex.getValue(sec,testMap));

	// nested map
	Map<String,Map<String,Object>> nestedMap = getNestedTestMap();
	ex = sep.parseExpression("aaa.foo.toUpperCase()");
	assertEquals("BAR",ex.getValue(sec,nestedMap));
	assertTrue(SpelCompiler.compile(ex));
	assertEquals("BAR",ex.getValue(sec,nestedMap));

	// avoiding inserting checkcast because first part of expression returns a Map
	ex = sep.parseExpression("getMap().foo");
	MapGetter mapGetter = new MapGetter();
	assertEquals("bar",ex.getValue(sec,mapGetter));
	assertTrue(SpelCompiler.compile(ex));
	assertEquals("bar",ex.getValue(sec,mapGetter));
}
 
Example 9
@Test
// Adding a new property accessor just for a particular type
public void testAddingSpecificPropertyAccessor() {
	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(7, (int) i);

	// 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(99, (int) i);

	// Cannot set it to a string value
	try {
		expr.setValue(ctx, "not allowed");
		fail("Should not have been allowed");
	}
	catch (EvaluationException ex) {
		// 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 10
Source Project: spring-analysis-note   File: MapAccessTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testCustomMapAccessor() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = TestScenarioCreator.getTestEvaluationContext();
	ctx.addPropertyAccessor(new MapAccessor());

	Expression expr = parser.parseExpression("testMap.monday");
	Object value = expr.getValue(ctx, String.class);
	assertEquals("montag", value);
}
 
Example 11
Source Project: spring-analysis-note   File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR5804() {
	Map<String, String> m = new HashMap<>();
	m.put("foo", "bar");
	StandardEvaluationContext context = new StandardEvaluationContext(m);  // root is a map instance
	context.addPropertyAccessor(new MapAccessor());
	Expression expr = new SpelExpressionParser().parseRaw("['foo']");
	assertEquals("bar", expr.getValue(context));
}
 
Example 12
Source Project: java-technology-stack   File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR5804() {
	Map<String, String> m = new HashMap<>();
	m.put("foo", "bar");
	StandardEvaluationContext context = new StandardEvaluationContext(m);  // root is a map instance
	context.addPropertyAccessor(new MapAccessor());
	Expression expr = new SpelExpressionParser().parseRaw("['foo']");
	assertEquals("bar", expr.getValue(context));
}
 
Example 13
@Test
public void testScenario02_ComparingNames() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	ctx.addPropertyAccessor(new SecurityPrincipalAccessor());

	// Multiple options for supporting this expression: "p.name == principal.name"
	// (1) If the right person is the root context object then "name==principal.name" is good enough
	Expression expr = parser.parseRaw("name == principal.name");

	ctx.setRootObject(new Person("Andy"));
	Boolean value = expr.getValue(ctx,Boolean.class);
	assertTrue(value);

	ctx.setRootObject(new Person("Christian"));
	value = expr.getValue(ctx,Boolean.class);
	assertFalse(value);

	// (2) Or register an accessor that can understand 'p' and return the right person
	expr = parser.parseRaw("p.name == principal.name");

	PersonAccessor pAccessor = new PersonAccessor();
	ctx.addPropertyAccessor(pAccessor);
	ctx.setRootObject(null);

	pAccessor.setPerson(new Person("Andy"));
	value = expr.getValue(ctx,Boolean.class);
	assertTrue(value);

	pAccessor.setPerson(new Person("Christian"));
	value = expr.getValue(ctx,Boolean.class);
	assertFalse(value);
}
 
Example 14
@Test
public void mapAccessorCompilable() {
	Map<String, Object> testMap = getSimpleTestMap();
	StandardEvaluationContext sec = new StandardEvaluationContext();		
	sec.addPropertyAccessor(new MapAccessor());
	SpelExpressionParser sep = new SpelExpressionParser();
	
	// basic
	Expression ex = sep.parseExpression("foo");
	assertEquals("bar",ex.getValue(sec,testMap));
	assertTrue(SpelCompiler.compile(ex));		
	assertEquals("bar",ex.getValue(sec,testMap));

	// compound expression
	ex = sep.parseExpression("foo.toUpperCase()");
	assertEquals("BAR",ex.getValue(sec,testMap));
	assertTrue(SpelCompiler.compile(ex));		
	assertEquals("BAR",ex.getValue(sec,testMap));
	
	// nested map
	Map<String,Map<String,Object>> nestedMap = getNestedTestMap();
	ex = sep.parseExpression("aaa.foo.toUpperCase()");
	assertEquals("BAR",ex.getValue(sec,nestedMap));
	assertTrue(SpelCompiler.compile(ex));		
	assertEquals("BAR",ex.getValue(sec,nestedMap));
	
	// avoiding inserting checkcast because first part of expression returns a Map
	ex = sep.parseExpression("getMap().foo");
	MapGetter mapGetter = new MapGetter();
	assertEquals("bar",ex.getValue(sec,mapGetter));
	assertTrue(SpelCompiler.compile(ex));		
	assertEquals("bar",ex.getValue(sec,mapGetter));
}
 
Example 15
@Test
public void SPR5804() throws Exception {
	Map<String, String> m = new HashMap<String, String>();
	m.put("foo", "bar");
	StandardEvaluationContext eContext = new StandardEvaluationContext(m); // root is a map instance
	eContext.addPropertyAccessor(new MapAccessor());
	Expression expr = new SpelExpressionParser().parseRaw("['foo']");
	assertEquals("bar", expr.getValue(eContext));
}
 
Example 16
Source Project: java-technology-stack   File: MapAccessTests.java    License: MIT License 5 votes vote down vote up
@Test
public void testCustomMapAccessor() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = TestScenarioCreator.getTestEvaluationContext();
	ctx.addPropertyAccessor(new MapAccessor());

	Expression expr = parser.parseExpression("testMap.monday");
	Object value = expr.getValue(ctx, String.class);
	assertEquals("montag", value);
}
 
Example 17
Source Project: java-technology-stack   File: SpelReproTests.java    License: MIT License 5 votes vote down vote up
@Test
public void SPR5847() {
	StandardEvaluationContext context = new StandardEvaluationContext(new TestProperties());
	String name = null;
	Expression expr = null;

	expr = new SpelExpressionParser().parseRaw("jdbcProperties['username']");
	name = expr.getValue(context, String.class);
	assertEquals("Dave", name);

	expr = new SpelExpressionParser().parseRaw("jdbcProperties[username]");
	name = expr.getValue(context, String.class);
	assertEquals("Dave", name);

	// MapAccessor required for this to work
	expr = new SpelExpressionParser().parseRaw("jdbcProperties.username");
	context.addPropertyAccessor(new MapAccessor());
	name = expr.getValue(context, String.class);
	assertEquals("Dave", name);

	// --- dotted property names

	// lookup foo on the root, then bar on that, then use that as the key into
	// jdbcProperties
	expr = new SpelExpressionParser().parseRaw("jdbcProperties[foo.bar]");
	context.addPropertyAccessor(new MapAccessor());
	name = expr.getValue(context, String.class);
	assertEquals("Dave2", name);

	// key is foo.bar
	expr = new SpelExpressionParser().parseRaw("jdbcProperties['foo.bar']");
	context.addPropertyAccessor(new MapAccessor());
	name = expr.getValue(context, String.class);
	assertEquals("Elephant", name);
}
 
Example 18
@Test
public void SPR11609() {
	StandardEvaluationContext sec = new StandardEvaluationContext();
	sec.addPropertyAccessor(new MapAccessor());
	Expression exp = new SpelExpressionParser().parseExpression(
			"T(org.springframework.expression.spel.SpelReproTests$MapWithConstant).X");
	assertEquals(1, exp.getValue(sec));
}
 
Example 19
Source Project: Moss   File: LetsChatNotifier.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
protected String getText(InstanceEvent event, Instance instance) {
    Map<String, Object> root = new HashMap<>();
    root.put("event", event);
    root.put("instance", instance);
    root.put("lastStatus", getLastStatus(event.getInstance()));
    StandardEvaluationContext context = new StandardEvaluationContext(root);
    context.addPropertyAccessor(new MapAccessor());
    return message.getValue(context, String.class);
}
 
Example 20
/**
 * Creates a new instance with {@link StandardEvaluationContext} including
 * {@link org.springframework.expression.spel.support.ReflectivePropertyAccessor ReflectivePropertyAccessor}
 * and {@link MapAccessor}.
 */
public SpelMessageInterpolator() {
    StandardEvaluationContext ctx = new StandardEvaluationContext();
    ctx.addPropertyAccessor(new MapAccessor());
    this.evalContext = ctx;
}