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

The following examples show how to use org.springframework.expression.Expression#setValue() . 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: EvaluationTests.java    From java-technology-stack with MIT License 8 votes vote down vote up
/**
 * SPR-6984: attempting to index a collection on write using an index that
 * doesn't currently exist in the collection (address.crossStreets[0] below)
 */
@Test
public void initializingCollectionElementsOnWrite() {
	TestPerson person = new TestPerson();
	EvaluationContext context = new StandardEvaluationContext(person);
	SpelParserConfiguration config = new SpelParserConfiguration(true, true);
	ExpressionParser parser = new SpelExpressionParser(config);
	Expression e = parser.parseExpression("name");
	e.setValue(context, "Oleg");
	assertEquals("Oleg", person.getName());

	e = parser.parseExpression("address.street");
	e.setValue(context, "123 High St");
	assertEquals("123 High St", person.getAddress().getStreet());

	e = parser.parseExpression("address.crossStreets[0]");
	e.setValue(context, "Blah");
	assertEquals("Blah", person.getAddress().getCrossStreets().get(0));

	e = parser.parseExpression("address.crossStreets[3]");
	e.setValue(context, "Wibble");
	assertEquals("Blah", person.getAddress().getCrossStreets().get(0));
	assertEquals("Wibble", person.getAddress().getCrossStreets().get(3));
}
 
Example 2
Source File: SetValueTests.java    From java-technology-stack with MIT License 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 File: ExpressionLanguageScenarioTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void testScenario_AddingYourOwnPropertyResolvers_2() throws Exception {
	// Create a parser
	SpelExpressionParser parser = new SpelExpressionParser();
	// Use the standard evaluation context
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	ctx.addPropertyAccessor(new VegetableColourAccessor());
	Expression expr = parser.parseRaw("pea");
	Object value = expr.getValue(ctx);
	assertEquals(Color.green, value);

	try {
		expr.setValue(ctx, Color.blue);
		fail("Should not be allowed to set peas to be blue !");
	}
	catch (SpelEvaluationException ee) {
		assertEquals(SpelMessage.PROPERTY_OR_FIELD_NOT_WRITABLE_ON_NULL, ee.getMessageCode());
	}
}
 
Example 4
Source File: SetValueTests.java    From java-technology-stack with MIT License 6 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 | ParseException ex) {
			ex.printStackTrace();
			fail("Unexpected Exception: " + ex.getMessage());
		}
	}
 
Example 5
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 6
Source File: SetValueTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
protected void setValue(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();
		assertTrue("Expression is not writeable but should be", e.isWritable(lContext));
		e.setValue(lContext, value);
		assertEquals("Retrieved value was not equal to set value", value, e.getValue(lContext,value.getClass()));
	}
	catch (EvaluationException | ParseException ex) {
		ex.printStackTrace();
		fail("Unexpected Exception: " + ex.getMessage());
	}
}
 
Example 7
Source File: SetValueTests.java    From spring-analysis-note with MIT License 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 8
Source File: EvaluationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
/**
 * SPR-6984: attempting to index a collection on write using an index that
 * doesn't currently exist in the collection (address.crossStreets[0] below)
 */
@Test
public void initializingCollectionElementsOnWrite() {
	TestPerson person = new TestPerson();
	EvaluationContext context = new StandardEvaluationContext(person);
	SpelParserConfiguration config = new SpelParserConfiguration(true, true);
	ExpressionParser parser = new SpelExpressionParser(config);
	Expression e = parser.parseExpression("name");
	e.setValue(context, "Oleg");
	assertEquals("Oleg", person.getName());

	e = parser.parseExpression("address.street");
	e.setValue(context, "123 High St");
	assertEquals("123 High St", person.getAddress().getStreet());

	e = parser.parseExpression("address.crossStreets[0]");
	e.setValue(context, "Blah");
	assertEquals("Blah", person.getAddress().getCrossStreets().get(0));

	e = parser.parseExpression("address.crossStreets[3]");
	e.setValue(context, "Wibble");
	assertEquals("Blah", person.getAddress().getCrossStreets().get(0));
	assertEquals("Wibble", person.getAddress().getCrossStreets().get(3));
}
 
Example 9
Source File: IndexingTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void setGenericPropertyContainingListAutogrow() {
	List<Integer> property = new ArrayList<>();
	this.property = property;
	SpelExpressionParser parser = new SpelExpressionParser(new SpelParserConfiguration(true, true));
	Expression expression = parser.parseExpression("property");
	assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList<?>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property, expression.getValue(this));
	expression = parser.parseExpression("property[0]");
	try {
		expression.setValue(this, "4");
	}
	catch (EvaluationException ex) {
		assertTrue(ex.getMessage().startsWith("EL1053E"));
	}
}
 
Example 10
Source File: EvaluationTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void limitCollectionGrowing() {
	TestClass instance = new TestClass();
	StandardEvaluationContext ctx = new StandardEvaluationContext(instance);
	SpelExpressionParser parser = new SpelExpressionParser( new SpelParserConfiguration(true, true, 3));
	Expression e = parser.parseExpression("foo[2]");
	e.setValue(ctx, "2");
	assertThat(instance.getFoo().size(), equalTo(3));
	e = parser.parseExpression("foo[3]");
	try {
		e.setValue(ctx, "3");
	}
	catch (SpelEvaluationException see) {
		assertEquals(SpelMessage.UNABLE_TO_GROW_COLLECTION, see.getMessageCode());
		assertThat(instance.getFoo().size(), equalTo(3));
	}
}
 
