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

The following examples show how to use org.springframework.expression.spel.support.StandardEvaluationContext#setRootObject() . 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: SpelDocumentationTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testTernary() throws Exception {
	String falseString = parser.parseExpression("false ? 'trueExp' : 'falseExp'").getValue(String.class);
	assertEquals("falseExp",falseString);

	StandardEvaluationContext societyContext = new StandardEvaluationContext();
	societyContext.setRootObject(new IEEE());


	parser.parseExpression("Name").setValue(societyContext, "IEEE");
	societyContext.setVariable("queryName", "Nikola Tesla");

	String expression = "isMember(#queryName)? #queryName + ' is a member of the ' "
			+ "+ Name + ' Society' : #queryName + ' is not a member of the ' + Name + ' Society'";

	String queryResultString = parser.parseExpression(expression).getValue(societyContext, String.class);
	assertEquals("Nikola Tesla is a member of the IEEE Society",queryResultString);
	// queryResultString = "Nikola Tesla is a member of the IEEE Society"
}
 
Example 2
Source File: IndexingTests.java    From spring4-understanding with Apache License 2.0 6 votes vote down vote up
@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 3
Source File: SpelDocumentationTests.java    From spring4-understanding with Apache License 2.0 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 4
Source File: ScenariosForSpringSecurity.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testScenario03_Arithmetic() throws Exception {
	SpelExpressionParser parser = new SpelExpressionParser();
	StandardEvaluationContext ctx = new StandardEvaluationContext();

	// Might be better with a as a variable although it would work as a property too...
	// Variable references using a '#'
	Expression expr = parser.parseRaw("(hasRole('SUPERVISOR') or (#a <  1.042)) and hasIpAddress('10.10.0.0/16')");

	Boolean value = null;

	ctx.setVariable("a",1.0d); // referenced as #a in the expression
	ctx.setRootObject(new Supervisor("Ben")); // so non-qualified references 'hasRole()' 'hasIpAddress()' are invoked against it
	value = expr.getValue(ctx,Boolean.class);
	assertTrue(value);

	ctx.setRootObject(new Manager("Luke"));
	ctx.setVariable("a",1.043d);
	value = expr.getValue(ctx,Boolean.class);
	assertFalse(value);
}
 
Example 5
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 6
Source File: ScenariosForSpringSecurity.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void testScenario01_Roles() throws Exception {
	try {
		SpelExpressionParser parser = new SpelExpressionParser();
		StandardEvaluationContext ctx = new StandardEvaluationContext();
		Expression expr = parser.parseRaw("hasAnyRole('MANAGER','TELLER')");

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

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

	}
	catch (EvaluationException ee) {
		ee.printStackTrace();
		fail("Unexpected SpelException: " + ee.getMessage());
	}
}
 
Example 7
Source File: IndexingTests.java    From spring-analysis-note with 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 8
Source File: SpelTest.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Test
	public void test(){
		StandardEvaluationContext elcontext = new StandardEvaluationContext();
		TestBean tb = new TestBean();
		tb.aaa = "cccc";
		Map map = LangUtils.asMap("ccc", "dddd");
//		map.put("tb", tb);
		map.put("map", LangUtils.asMap("ccc", "dddd", "tb", tb));
		elcontext.setVariables(map);
		elcontext.setRootObject(tb);
		Expression exp = parser.parseExpression("'bb{ccc}'");
		Object val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("bb{ccc}", val);
		
		exp = parser.parseExpression("#ccc");
		val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("dddd", val);
		
		exp = parser.parseExpression("#map['tb'].aaa");
		val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("cccc", val);
	}
 
Example 9
Source File: SpelTest.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Test
	public void test(){
		StandardEvaluationContext elcontext = new StandardEvaluationContext();
		TestBean tb = new TestBean();
		tb.aaa = "cccc";
		Map map = LangUtils.asMap("ccc", "dddd");
//		map.put("tb", tb);
		map.put("map", LangUtils.asMap("ccc", "dddd", "tb", tb));
		elcontext.setVariables(map);
		elcontext.setRootObject(tb);
		Expression exp = parser.parseExpression("'bb{ccc}'");
		Object val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("bb{ccc}", val);
		
		exp = parser.parseExpression("#ccc");
		val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("dddd", val);
		
		exp = parser.parseExpression("#map['tb'].aaa");
		val = (String)exp.getValue(elcontext, String.class);
		Assert.assertEquals("cccc", val);
	}
 
Example 10
Source File: IndexingTests.java    From java-technology-stack with 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 11
Source File: SpelTest.java    From onetwo with Apache License 2.0 6 votes vote down vote up
@Test
	public void test2(){
		StandardEvaluationContext elcontext = new StandardEvaluationContext();
		TestBean tb = new TestBean();
		tb.aaa = "cccc";
		Map map = LangUtils.asMap("ccc", "dddd", "userName", "testUser");
//		map.put("tb", tb);
		map.put("map", LangUtils.asMap("ccc", "dddd", "tb", tb));
		elcontext.setRootObject(map);
		Expression exp = parser.parseExpression("['ccc']");
		Object val = (String)exp.getValue(elcontext, String.class);
		System.out.println("val: " + val);
		Assert.assertEquals("dddd", val);

		elcontext.setVariables(map);
		elcontext.setRootObject(null);
		exp = parser.parseExpression("I am ${#userName}", PARSER_CONTEXT);
		val = (String)exp.getValue(elcontext, String.class);
		System.out.println("val: " + val);
		Assert.assertEquals("I am testUser", val);
	}
 
Example 12
Source File: ExpressionEvaluator.java    From oneops with Apache License 2.0 5 votes vote down vote up
private EvaluationContext getEvaluationContext(CmsWorkOrderBase woBase) {
	StandardEvaluationContext context = new StandardEvaluationContext();
	if (woBase instanceof CmsWorkOrder) {
		CmsRfcCISimple rfcSimple = cmsUtil.custRfcCI2RfcCISimple(((CmsWorkOrder)woBase).getRfcCi());
		context.setRootObject(rfcSimple);
	} else if (woBase instanceof CmsActionOrder) {
		CmsCISimple ciSimple = cmsUtil.custCI2CISimple(((CmsActionOrder)woBase).getCi(), CmsConstants.ATTR_VALUE_TYPE_DF, true);
		context.setRootObject(ciSimple);
	}
	return context;
}
 
Example 13
Source File: DeclarativeRoutingKeyAspect.java    From cloud-config with MIT License 5 votes vote down vote up
private String resolveRoutingValue(ProceedingJoinPoint jp, String routingValue) throws Exception {
    String resolvedValue = stringValueResolver.resolveStringValue(routingValue).trim();
    Matcher matcher = pattern.matcher(resolvedValue);
    if(matcher.find()) {
        // prepare execution context
        StandardEvaluationContext simpleContext = new StandardEvaluationContext();
        simpleContext.setRootObject(jp.getTarget()); // or getThis?
        simpleContext.setVariable("args", jp.getArgs());

        MethodSignature signature = (MethodSignature) jp.getSignature();
        Method method = signature.getMethod();
        Annotation[][] annotations = method.getParameterAnnotations();
        for(int i=0; i<annotations.length; i++) {
            if(annotations[i]==null || annotations[i].length==0) continue;
            RoutingVariable routingParam = null;
            for(Annotation annotation : annotations[i]) {
                if(annotation.annotationType() == RoutingVariable.class) {
                    routingParam = (RoutingVariable) annotation;
                    break;
                }
            }
            if(routingParam!=null) {
                simpleContext.setVariable(routingParam.value(), jp.getArgs()[i]);
            }
        }
        String elExpr = matcher.group(1);
        resolvedValue = expressionCache.get(elExpr).getValue(simpleContext, String.class);
    }
    return resolvedValue;
}
 