Example 11
Source File: IndexingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void setPropertyContainingList() {
	List<Integer> property = new ArrayList<>();
	property.add(3);
	this.parameterizedList = property;
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression("parameterizedList");
	assertEquals("java.util.ArrayList<java.lang.Integer>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property, expression.getValue(this));
	expression = parser.parseExpression("parameterizedList[0]");
	assertEquals(3, expression.getValue(this));
	expression.setValue(this, "4");
	assertEquals(4, expression.getValue(this));
}
 
Example 12
Source File: PropertyAccessTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@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 13
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 14
Source File: IndexingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void setPropertyContainingList() {
	List<Integer> property = new ArrayList<>();
	property.add(3);
	this.parameterizedList = property;
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression("parameterizedList");
	assertEquals("java.util.ArrayList<java.lang.Integer>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property, expression.getValue(this));
	expression = parser.parseExpression("parameterizedList[0]");
	assertEquals(3, expression.getValue(this));
	expression.setValue(this, "4");
	assertEquals(4, expression.getValue(this));
}
 
Example 15
Source File: IndexingTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void setGenericPropertyContainingList() {
	List<Integer> property = new ArrayList<>();
	property.add(3);
	this.property = property;
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression("property");
	assertEquals("@org.springframework.expression.spel.IndexingTests$FieldAnnotation java.util.ArrayList<?>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property, expression.getValue(this));
	expression = parser.parseExpression("property[0]");
	assertEquals(3, expression.getValue(this));
	expression.setValue(this, "4");
	assertEquals("4", expression.getValue(this));
}
 
Example 16
Source File: IndexingTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void setPropertyContainingMap() {
	Map<Integer, Integer> property = new HashMap<>();
	property.put(9, 3);
	this.parameterizedMap = property;
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression("parameterizedMap");
	assertEquals("java.util.HashMap<java.lang.Integer, java.lang.Integer>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property, expression.getValue(this));
	expression = parser.parseExpression("parameterizedMap['9']");
	assertEquals(3, expression.getValue(this));
	expression.setValue(this, "37");
	assertEquals(37, expression.getValue(this));
}
 
Example 17
Source File: IndexingTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void setPropertyContainingMap() {
	Map<Integer, Integer> property = new HashMap<Integer, Integer>();
	property.put(9, 3);
	this.parameterizedMap = property;
	SpelExpressionParser parser = new SpelExpressionParser();
	Expression expression = parser.parseExpression("parameterizedMap");
	assertEquals("java.util.HashMap<java.lang.Integer, java.lang.Integer>", expression.getValueTypeDescriptor(this).toString());
	assertEquals(property, expression.getValue(this));
	expression = parser.parseExpression("parameterizedMap['9']");
	assertEquals(3, expression.getValue(this));
	expression.setValue(this, "37");
	assertEquals(37, expression.getValue(this));
}
 
Example 18
Source File: ExpressionLanguageScenarioTests.java    From spring4-understanding with Apache License 2.0 4 votes vote down vote up
/**
 * Scenario: using your own root context object
 */
@Test
public void testScenario_UsingADifferentRootContextObject() throws Exception {
	// Create a parser
	SpelExpressionParser parser = new SpelExpressionParser();
	// Use the standard evaluation context
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	TestClass tc = new TestClass();
	tc.setProperty(42);
	tc.str = "wibble";
	ctx.setRootObject(tc);

	// read it, set it, read it again
	Expression expr = parser.parseRaw("str");
	Object value = expr.getValue(ctx);
	assertEquals("wibble", value);
	expr = parser.parseRaw("str");
	expr.setValue(ctx, "wobble");
	expr = parser.parseRaw("str");
	value = expr.getValue(ctx);
	assertEquals("wobble", value);
	// or using assignment within the expression
	expr = parser.parseRaw("str='wabble'");
	value = expr.getValue(ctx);
	expr = parser.parseRaw("str");
	value = expr.getValue(ctx);
	assertEquals("wabble", value);

	// private property will be accessed through getter()
	expr = parser.parseRaw("property");
	value = expr.getValue(ctx);
	assertEquals(42, value);

	// ... and set through setter
	expr = parser.parseRaw("property=4");
	value = expr.getValue(ctx);
	expr = parser.parseRaw("property");
	value = expr.getValue(ctx);
	assertEquals(4,value);
}
 
Example 19
Source File: JavaInvocationEngine.java    From n2o-framework with Apache License 2.0 4 votes vote down vote up
private static void set(Object val, String field, Object obj) {
    Expression expression = writeParser.parseExpression(field);
    if (val != null) expression.setValue(obj, val);
}
 
Example 20
Source File: MappingProcessor.java    From n2o-framework with Apache License 2.0 2 votes vote down vote up
/**
 * Входящее преобразование value согласно выражению mapping в объект target
 *
 * @param target  результирующий объект
 * @param mapping выражение преобразования
 * @param value   значение
 */
public static void inMap(Object target, String mapping, Object value) {
    Expression expression = writeParser.parseExpression(mapping);
    if (target != null) expression.setValue(target, value);
}