Example 14
Source File: SpelDocumentationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void testSelection() throws Exception {
	StandardEvaluationContext societyContext = new StandardEvaluationContext();
	societyContext.setRootObject(new IEEE());
	List<Inventor> list = (List<Inventor>) parser.parseExpression("Members2.?[nationality == 'Serbian']").getValue(societyContext);
	assertEquals(1,list.size());
	assertEquals("Nikola Tesla",list.get(0).getName());
}
 
Example 15
Source File: SpelDocumentationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testAssignment() throws Exception {
	Inventor inventor = new Inventor();
	StandardEvaluationContext inventorContext = new StandardEvaluationContext();
	inventorContext.setRootObject(inventor);

	parser.parseExpression("foo").setValue(inventorContext, "Alexander Seovic2");

	assertEquals("Alexander Seovic2",parser.parseExpression("foo").getValue(inventorContext,String.class));
	// alternatively

	String aleks = parser.parseExpression("foo = 'Alexandar Seovic'").getValue(inventorContext, String.class);
	assertEquals("Alexandar Seovic",parser.parseExpression("foo").getValue(inventorContext,String.class));
	assertEquals("Alexandar Seovic",aleks);
}
 
Example 16
Source File: SpelDocumentationTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void testLogicalOperators() throws Exception {

	StandardEvaluationContext societyContext = new StandardEvaluationContext();
	societyContext.setRootObject(new IEEE());

	// -- AND --

	// evaluates to false
	boolean falseValue = parser.parseExpression("true and false").getValue(Boolean.class);
	assertFalse(falseValue);
	// evaluates to true
	String expression =  "isMember('Nikola Tesla') and isMember('Mihajlo Pupin')";
	boolean trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);

	// -- OR --

	// evaluates to true
	trueValue = parser.parseExpression("true or false").getValue(Boolean.class);
	assertTrue(trueValue);

	// evaluates to true
	expression =  "isMember('Nikola Tesla') or isMember('Albert Einstien')";
	trueValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
	assertTrue(trueValue);

	// -- NOT --

	// evaluates to false
	falseValue = parser.parseExpression("!true").getValue(Boolean.class);
	assertFalse(falseValue);


	// -- AND and NOT --
	expression =  "isMember('Nikola Tesla') and !isMember('Mihajlo Pupin')";
	falseValue = parser.parseExpression(expression).getValue(societyContext, Boolean.class);
	assertFalse(falseValue);
}
 
Example 17
Source File: SpelDocumentationTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void testEqualityCheck() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();

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

	Expression exp = parser.parseExpression("name == 'Nikola Tesla'");
	boolean isEqual = exp.getValue(context, Boolean.class);  // evaluates to true
	assertTrue(isEqual);
}
 
Example 18
Source File: SpelDocumentationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testConstructors() throws Exception {
	StandardEvaluationContext societyContext = new StandardEvaluationContext();
	societyContext.setRootObject(new IEEE());
	Inventor einstein =
		   parser.parseExpression("new org.springframework.expression.spel.testresources.Inventor('Albert Einstein',new java.util.Date(), 'German')").getValue(Inventor.class);
	assertEquals("Albert Einstein", einstein.getName());
	//create new inventor instance within add method of List
	parser.parseExpression("Members2.add(new org.springframework.expression.spel.testresources.Inventor('Albert Einstein', 'German'))").getValue(societyContext);
}
 
Example 19
Source File: SpelDocumentationTests.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Test
public void testEqualityCheck() throws Exception {
	ExpressionParser parser = new SpelExpressionParser();

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

	Expression exp = parser.parseExpression("name == 'Nikola Tesla'");
	boolean isEqual = exp.getValue(context, Boolean.class);  // evaluates to true
	assertTrue(isEqual);
}
 
Example 20
Source File: ExpressionLanguageScenarioTests.java    From spring-analysis-note with MIT License 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);
}